package com.junmp.jyzb.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.junmp.junmpProcess.mapper.OrgUserMapper;
import com.junmp.jyzb.api.bean.query.TestReq;
import com.junmp.jyzb.api.bean.query.hardWareReq.HardWareCabReq;
import com.junmp.jyzb.api.bean.query.processReq.PoliceEquipmentReq;
import com.junmp.jyzb.api.bean.req.PlanInitiationReq;
import com.junmp.jyzb.api.bean.vo.PlanOrgTypeVo;
import com.junmp.jyzb.api.exception.JYZBAppException;
import com.junmp.jyzb.api.exception.enums.OrderExceptionEnum;
import com.junmp.jyzb.cache.OutInRecordRedisCache;
import com.junmp.jyzb.entity.Inventory;
import com.junmp.jyzb.entity.PlanInitiation;
import com.junmp.jyzb.entity.PoliceEquipment;
import com.junmp.jyzb.entity.WarehouseInventory;
import com.junmp.jyzb.mapper.InventoryMapper;
import com.junmp.jyzb.service.*;
import com.junmp.jyzb.task.InvExpireMsg;
import com.junmp.v2.common.bean.response.ApiRes;
import com.junmp.v2.common.util.BeanPlusUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/api")
public class TestController {

    @Resource
    private TestService testService;
    @Resource
    private InventorySummaryService inventorySummaryService;

    @Resource
    private PoliceEquipmentService policeEquipmentService;

    @Resource
    private RabbitAdmin rabbitAdmin;
    @Resource
    private OrgUserMapper orgUserMapper;

    @Resource
    private PlanInitiationService planInitiationService;
    @Resource
    private PlanInitiationItemService planInitiationItemService;

    @Resource
    private InventoryService inventoryService;

    @Resource
    private OrderMainService orderMainService;

    @Resource
    private InventoryMapper inventoryMapper;

    @Resource
    private OutInRecordRedisCache outInRecordRedisCache;

    @Resource
    private InvExpireMsg invExpireMsg;


    /**
     * 不能删除!!!
     * @return
     */
    @PostMapping("/aaa")
    public ApiRes<Boolean> test(){
        return ApiRes.success(true);
    }

    //消息队列中是否有消费者
    @PostMapping("/hasConsumers")
    public ApiRes<Boolean> hasConsumers(@RequestBody TestReq req){
        Long execute = rabbitAdmin.getRabbitTemplate().execute(channel -> channel.consumerCount(req.getQueueName()));
        System.out.println("execute = " + execute);
        return ApiRes.success(execute>0L);
    }

    @PostMapping("addPoliceEqs")
    public ApiRes<Boolean> addPoliceEqs(@RequestBody PoliceEquipmentReq req){
        List<PoliceEquipment> collect = req.getList().stream().map(policeEquipmentReq -> {
            PoliceEquipment policeEquipment = new PoliceEquipment();
            BeanPlusUtil.copyProperties(policeEquipmentReq, policeEquipment);
            return policeEquipment;
        }).collect(Collectors.toList());
        return ApiRes.success(policeEquipmentService.saveBatch(collect));
    }

    @PostMapping("/action")
    public List<Inventory> action(@RequestBody HardWareCabReq req) {
//        inventorySummaryService.setWarrantyGroupAction();
        List<Inventory> invList = inventoryService.list(new LambdaQueryWrapper<Inventory>()
                .in(Inventory::getEpc, req.getRFIDList()));
        return invList;
    }

    @PostMapping("/bbbbb")
    public void aaa() {
        // 创建一个字典格式的数据
        Map<String, Object> dictionary = new HashMap<>();
        dictionary.put("key1", "value1");
        dictionary.put("key2", 123);
        dictionary.put("key3", true);

        // 返回字典格式的数据
        System.out.println(dictionary);


    }

    @PostMapping("/sss")
    public void sss(@RequestBody PlanInitiationReq req){
        PlanInitiation plan = planInitiationService.getById(req.getPlanId());
        if (ObjectUtil.isNull(plan)){
            throw new JYZBAppException(OrderExceptionEnum.ORDER_NOT_EXIST);
        }

        //将判断预案完成的数量是多少进行生成归还单
        List<PlanOrgTypeVo> dtoList = planInitiationItemService.getDetail(req);
        List<String> collect = dtoList.stream().map(PlanOrgTypeVo::getOrderId).distinct().collect(Collectors.toList());
        //校验该预案单生成的出库单是否存在尚未记账的,若存在,则不允许归还
        if (CollectionUtil.isNotEmpty(collect)){

            //将未记账的单子在dtoList中进行删除（未记账的领用出库单直接不需要进行归还操作）-- 或者记账数量全为0的单子
            dtoList = dtoList.stream().filter(dto -> !dto.getOrderId().equals("0")).collect(Collectors.toList());
            dtoList = dtoList.stream()
                    .collect(Collectors.groupingBy(PlanOrgTypeVo::getOrderId))  // 按 orderId 进行分组
                    .values().stream()  // 获取分组后的值
                    .flatMap(group -> group.stream()
                            .anyMatch(order -> order.getActualNum() != 0)  // 如果有 real_num 不为 0，则保留该组
                            ? group.stream() : group.stream().filter(order -> false))  // 否则过滤掉该组
                    .collect(Collectors.toList());
        }
        System.out.println("dtoList = " + dtoList);
    }


    @PostMapping("/abc")
    public void test1(){
        List<String> epcList=new ArrayList<>();
        epcList.add("1");
        epcList.add("21");
        epcList.add("133");
        boolean remove = inventoryService.remove(new LambdaUpdateWrapper<Inventory>().in(Inventory::getEpc, epcList));
        System.out.println("remove = " + remove);

        boolean result=inventoryService.update(new LambdaUpdateWrapper<Inventory>()
                .set(Inventory::getLocationId,"1")
                .set(Inventory::getLocationType,"1")
                .set(Inventory::getLocationState,"in")
                .in(Inventory::getEpc, epcList));
        System.out.println("result = " + result);

        boolean upresult=inventoryService.update(new LambdaUpdateWrapper<Inventory>()
                .set(Inventory::getLocationState,"out")
                .in(Inventory::getEpc, epcList));
        System.out.println("upresult = " + upresult);
    }



    @PostMapping("/rabbitTest")
    public void rabbitTest(){

        List<Inventory> objectList3 = outInRecordRedisCache.addInventory("addInvRecord:296d2287-7f54-4440-88e2-9867caf6af55");
        for (Inventory inventory:objectList3) {
            System.out.println("inventory = " + inventory);
        }


    }

    @PostMapping("/expireInventory")
    public void expireInventory(){
        invExpireMsg.action();
    }


}
