package com.ximai.mes.restful;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.core.controller.BaseController;
import com.ximai.common.core.domain.AjaxResult;
import com.ximai.common.exception.ServiceException;
import com.ximai.mes.md.domain.MdItem;
import com.ximai.mes.md.service.IMdItemService;
import com.ximai.mes.pro.domain.ProFeedback;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.task.ProPackagePrintRecord;
import com.ximai.mes.pro.domain.vo.proWorkOrder.BuildPackageParams2;
import com.ximai.mes.pro.domain.vo.proWorkOrder.WorkorderPackage;
import com.ximai.mes.pro.domain.vo.proWorkOrder.WorkorderPackageResult;
import com.ximai.mes.pro.service.IProFeedbackService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkorderService;
import com.ximai.mes.pro.service.task.IProPackagePrintRecordService;
import com.ximai.mes.restful.vo.PackageLinkInfo;
import com.ximai.mes.restful.vo.PackageSearchParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/apiPda/search")
public class PdaSearchRestController extends BaseController {

    @Autowired
    private IProPackagePrintRecordService proPackagePrintRecordService;
    @Autowired
    private IProWorkorderService proWorkorderService;
    @Autowired
    private IMdItemService mdItemService;
    @Autowired
    private IProFeedbackService feedbackService;

    @ApiOperation(value = "根据包装条码查询关联信息")
    @RequestMapping(value = "/findPackageLinkInfo", method = RequestMethod.POST)
    public AjaxResult<List<PackageLinkInfo>> findPackageLinkInfo(@RequestBody PackageSearchParams packageSearchParams) {
        List<PackageLinkInfo> rst = new ArrayList<PackageLinkInfo>();
        ProPackagePrintRecord record = proPackagePrintRecordService.selectProPackagePrintRecordByBarcode(packageSearchParams.getQrcode());
        if (record == null) {
            throw new ServiceException("未找到包装标签数据：" + packageSearchParams.getQrcode());
        }
        ProWorkorder workorder = proWorkorderService.selectWorkorderById(record.getWorkorderId());
        BuildPackageParams2 buildPackageParams = new BuildPackageParams2();
        buildPackageParams.setEncasementNum(workorder.getUsageEncasementNum());
        buildPackageParams.setPackNum(workorder.getUsagePackNum());
        buildPackageParams.setMergePack(workorder.getMergePack()==1);
        buildPackageParams.setWorkorderId(record.getWorkorderId());
        WorkorderPackageResult packageResult = proWorkorderService.buildPackagePrintInfo(buildPackageParams);
        WorkorderPackage workorderPackage = packageResult.getPackageList().stream().filter(s -> s.getQrcode().equals(record.getQrcode()))
                .findFirst().orElseThrow(() -> new ServiceException("未找到包装标签数据" + record.getQrcode()));
        MdItem mdItem = mdItemService.selectMdItemById(workorder.getProductId());
        if (mdItem == null) {
            throw new ServiceException("未找到物料基础数据");
        }
        final List<ProFeedback> feedbackList = new ArrayList<ProFeedback>();
        List<ProPackagePrintRecord> plList = null;
        if(packageSearchParams.getQrcode().startsWith("B")) {
            QueryWrapper<ProPackagePrintRecord> query = new QueryWrapper<ProPackagePrintRecord>();
            query.eq("bl_group", record.getBlGroup());
            query.eq("workorder_id", record.getWorkorderId());
            query.ne("qrcode", record.getQrcode());
            plList = proPackagePrintRecordService.selectProPackagePrintRecordList(query);
            QueryWrapper<ProFeedback> queryFeedback = new QueryWrapper<ProFeedback>();
            queryFeedback.in("qrcode", plList.stream().map(s->s.getQrcode()).collect(Collectors.toList()));
            feedbackList.addAll(feedbackService.selectProFeedbackList(queryFeedback));
        }else{
            QueryWrapper<ProFeedback> queryFeedback = new QueryWrapper<ProFeedback>();
            queryFeedback.eq("qrcode", record.getQrcode());
            feedbackList.addAll(feedbackService.selectProFeedbackList(queryFeedback));
        }
        //BL标签，返回所属PL标签
        if(packageSearchParams.getQrcode().startsWith("B")){
            plList.forEach(s->{
                Optional<WorkorderPackage> plPackage = packageResult.getPackageList().stream().filter(s2 -> s2.getQrcode().equals(s.getQrcode())).findFirst();
                if(!plPackage.isPresent()){
                    throw new ServiceException(String.format("未找到包装标签%s", s.getQrcode()));
                }
                if (plPackage.get().getDistributes() == null || plPackage.get().getDistributes().isEmpty()) {
                    PackageLinkInfo tempPackageLinkInfo = this.convert(s, mdItem, workorder, record);
                    Integer quantityQualify = feedbackList.stream().filter(temp-> temp.getQrcode().equals(s.getQrcode())).mapToInt(t -> t.getQuantityQualify().intValue()).sum();
                    tempPackageLinkInfo.setQuantity(Math.max(quantityQualify-tempPackageLinkInfo.getLossNum(),0));
                    tempPackageLinkInfo.setTotalQuantity(tempPackageLinkInfo.getLossNum() + tempPackageLinkInfo.getQuantity());
                    initSizeDirective(s.getWorkorderSoSizeItemId(), s.getWorkorderSoDirectiveId(), packageResult, tempPackageLinkInfo);
                    rst.add(tempPackageLinkInfo);
                }else{
                    plPackage.get().getDistributes().forEach(distri -> {
                        PackageLinkInfo tempPackageLinkInfo = this.convert(s, mdItem, workorder, distri, record);
                        initSizeDirective(distri.getSizeId(), distri.getDirectiveId(), packageResult, tempPackageLinkInfo);
                        rst.add(tempPackageLinkInfo);
                    });
                }
            });
        }else {
            Optional<WorkorderPackage> blPackage = packageResult.getPackageList().stream().filter(s -> record.getBlGroup() == s.getBlGroup() &&
                                s.getQrcode().startsWith("BL")).findFirst();
            ProPackagePrintRecord blRecord;
            if(blPackage.isPresent()){
                blRecord = proPackagePrintRecordService.selectProPackagePrintRecordByQrcode(blPackage.get().getQrcode());
            } else {
                blRecord = null;
            }
            if (workorderPackage.getDistributes() == null || workorderPackage.getDistributes().isEmpty()) {
                PackageLinkInfo packageLinkInfo = this.convert(record, mdItem, workorder, blRecord);
                initSizeDirective(record.getWorkorderSoSizeItemId(), record.getWorkorderSoDirectiveId(), packageResult, packageLinkInfo);
                Integer quantityQualify = feedbackList.stream().mapToInt(s -> s.getQuantityQualify().intValue()).sum();
                packageLinkInfo.setQuantity(Math.max(quantityQualify - record.getLossNum(), 0));
                packageLinkInfo.setTotalQuantity(packageLinkInfo.getLossNum() + packageLinkInfo.getQuantity());
                rst.add(packageLinkInfo);
            } else {
                workorderPackage.getDistributes().forEach(distri -> {
                    PackageLinkInfo tempPackageLinkInfo = this.convert(record, mdItem, workorder, distri, blRecord);
                    initSizeDirective(distri.getSizeId(), distri.getDirectiveId(), packageResult, tempPackageLinkInfo);
                    rst.add(tempPackageLinkInfo);
                });
            }
        }
        return AjaxResult.success(rst);
    }

    private void initSizeDirective(Long sizeId,Long directiveId,WorkorderPackageResult packageResult,PackageLinkInfo packageLinkInfo){
        if (sizeId != null) {
            packageResult.getSizeList().stream().filter(s -> s.getWorkorderSoSizeItemId().equals(sizeId)).findFirst().ifPresent(s -> {
                packageLinkInfo.setStandardSize(s.getStandardSize());
            });
        }
        //默认第一个指令号
        if (packageResult.getDirectiveList().size() == 1) {
            packageLinkInfo.setClientCmd(packageResult.getDirectiveList().get(0).getClientCmd());
        }
    }

    private PackageLinkInfo convert(ProPackagePrintRecord record, MdItem mdItem, ProWorkorder workorder,
                                    WorkorderPackage.QuantityDistribute distri, ProPackagePrintRecord blRecord){
        PackageLinkInfo packageLinkInfo = this.convert(record, mdItem, workorder, blRecord);
        packageLinkInfo.setLossNum(distri.getLossNum());
        packageLinkInfo.setQuantity(distri.getPackageNum());
        packageLinkInfo.setTotalQuantity(packageLinkInfo.getLossNum() + packageLinkInfo.getQuantity());
        return packageLinkInfo;
    }

    private PackageLinkInfo convert(ProPackagePrintRecord record, MdItem mdItem, ProWorkorder workorder, ProPackagePrintRecord blRecord){
        PackageLinkInfo packageLinkInfo = new PackageLinkInfo();
        packageLinkInfo.setWorkorderNo(workorder.getWorkorderCode());
        packageLinkInfo.setLossNum(record.getLossNum());
        packageLinkInfo.setQrcode(record.getBarcode());
        packageLinkInfo.setUnitOfMeasure(workorder.getUnitOfMeasure());
        packageLinkInfo.setSapItemCode(mdItem.getSapItemCode());
        packageLinkInfo.setItemName(mdItem.getItemName());
        packageLinkInfo.setWeightUnit("KG");
        packageLinkInfo.setCheckBy(record.getCheckBy());
        packageLinkInfo.setNetWeight(record.getNetWeight());
        packageLinkInfo.setCreateBy(record.getCreateBy());
        packageLinkInfo.setCreateDate(DateUtil.format(record.getCreateTime(),"yyyy-MM-dd"));
        packageLinkInfo.setCreateTime(DateUtil.format(record.getCreateTime(),"HH:mm"));
        packageLinkInfo.setPrintBy(record.getPrintBy());
        packageLinkInfo.setPrintDate(DateUtil.format(record.getPrintDate(),"yyyy-MM-dd"));
        packageLinkInfo.setPrintTime(DateUtil.format(record.getPrintDate(),"HH:mm"));
        packageLinkInfo.setRemark(record.getRemark());
        packageLinkInfo.setTemplateStandard("100*80");
        packageLinkInfo.setClientCode(workorder.getClientCode());
        if(blRecord!=null){
            packageLinkInfo.setBlQrcode(blRecord.getBarcode());
            packageLinkInfo.setBoxWeight(blRecord.getBoxWeight());
            packageLinkInfo.setGrossWeight(blRecord.getGrossWeight());
            packageLinkInfo.setPackageStandard(blRecord.getPackageStandard());
        }
        return packageLinkInfo;
    }

}
