package com.bonus.sgzb.material.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.bonus.sgzb.base.api.domain.*;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.material.domain.*;
import com.bonus.sgzb.material.mapper.*;
import com.bonus.sgzb.material.service.IPurchaseCheckInfoService;
import com.bonus.sgzb.material.service.IPurchaseMacodeInfoService;
import com.bonus.sgzb.common.core.utils.DateUtils;
import com.bonus.sgzb.material.vo.GlobalContants;
import com.bonus.sgzb.base.api.domain.MaInputVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 新购验收编号管理Service业务层处理
 *
 * @author bonus
 * @date 2023-12-10
 */
@Service
@Slf4j
public class PurchaseMacodeInfoServiceImpl implements IPurchaseMacodeInfoService {

    @Resource
    private PurchaseMacodeInfoMapper purchaseMacodeInfoMapper;

    @Resource
    private TaskMapper taskMapper;

    @Autowired
    private IPurchaseCheckInfoService purchaseCheckInfoService;

    @Resource
    private BmQrcodeInfoMapper qrcodeInfoMapper;

    @Resource
    private PurchaseCheckDetailsMapper checkDetailsMapper;


    /**
     * 查询新购验收编号管理
     *
     * @param taskId 新购验收编号管理主键
     * @return 新购验收编号管理
     */
    @Override
    public PurchaseMacodeInfo selectPurchaseMacodeInfoByTaskId(Long taskId) {
        return purchaseMacodeInfoMapper.selectPurchaseMacodeInfoByTaskId(taskId);
    }

    /**
     * 查询新购验收编号管理列表
     *
     * @param purchaseMacodeInfo 新购验收编号管理
     * @return 新购验收编号管理
     */
    @Override
    public List<PurchaseMacodeInfo> selectPurchaseMacodeInfoList(PurchaseMacodeInfo purchaseMacodeInfo) {
        List<PurchaseMacodeInfo> purchaseMacodeInfoList = purchaseMacodeInfoMapper.selectPurchaseMacodeInfoList(purchaseMacodeInfo);
        //判断有没有绑定固定资产
        if (purchaseMacodeInfoList.size() > 0/* && purchaseMacodeInfoList.get(0).getFixCode()!=null*/) {
            Map<Object, Long> groupCounts = purchaseMacodeInfoList.stream().map(PurchaseMacodeInfo::getTypeId).collect(Collectors.groupingBy(String::valueOf, Collectors.counting()));
            // 根据 typeId 进行去重
            purchaseMacodeInfoList = purchaseMacodeInfoList.stream()
                    // 指定键为 typeId
                    .collect(Collectors.toMap(PurchaseMacodeInfo::getTypeId,
                            // 指定值为对象本身
                            maCodeInfo -> maCodeInfo,
                            // 如果存在重复的 typeId，则保留已存在的对象
                            (existing, replacement) -> existing))
                    .values().stream().collect(Collectors.toList());
            //遍历purchaseMaCodeInfoList集合，非空判断取值
            purchaseMacodeInfoList.stream()
                    .forEach(purchaseMaCodeInfo1 -> {
                        Optional.ofNullable(groupCounts.get(String.valueOf(purchaseMaCodeInfo1.getFixCode())))
                                .ifPresent(count -> purchaseMaCodeInfo1.setBindNum(count.intValue()));
                    });
        }
        //根据fixCode固定资产编号判断是否绑定，未绑定，绑定数量设置为0
        for (PurchaseMacodeInfo maCodeInfo : purchaseMacodeInfoList) {
            if (maCodeInfo.getFixCode() == null) {
                maCodeInfo.setBindNum(0);
            }
        }
        return purchaseMacodeInfoList;
    }

    @Override
    public List<PurchaseMacodeInfo> selectPurchaseMacodeInfoListDetails(PurchaseMacodeInfo purchaseMacodeInfo) {
        List<PurchaseMacodeInfo> purchaseMacodeInfoList = purchaseMacodeInfoMapper.selectPurchaseMacodeInfoListDetails(purchaseMacodeInfo);
        return purchaseMacodeInfoList;
    }

    /**
     * 新增新购验收编号管理
     *
     * @param purchaseMacodeInfoList 新购验收编号管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertPurchaseMacodeInfo(List<PurchaseMacodeInfo> purchaseMacodeInfoList) throws Exception {
        boolean b = true;
        for (PurchaseMacodeInfo purchaseMacodeInfo : purchaseMacodeInfoList) {
            int i = purchaseMacodeInfoMapper.selectMaCode(purchaseMacodeInfo.getMaCode());
            if (i > 0) {
                purchaseMacodeInfo.setStatusFlag(1);
                purchaseMacodeInfo.setMaCode(null);
                b = false;
            } else {
                purchaseMacodeInfo.setStatusFlag(0);
            }
        }
        if (!b) {
            return AjaxResult.success(purchaseMacodeInfoList);
        }
        PurchaseCheckDetails purchaseCheckDetails = new PurchaseCheckDetails();
        for (PurchaseMacodeInfo purchaseMacodeInfo : purchaseMacodeInfoList) {
            Long taskId = purchaseMacodeInfo.getTaskId();
            TmTask task = taskMapper.selectTmTaskByTaskId(taskId);
            Long typeId = purchaseMacodeInfo.getTypeId();
            String maCode = purchaseMacodeInfo.getMaCode();
            purchaseCheckDetails.setTypeId(typeId);
            purchaseCheckDetails.setTaskId(purchaseMacodeInfo.getTaskId());

            MaMachineLabel maLabel = new MaMachineLabel();
            String qrCode = generateEquipmentNumber(maLabel);

            if (StringUtils.isNotEmpty(maCode)) {
                MaMachine maMachine = new MaMachine();
                maMachine.setTypeId(typeId);
                maMachine.setMaStatus("14");
                maMachine.setQrCode(qrCode);
                maMachine.setBuyTask(task.getCode());
                // 设备原厂编号
                String fixCode = purchaseMacodeInfo.getFixCode();
                if ("0".equals(fixCode)) {
                    MaMachine machine = purchaseMacodeInfoMapper.selectMachineByAssetsCode(purchaseMacodeInfo.getAssetsCode());
                    if (machine != null) {
                        throw new Exception("固定资产编号已存在");
                    }
                    maMachine.setAssetsCode(purchaseMacodeInfo.getAssetsCode());
                }
                maMachine.setMaCode(maCode);
                maMachine.setCreateTime(new Date());
                maMachine.setCreateBy(SecurityUtils.getUsername());
                purchaseMacodeInfoMapper.maMachineAdd(maMachine);

                // 标签绑定
                maLabel.setIsBind("1");
                maLabel.setLabelCode(qrCode);
                maLabel.setMaId(maMachine.getMaId());
                maLabel.setCreateTime(new Date());
                maLabel.setLabelType(9L);
                purchaseMacodeInfoMapper.insertMaMachineLabel(maLabel);

                MaLabelBind maLabelBind = new MaLabelBind();
                maLabelBind.setStatus("1");
                maLabelBind.setIsBind("1");
                maLabelBind.setLabelCode(qrCode);
                maLabelBind.setMaId(maMachine.getMaId());
                maLabelBind.setTypeId(typeId);
                maLabelBind.setBindTime(new Date());
                maLabelBind.setLabelType(9);
                maLabelBind.setBinder(SecurityUtils.getLoginUser().getUserid().toString());
                purchaseMacodeInfoMapper.insertMaLabelBind(maLabelBind);

            }

            purchaseMacodeInfo.setStatus("0");
            purchaseMacodeInfo.setCreateTime(DateUtils.getNowDate());
            purchaseMacodeInfoMapper.insertPurchaseMacodeInfo(purchaseMacodeInfo);
        }
        Integer bindNum = checkDetailsMapper.selectBindNumByTypeId(purchaseCheckDetails.getTypeId(), purchaseCheckDetails.getTaskId());
        // 添加绑定数量
        purchaseCheckDetails.setBindNum(bindNum + purchaseMacodeInfoList.size());
        purchaseCheckDetails.setUpdateTime(new Date());
        checkDetailsMapper.updateBindByTaskIdTypeId(purchaseCheckDetails);
        return AjaxResult.success(new ArrayList<PurchaseMacodeInfo>());
    }


    /**
     * 修改新购验收编号管理
     *
     * @param purchaseMacodeInfoList 新购验收编号管理
     * @return 结果
     */
    @Override
    public int updatePurchaseMacodeInfo(List<PurchaseMacodeInfo> purchaseMacodeInfoList) throws Exception {

        for (PurchaseMacodeInfo purchaseMacodeInfo : purchaseMacodeInfoList) {

            Long typeId = purchaseMacodeInfo.getTypeId();
            String maCode = purchaseMacodeInfo.getMaCode();

            if (StringUtils.isNotEmpty(maCode)) {
                MaMachine maMachine = new MaMachine();
                maMachine.setTypeId(typeId);
                maMachine.setMaStatus("14");
                maMachine.setQrCode(purchaseMacodeInfo.getQrCode());
                // 设备原厂编号
                String fixCode = purchaseMacodeInfo.getFixCode();
                if ("1".equals(fixCode)) {
                    MaMachine machine = purchaseMacodeInfoMapper.selectMachineByAssetsCode(fixCode);
                    if (machine != null) {
                        throw new Exception("固定资产编号已存在");
                    }
                    maMachine.setAssetsCode(fixCode);
                }
                maMachine.setMaCode(maCode);
                purchaseMacodeInfoMapper.maMachineAdd(maMachine);
            }
            String qrCode = purchaseMacodeInfo.getQrCode();
            // 二维码存储
            if (StringUtils.isNotEmpty(qrCode)) {
                BmQrcodeInfo bmQrcodeInfo = new BmQrcodeInfo();
                bmQrcodeInfo.setTypeId(typeId);
                bmQrcodeInfo.setQrCode(qrCode);
                bmQrcodeInfo.setTaskId(purchaseMacodeInfo.getTaskId());
                bmQrcodeInfo.setCreateTime(new Date());
                qrcodeInfoMapper.insertBmQrcodeInfo(bmQrcodeInfo);
            }
            // 修改新购机具编码
            purchaseMacodeInfo.setUpdateTime(DateUtils.getNowDate());
            purchaseMacodeInfoMapper.updatePurchaseMacodeInfo(purchaseMacodeInfo);
        }

        return 1;
    }

    /**
     * 批量删除新购验收编号管理
     *
     * @param taskIds 需要删除的新购验收编号管理主键
     * @return 结果
     */
    @Override
    public int deletePurchaseMacodeInfoByTaskIds(Long[] taskIds) {
        return purchaseMacodeInfoMapper.deletePurchaseMacodeInfoByTaskIds(taskIds);
    }

    /**
     * 删除新购验收编号管理信息
     *
     * @param taskId 新购验收编号管理主键
     * @return 结果
     */
    @Override
    public int deletePurchaseMacodeInfoByTaskId(Long taskId) {
        return purchaseMacodeInfoMapper.deletePurchaseMacodeInfoByTaskId(taskId);
    }

    /**
     * 生成设备编号
     *
     * @param maMachineLabel 类型id,生成数量
     * @return 编码结果
     */
    @Override
    public String generateEquipmentNumber(MaMachineLabel maMachineLabel) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Date nowDate = DateUtils.getNowDate();
        String format = dateFormat.format(nowDate);
        int lableNum = purchaseMacodeInfoMapper.selectLableNumByMonth(nowDate) + 1;
        String code = "";
        if (lableNum > GlobalContants.NUM1 && lableNum < GlobalContants.NUM2) {
            code = format + "-00" + lableNum;
        } else if (lableNum > GlobalContants.NUM3 && lableNum < GlobalContants.NUM4) {
            code = format + "-0" + lableNum;
        } else {
            code = format + "-000" + lableNum;
        }
        return code;
    }

    /**
     * 删除机具编码
     *
     * @param id 机具编码id
     * @return 结果
     */
    @Override
    public int deletePurchaseMacodeInfoById(Long id) {
        return purchaseMacodeInfoMapper.deletePurchaseMacodeInfoById(id);
    }

    /**
     * 新购入库审核
     * 通过/不通过
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int modifyManageStatus(MaInputVO maInputVO) {
        Long taskId = maInputVO.getTaskId();
        String checkResult = maInputVO.getCheckResult();
        List<MaInputRecord> inputRecordList = maInputVO.getInputRecordList();
        for (MaInputRecord maInputRecord : inputRecordList) {
            Long typeId = maInputRecord.getTypeId();
            // 修改机具入库状态
            MaMachine maMachine = new MaMachine();
            maMachine.setMaId(maInputRecord.getMaId());
            maMachine.setMaCode(maInputRecord.getMaCode());

            //修改编码管理表入库状态
            PurchaseMacodeInfo purchaseMacodeInfo = new PurchaseMacodeInfo();
            purchaseMacodeInfo.setTaskId(taskId);
            purchaseMacodeInfo.setTypeId(typeId);
            purchaseMacodeInfo.setMaCode(maInputRecord.getMaCode());

            // 修改验收任务详细表入库数量
            if ("1".equals(checkResult)) {
                //修改机具状态为在库
                maMachine.setMaStatus("15");
                purchaseMacodeInfoMapper.updateMaMachine(maMachine);


                // 修改编码管理的入库状态
                MaType maType = purchaseMacodeInfoMapper.selectTypeByTypeId(typeId);
                // 库存添加
                maType.setNum((maInputRecord.getInputNum() == null ? 0 : maInputRecord.getInputNum()) +
                        (maType.getNum() == null ? 0 : maType.getNum()));
                purchaseMacodeInfoMapper.updateTypeByTypeId(maType);

                if ("0".equals(maType.getManageType())) {  //编码设备
                    int countOfMachineByTypeId = purchaseMacodeInfoMapper.getCountOfMachineByTypeId(typeId);
                    maInputRecord.setNum(countOfMachineByTypeId);
                }

                //判断是否是成套机具，是的话配件库存也要增加
                if ("2".equals(maType.getManageType())) {
                    PurchaseCheckInfo purchaseCheckInfo = new PurchaseCheckInfo();
                    purchaseCheckInfo.setPurchaseNum(maInputRecord.getInputNum().toString());
                    purchaseCheckInfo.setTypeId(maInputRecord.getTypeId());
                    List<MachinePart> wholeSetDetails = purchaseCheckInfoService.getWholeSetDetails(purchaseCheckInfo);
                    for (MachinePart wholeSetDetail : wholeSetDetails) {
                        purchaseMacodeInfoMapper.updateMaTypeNum(wholeSetDetail);
                    }
                }

                int inputNum = checkDetailsMapper.selectInputNumByTypeId(taskId, typeId);
                PurchaseCheckDetails purchaseCheckDetails = new PurchaseCheckDetails();
                purchaseCheckDetails.setTaskId(taskId);
                purchaseCheckDetails.setTypeId(typeId);
                purchaseCheckDetails.setInputNum(inputNum + (maInputRecord.getInputNum() == null ? 0 : maInputRecord.getInputNum()));
                purchaseCheckDetails.setStatus(4);
                checkDetailsMapper.updateByTaskIdTypeId(purchaseCheckDetails);

                // 新增入库任务详细表
                InputApplyDetails applyDetails = new InputApplyDetails();
                applyDetails.setTaskId(taskId);
                applyDetails.setTypeId(typeId);
                applyDetails.setInputNum(maInputRecord.getInputNum() == null ? 0 : maInputRecord.getInputNum());
                applyDetails.setMaId(maInputRecord.getMaId());
                applyDetails.setInputType("1");
                applyDetails.setCreateTime(new Date());
                applyDetails.setCreateBy(SecurityUtils.getUsername());
                applyDetails.setCompanyId(maInputRecord.getCompanyId());
                purchaseMacodeInfoMapper.insertInputApplyDetails(applyDetails);

                purchaseMacodeInfo.setStatus("1");
                purchaseMacodeInfoMapper.updateMacodeByType(purchaseMacodeInfo);

                // 新增入库记录
                purchaseMacodeInfoMapper.insertMaInputRecord(maInputRecord);
            } else {
                //删除ma_machine表
                purchaseMacodeInfoMapper.deleteMaMachineInfoByMaId(maInputRecord.getMaId());
                //删除ma_machine_label表
                purchaseMacodeInfoMapper.deleteMaMachineLabelByMaId(maInputRecord.getMaId());
                //删除ma_label_bind表
                purchaseMacodeInfoMapper.deleteMaLabelBindByMaId(maInputRecord.getMaId());
                //修改purchase_macode_info表
                purchaseMacodeInfoMapper.updatetePurchaseMaCodeInfoByMaCodeAndTaskIdAndTypeId(taskId, typeId, maInputRecord.getMaCode());
                if ("1".equals(maInputRecord.getManageType())) {
                    //修改purchase_check_details表
                    checkDetailsMapper.updatePurchaseCheckDetailsByTaskId(taskId, typeId);
                }
            }
        }
        //判断是否全部已操作（通过或不通过）
        int count = purchaseMacodeInfoMapper.isOperateAll(taskId);
        if (count <= 0) {
            //获取该订单下所有的装备信息
            List<PurchaseCheckDetails> purchaseCheckDetailsList = checkDetailsMapper.selectPurchaseCheckDetailsByTaskId(taskId);
            //判断每种设备的验收数量和绑定数量一致
            for (PurchaseCheckDetails purchaseCheckDetails : purchaseCheckDetailsList) {
                if (StringUtils.isNotNull(purchaseCheckDetails.getBindNum())) {
                    if (purchaseCheckDetails.getCheckNum().compareTo(purchaseCheckDetails.getBindNum()) != 0) {
                        //全部操作以后如果还有未绑定的，则不改变状态
                        count = 1;
                    }
                }
            }
            if (count == 0) {
                //全部审核任务状态改为已审核
                TmTask task = new TmTask();
                task.setTaskId(taskId);
                task.setTaskStatus(28);
                task.setUpdateBy(String.valueOf(SecurityUtils.getLoginUser().getUserid()));
                task.setUpdateTime(DateUtils.getNowDate());
                taskMapper.updateTmTask(task);
            }
        }
        return 1;
    }

    private List<PurchaseMacodeInfo> selectPutinDetailsAddTypeId(PurchaseMacodeInfo purchaseMacodeInfo) {
        return purchaseMacodeInfoMapper.selectPutinDetailsAddTypeId(purchaseMacodeInfo);
    }


    /**
     * 根据机具编码删除编码
     *
     * @param maCode 机具编码
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deletePurchaseMacodeInfoByMaCode(String maCode) {
        purchaseMacodeInfoMapper.deleteMaMachineInfoByMaCode(maCode);
        return purchaseMacodeInfoMapper.deletePurchaseMacodeInfoByMaCode(maCode);
    }

    /**
     * 根据类型id和任务id查询编码详情
     *
     * @param purchaseMacodeInfo
     * @return 结果
     */
    @Override
    public List<PurchaseMacodeInfo> selectPurchaseMacodeInfo(PurchaseMacodeInfo purchaseMacodeInfo) {
        return purchaseMacodeInfoMapper.selectPurchaseMacodeInfo(purchaseMacodeInfo);
    }

    /**
     * 获取入库清单明细
     *
     * @param purchaseMacodeInfo 查询条件
     * @return 结果
     */
    @Override
    public List<PurchaseMacodeInfo> selectPutinDetails(PurchaseMacodeInfo purchaseMacodeInfo) {
        Long userid = SecurityUtils.getLoginUser().getUserid();
        purchaseMacodeInfo.setUserId(userid.toString());
        List<PurchaseMacodeInfo> purchaseMacodeInfos = purchaseMacodeInfoMapper.selectPutinDetails(purchaseMacodeInfo);
       /* for (PurchaseMacodeInfo macodeInfo : purchaseMacodeInfos) {
            List<String> userIds = purchaseMacodeInfoMapper.selectKeepUser(macodeInfo.getTypeId().intValue());
            userIds.add("1");
            macodeInfo.setUserIds(userIds);
        }*/
        return purchaseMacodeInfos;
    }

    @Override
    public List<PurchaseMacodeInfo> warehousingEntry(PurchaseMacodeInfo purchaseMacodeInfo) {
        return purchaseMacodeInfoMapper.warehousingEntry(purchaseMacodeInfo);
    }

}
