package com.aucma.api.controller;

import com.aucma.api.domain.dto.CheckInfoDto;
import com.aucma.api.domain.dto.RepairSubmitInfoDto;
import com.aucma.api.service.IPdaBindingService;
import com.aucma.base.domain.BaseProcessStation;
import com.aucma.base.service.IBaseProcessStationService;
import com.aucma.common.core.domain.AjaxResult;
import com.aucma.common.utils.SecurityUtils;
import com.aucma.common.utils.StringUtils;
import com.aucma.report.domain.RecordExceptionProcess;
import com.aucma.report.domain.ReportQualityInspection;
import com.aucma.report.service.IMaterialCompletionService;
import com.aucma.report.service.IReportQualityInspectionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

import static com.aucma.common.core.domain.AjaxResult.error;
import static com.aucma.common.core.domain.AjaxResult.success;

/**
 * @author wanghao
 * @date 2023/11/14  9:28
 */
@RestController
@RequestMapping("/api")
public class PdaApiController {
    private static final Logger logger = LoggerFactory.getLogger(PdaApiController.class);
    @Autowired
    private IPdaBindingService service;

    @Autowired
    private IBaseProcessStationService baseProcessStationService;

    @Autowired
    private IMaterialCompletionService completionService;

    @Autowired
    private IReportQualityInspectionService qualityService;

    //壳胆绑定-提交
    @PostMapping("/boxBanding")
    public AjaxResult binding(String boxCode, String innerCode, String loginName) {
        String boxName = service.selectBoxNameByCode(boxCode);
        if (StringUtils.isNotNull(boxName)) {
            service.insertBindingInfo(boxCode, boxName, innerCode);
            return success();
        }
        return error("箱壳条码扫描错误");
    }

    //条码绑定
    @PostMapping("/barCodeBanding")
    public AjaxResult barCodeBanding(String boxCode, String innerCode, String loginName) {
//        查询质检缺陷有没有修复
        int countQa = service.countQualityRecordByCode(boxCode);
        if (countQa > 0) {
            return error("返修中" + countQa + "条未处理，不允许绑定");
        }
//        查询插入
        return toAjax(service.updateCodeBinding(boxCode, innerCode));
    }

    @PostMapping("/selectGoodsName")
    public AjaxResult selectGoodsName(String code) {
        String boxName = service.selectBoxNameByCode(code);
        if (boxName == null) {
            return error("查询失败，条码不正确");
        }
        return success("操作成功", boxName);
    }


    //    质检查询名称、前工位返修数据
    @PostMapping("/check/select")
    public AjaxResult checkSelect(String code) {
        String boxName = service.selectBoxNameByCode(code);
        if (boxName == null) {
            // boxName = "固定数据";
            return error("箱壳条码扫描错误");
        }
        List<ReportQualityInspection> list = service.checkSelectRepairInfo(code);
        return success(boxName, list);

    }

    /**
     * 质量检测：查询物料名称、前工位返修数据
     *
     * @param code
     * @return
     */
    @PostMapping("/check/query")
    public AjaxResult checkQuery(String code, String station) {
        long begin = System.currentTimeMillis();
        String boxName = service.selectBoxNameByCode(code);
        if (boxName == null) {
            return error("条码信息扫描错误！");
        }
        long one = System.currentTimeMillis();
        //检验前一工位是否已完成质检
        long two = 0;
        long three = 0;
        if (StringUtils.isNotEmpty(station)) {
            //箱体发泡检验01工位、二线箱体预装检验工位 对 壳胆绑定进行验证
            two = System.currentTimeMillis();
            if (station.equals("2003") || station.equals("2018") || station.equals("2103") || station.equals("2104")) {
                String result = service.checkShellBinding(code, station);
                if (StringUtils.isNotNull(result)) {
                    return error(result);
                }
            }
            String result = qualityService.checkBeforeStationInspection(code, station);
            three = System.currentTimeMillis();
            if (StringUtils.isNotNull(result)) {
                return error(result);
            }
        }
        List<ReportQualityInspection> list = service.checkSelectRepairInfo(code);
        long end = System.currentTimeMillis();
        logger.info("质量检测checkQuery:" + code + "|总运行时间：" +  (end - begin) + "|工位：" + station
                + "|one:" + (one - begin) + "|two:" + (two - one) + "|three:" + (three - two) + "|three:" + (end - three));
        return success(boxName, list);

    }

    //    质检提交
    @PostMapping("/checkSubmit")
    public AjaxResult checkSubmit(@RequestBody CheckInfoDto checkInfo) {
        long begin = System.currentTimeMillis();
        List<CheckInfoDto.DefectBeen> list = checkInfo.getList();
        int size = (list == null || list.isEmpty()) ? 1 : list.size();
//        logger.info("质检提交checkSubmit1:" + checkInfo.getCode() +  "工位：" +  checkInfo.getStationCode());
        for (int i = 0; i < size; i++) {
            ReportQualityInspection inspection = new ReportQualityInspection();
            inspection.setBarCode(checkInfo.getCode());

            String boxName = service.selectBoxNameBarCode(checkInfo.getCode());
//            logger.info("质检提交checkSubmit2:" + checkInfo.getCode() +  "工位：" +  checkInfo.getStationCode());
            inspection.setMaterialName(boxName);

            String measure = checkInfo.getMeasure();
            inspection.setTreatmentMeasure(measure);
            if (measure.equals("3")) {
                inspection.setIsFlag(1L);
            }
            //检测人
            inspection.setInspectorCode(SecurityUtils.getUsername());
            inspection.setInspectorTime(new Date());
            inspection.setStationCode(checkInfo.getStationCode());
            inspection.setGroupCode(checkInfo.getTeamCode());

            try {
                // 查质检工序
                BaseProcessStation processStation = new BaseProcessStation();
                processStation.setParentId(checkInfo.getStationCode());
                List<BaseProcessStation> processStations = baseProcessStationService.selectBaseProcessStationList(processStation);
//                logger.info("质检提交checkSubmit3:" + checkInfo.getCode() +  "工位：" + checkInfo.getStationCode());
                inspection.setProcessCode(processStations.get(0).getProcessCode());
                inspection.setProductLineName(processStations.get(0).getProductLineCode());
            } catch (Exception e) {
                logger.info("质检提交查质检工序checkSubmitException:{}|工位：{}|{}", checkInfo.getCode(), checkInfo.getStationCode(), e.getMessage());
            }

            assert list != null;
            if (!list.isEmpty()) {
                CheckInfoDto.DefectBeen defectBeen = list.get(i);
                inspection.setSubmitQualtyId(defectBeen.getObjId());
                inspection.setTestItemCode(list.get(i).getStationCode());
                inspection.setQualityDefectCode(list.get(i).getQualityDefectCode());
                inspection.setQualityDefectName(list.get(i).getQualityDefectName());
            }
            qualityService.insertReportQualityInspection(inspection);
//            logger.info("质检提交checkSubmit4:" + checkInfo.getCode() +  "工位：" +  checkInfo.getStationCode());
            //质检处理措施（3=合格,1=返修）
            if (inspection.getTreatmentMeasure().equals("3")) {
                try {
                    completionService.inspectionProcessing(inspection);
//                    logger.info("质检提交checkSubmit5:" + checkInfo.getCode() +  "工位：" +  checkInfo.getStationCode());
                } catch (Exception e) {
                    logger.info("质检提交checkSubmitException:{}|工位：{}|{}", checkInfo.getCode(), checkInfo.getStationCode(), e.getMessage());
                }
            }
        }
        long end = System.currentTimeMillis();
        logger.info("质检提交checkSubmit:" + checkInfo.getCode() +  "|运行时间："+ (end - begin) + "|工位：" + checkInfo.getStationCode());
        return success();
    }

    //返修查询质检信息
    @PostMapping("/findCheckInfoByCode")
    public AjaxResult findCheckInfoByCode(String code) {
        List<ReportQualityInspection> list = service.findCheckInfoByCode(code);
        if (list == null || list.isEmpty()) {
            return error("扫描条码不正确或无返修信息");
        }
        return success(list);
    }

    //返修提交质检信息
    @PostMapping("/submitRepair")
    public AjaxResult submitRepair(@RequestBody RepairSubmitInfoDto info) {
        int i = service.submitRepair(info);
        if (i == 999) {
            return error("该箱体未审批完成，无法降级！");
        }
        if (i > 0) {
            return success("操作成功！");
        } else {
            return error("该箱体已完成返修！");
        }
    }


    private AjaxResult toAjax(int rows) {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * PDA查询当班质检数量
     *
     * @param stationCode 质检记录管理
     * @return 质检记录管理集合
     */
    @PostMapping("/pdaQueryQuantityNumber")
    public AjaxResult pdaQueryQuantityNumber(String stationCode) {
        return success(qualityService.pdaQueryQuantityNumber(stationCode));
    }

    /**
     * PDA补打条码
     *
     * @param barCode
     * @return
     */
    @PostMapping("/rebarCode")
    public AjaxResult rebarCode(String barCode) {
        String result = service.rebarCode(barCode, "PDA补码");
        if (StringUtils.isNotEmpty(result)) {
            return error(result);
        }
        return success("请到条码打印机旁进行补打条码！");
    }

    /**
     * PDA解绑条码
     *
     * @param barCode
     * @return
     */
    @PostMapping("/unbindBarCode")
    public AjaxResult unbindBarCode(String barCode) {
        String result = service.unbindBarCode(barCode);
        if (StringUtils.isEmpty(result)) {
            return error("条码信息输入错误！");
        }
        return success(result);
    }


    /**
     * PDA降级消息通知
     *
     * @param userName
     * @return
     */
    @PostMapping("/messageNotifications")
    public AjaxResult messageNotifications(String userName) {
        String result = service.messageNotifications(userName);
        if (StringUtils.isEmpty(result)) {
            return error("无消息提醒！");
        }
        return success(result);
    }

    /**
     * PDA切换订单
     *
     * @param barCode
     * @param stationCode
     * @return
     */
    @PostMapping("/switchOrders")
    public AjaxResult switchOrders(String barCode, String stationCode) {
        String result = service.switchOrders(barCode, stationCode);
        if (StringUtils.isEmpty(result)) {
            return error("条码信息输入错误！");
        }
        return success(result);
    }

    /**
     * PDA降级信息查询
     *
     * @param inspectionUserFlag 巡检班长降级标识(1=已降级，2=未降级)
     * @return
     */
    @PostMapping("/downgradeQuery")
    public AjaxResult downgradeQuery(String inspectionUserFlag) {
        if (StringUtils.isEmpty(inspectionUserFlag)) {
            return error();
        }
        List<RecordExceptionProcess> list = service.selectExceptionProcessList(inspectionUserFlag);
        return success(list);
    }
}
