package com.junmp.jyzb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junmp.jyzb.api.bean.query.CabinetReq;
import com.junmp.jyzb.api.bean.req.UpdateCabinetBoxReq;
import com.junmp.jyzb.api.bean.req.UpdateCabinetReq;
import com.junmp.jyzb.entity.Cabinet;
import com.junmp.jyzb.entity.CabinetBox;
import com.junmp.jyzb.api.exception.enums.CabinetBoxExceptionEnum;
import com.junmp.jyzb.api.exception.enums.CabinetExceptionEnum;
import com.junmp.jyzb.entity.ES.Blog;
import com.junmp.jyzb.mapper.CabinetBoxMapper;
import com.junmp.jyzb.mapper.PoliceFingerMapper;
import com.junmp.jyzb.mapper.PolicemanMapper;
import com.junmp.jyzb.service.CabinetBoxService;
import com.junmp.jyzb.service.CabinetService;
import com.junmp.jyzb.utils.RabbitMQSendMsg;
import com.junmp.v2.common.exception.base.ServiceException;
import com.junmp.v2.common.util.BeanPlusUtil;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CabinetBoxServiceImpl extends ServiceImpl<CabinetBoxMapper, CabinetBox> implements CabinetBoxService {


    @Resource
    private CabinetService cabinetService;
    @Autowired
    private RabbitMQSendMsg MQ;


    //添加箱门信息
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String AddOrUpdateBoxInfo(UpdateCabinetReq req) {
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>()
                .eq(Cabinet::getCabinetNum, req.getSerialNum()));
        if (ObjectUtil.isNull(cabinet)) {
            throw new ServiceException(CabinetExceptionEnum.CABINET_ISNOT_EXISTS);
        }

        List<UpdateCabinetBoxReq> addList = req.getCabinetBoxList();
        List<CabinetBox> existingBoxes = list(new LambdaQueryWrapper<CabinetBox>()
                .eq(CabinetBox::getCabinetId, cabinet.getId()));

        Map<Integer, CabinetBox> existingBoxMap = existingBoxes.stream()
                .collect(Collectors.toMap(CabinetBox::getNum, Function.identity()));

        List<CabinetBox> boxListAdd = new ArrayList<>();

        for (UpdateCabinetBoxReq boxReq : addList) {
            CabinetBox box = new CabinetBox();
            box.setCabinetId(cabinet.getId());
            box.setPower(boxReq.getPower());
            box.setEquipmentConfig(boxReq.getEquipmentConfig());
            box.setContainType(boxReq.getContainType());
            box.setState(1);
            box.setBoxName(boxReq.getBoxName());
            box.setNum(boxReq.getNum());
            box.setUpdateTime(new Date());
            // 在内存中比较是否存在相同 SerialNum 和相同 num 的数据
            CabinetBox existingBox = existingBoxMap.get(boxReq.getNum());

            if (existingBox != null) {
                // 如果存在，则更新数据
                box.setId(existingBox.getId());
                updateById(box);
            } else {
                // 如果不存在，则新增数据
                Integer num = cabinet.getNum();//获取当前柜的总数量
                if (num == null) {
                    num = 0;
                }
                cabinet.setNum(num + addList.size());
                boxListAdd.add(box);
            }
        }




        cabinetService.updateById(cabinet);

        if (req.getActionFrom().equals("platform"))//请求来源于平台，则进行推送
        {
            MQ.SendMsg("cabinetMsg",req.getSerialNum(),"cabinetChange");
        }
        // 批量保存新增的数据
        saveBatch(boxListAdd);

        return cabinet.getId();
    }

    //删除箱门
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String DeleteBox(UpdateCabinetReq req) {
        Cabinet cabinet = cabinetService.getOne(new LambdaQueryWrapper<Cabinet>()
                .eq(Cabinet::getCabinetNum, req.getSerialNum()));
        if (ObjectUtil.isNull(cabinet)){
            throw new ServiceException(CabinetExceptionEnum.CABINET_ISNOT_EXISTS);
        }
        CabinetBox one = getOne(new LambdaQueryWrapper<CabinetBox>()
                .eq(CabinetBox::getCabinetId, cabinet.getId())
                .eq(CabinetBox::getId,req.getId()));
        if (ObjectUtil.isNotNull(one)){
            throw new ServiceException(CabinetBoxExceptionEnum.CABINETBOX_IS_EXISTS);
        }
        //添加单警柜箱门信息默认状态为0正常
        List<String> boxNumList = req.getNumList();
        remove(new LambdaQueryWrapper<CabinetBox>()
                .eq(CabinetBox::getCabinetId, cabinet.getId())
                .in(CabinetBox::getNum, boxNumList));

        // 更新 Cabinet 实体的 num 字段
        Integer cabinetNum = cabinet.getNum();
        if (cabinetNum != null) {
            cabinet.setNum(cabinetNum - boxNumList.size());
            cabinetService.updateById(cabinet);
        }
        if (req.getActionFrom().equals("platform"))//请求来源于平台，则进行推送
        {
            MQ.SendMsg("cabinetMsg",req.getSerialNum(),"cabinetChange");
        }
        return cabinet.getId();
    }
    //判断箱子信息是否存在
    @Override
    public CabinetBox CabinetBoxExist(String id) {
        CabinetBox cabinetBox = getById(id);
        if (ObjectUtil.isNull(cabinetBox)) {
            throw new ServiceException(CabinetBoxExceptionEnum.CABINETBOX_ISNOT_EXISTS);
        }
        return cabinetBox;
    }

}
