package com.aucma.api.service.impl;

import com.aucma.api.domain.dto.RepairSubmitInfoDto;
import com.aucma.api.mapper.PdaBindingMapper;
import com.aucma.api.service.IPdaBindingService;
import com.aucma.common.utils.SecurityUtils;
import com.aucma.common.utils.StringUtils;
import com.aucma.report.domain.RecordExceptionProcess;
import com.aucma.report.domain.RecordSwitchOrder;
import com.aucma.report.domain.ReportQualityInspection;
import com.aucma.report.mapper.ReportQualityInspectionMapper;
import com.aucma.report.service.IRecordExceptionProcessService;
import com.aucma.report.service.IRecordSwitchOrderService;
import com.aucma.system.service.ISysPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

import static com.aucma.common.utils.SecurityUtils.getUsername;

/**
 * @author wanghao
 * @date 2023/11/14  9:56
 */
@Service
public class PdaServiceImpl implements IPdaBindingService {
    @Autowired
    private PdaBindingMapper mapper;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private IRecordExceptionProcessService recordExceptionProcessService;

    @Autowired
    private IRecordSwitchOrderService recordSwitchOrderService;

    @Autowired
    private ReportQualityInspectionMapper reportQualityInspectionMapper;

    @Override
    public String selectBoxNameByCode(String boxCode) {
//        mapper.selectBoxNameByCode(boxCode.substring(7,17));
//        select MATERIAL_NAME from BASE_MATERIALINFO where MATERIAL_CODE = #{boxCode}
        return mapper.selectBoxNameByCode(boxCode);
    }

    @Override
    public String selectBoxNameBarCode(String boxCode) {
        return mapper.selectBoxNameBarCode(boxCode.substring(7,17));
    }

    @Override
    public int insertBindingInfo(String boxCode, String boxName, String innerCode) {
        return mapper.insertBindingInfo(boxCode,boxName,innerCode);
    }

    @Override
    public int countQualityRecordByCode(String code) {
        return mapper.countQualityRecordByCode(code);
    }

    @Override
    public int updateCodeBinding(String boxCode, String innerCode) {
        int flag = mapper.updateCodeBinding(boxCode, innerCode);
        if (flag == 0){
            mapper.insertCodeBinding(boxCode);
            flag = mapper.updateCodeBinding(boxCode, innerCode);
        }
        return flag;
    }

    /**
     * 质量返修 提交
     * @param info
     * @return
     */
    @Override
    public int submitRepair(RepairSubmitInfoDto info) {
        if(StringUtils.isNotEmpty(info.getRepairName()) && info.getRepairName().equals("KA")){
            //降级品卡控
            List<HashMap<String, String>> hashMaps = mapper.downgradedProductCardControl(String.valueOf(info.getList().get(0)));
            if (hashMaps.size() == 0){
                return 999;
            }
            RecordExceptionProcess select = new RecordExceptionProcess();
            select.setBoxBarcode(hashMaps.get(0).get("BOX_BARCODE"));
            List<RecordExceptionProcess> processList = recordExceptionProcessService.selectRecordExceptionProcessList(select);
            for (RecordExceptionProcess exceptionProcess : processList) {
                RecordExceptionProcess recordExceptionProcess = new RecordExceptionProcess();
                recordExceptionProcess.setObjId(exceptionProcess.getObjId());
                recordExceptionProcess.setInspectionUserFlag("1");
                recordExceptionProcessService.updateRecordExceptionProcess(recordExceptionProcess);
            }
        }
        try {
            if(StringUtils.isNotEmpty(info.getRepairName()) && info.getRepairName().equals("报废重做")){
                Integer objId = info.getList().get(0);
                ReportQualityInspection inspection = reportQualityInspectionMapper.selectReportQualityInspectionByObjId(Long.valueOf(objId));
                this.rebarCode(inspection.getBarCode(), "报废重做,报废原因:" + inspection.getQualityDefectName());
            }
            if(StringUtils.isNotEmpty(info.getRepairName()) && info.getRepairName().equals("设备报废重做")){
                Integer objId = info.getList().get(0);
                ReportQualityInspection inspection = reportQualityInspectionMapper.selectReportQualityInspectionByObjId(Long.valueOf(objId));
                this.rebarCode(inspection.getBarCode(), "设备报废重做,报废原因:" + inspection.getQualityDefectName());
            }
        } catch (Exception e) {
            System.out.println("质量返修提交报废重做|设备报废重做异常：" + e);
        }
        return mapper.submitRepair(info);
    }

    @Override
    public List<ReportQualityInspection> findCheckInfoByCode(String code) {
        try {
            Long userId = SecurityUtils.getUserId();
            if (StringUtils.isNotNull(userId)){
                List<Long> postList = postService.selectPostListByUserId(userId);
                if (postList.contains(9L)){
                    //质量返修查询：巡检班长获取所有返修信息
                    return mapper.findCheckInfoByCodeUserId(code);
                }
            }
        } catch (Exception e) {
            System.out.println("findCheckInfoByCode异常：" + e);
        }
        return mapper.findCheckInfoByCode(code);
    }

    @Override
    public List<ReportQualityInspection> checkSelectRepairInfo(String code) {
        return mapper.checkSelectRepairInfo(code);
    }

    /**
     * PDA补打条码
     * @param barCode
     * @return
     */
    @Override
    public String rebarCode(String barCode, String printReason) {
        if (StringUtils.isEmpty(barCode)){
            return "条码信息输入错误！";
        }
        List<HashMap<String, String>> barcodeList = mapper.selectPrintBarcode(barCode);
        if (barcodeList.size() > 0){
            if (StringUtils.isNotEmpty(barcodeList.get(0).get("IS_PRINT")) &&
                    barcodeList.get(0).get("IS_PRINT").equals("0")){
                return "请勿重复补打条码！";
            }
            //  维护条码补打记录表
            for (HashMap<String, String> map : barcodeList) {
                map.put("print_reason", printReason);
                map.put("CREATE_BY", getUsername());
            }
            mapper.printSupplementBarcode(barcodeList.get(0));
        }
        return null;
    }

    /**
     * PDA解绑条码
     * @param  barCode
     * @return
     */
    @Override
    public String unbindBarCode(String barCode) {
        String result = null;
        if (StringUtils.isEmpty(barCode)){
            return null;
        }
        List<HashMap<String, String>> barcodeList = mapper.selectPrintBarcode(barCode);
        if (barcodeList.size() > 0){
            mapper.unbindBarCode(barCode);
            result = "解绑条码成功！";
        }
        return result;
    }

    /**
     * PDA降级消息通知
     * @param userName
     * @return
     */
    @Override
    public String messageNotifications(String userName) {
        String resultMessage = null;
        StringBuilder boxCode = null;
        List<HashMap<String, String>> barcodeList = mapper.messageNotifications(userName);
        for (HashMap<String, String> map : barcodeList) {
            String userNames = map.get("INSPECTION_USER_CODE");
            if (userNames.equals("NULL")){
                userNames = userName;
            } else {
                if (userNames.contains(userName)){
                    continue;
                }
                userNames = userNames + "," + userName;
            }
            RecordExceptionProcess recordExceptionProcess = new RecordExceptionProcess();
            recordExceptionProcess.setObjId(Long.valueOf(String.valueOf(map.get("OBJ_ID"))));
            recordExceptionProcess.setInspectionUserCode(userNames);
            recordExceptionProcessService.updateRecordExceptionProcess(recordExceptionProcess);
            if (boxCode == null){
                boxCode = new StringBuilder(map.get("BOX_BARCODE")).append("(位置:").append(map.get("TEAM_NAME")).append(")");
            } else {
                boxCode.append(",").append(map.get("BOX_BARCODE")).append("(位置:").append(map.get("TEAM_NAME")).append(")");
            }
        }
        if (boxCode != null){
            resultMessage  = boxCode + "已审批完成，请进行降级处理！";
        }
        System.out.println("PDA降级消息通知:" + resultMessage);
        return resultMessage;
    }

    /**
     * PDA切换订单
     * @param barCode
     * @param stationCode
     * @return
     */
    @Override
    public String switchOrders(String barCode, String stationCode) {

        RecordSwitchOrder recordSwitchOrder = new RecordSwitchOrder();
        recordSwitchOrder.setMaterialBarcode(barCode);
        recordSwitchOrder.setSwitchStationCode(stationCode);
        recordSwitchOrderService.insertRecordSwitchOrder(recordSwitchOrder);
        return "提交成功！";
    }

    /**
     * PDA降级信息查询
     * @param inspectionUserFlag 巡检班长降级标识(1=已降级，2=未降级)
     * @return
     */
    @Override
    public List<RecordExceptionProcess> selectExceptionProcessList(String inspectionUserFlag) {
        RecordExceptionProcess process = new RecordExceptionProcess();
        process.setProductionUserFlag("9");
        process.setInspectionUserFlag(inspectionUserFlag);
        return recordExceptionProcessService.selectRecordExceptionProcessList(process);
    }

    /**
     * 箱体发泡检验01工位 对 壳胆绑定进行验证
     * @param code
     * @param station
     * @return
     */
    @Override
    public String checkShellBinding(String code, String station) {
        String result = null;
        List<HashMap<String, String>> mapList = mapper.checkShellBinding(code);
        if (mapList.size() == 0){
            result = "该箱体未绑定内胆码！";
        }
        return result;
    }

}
