package com.jwipc.job.handler;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jwipc.order.entity.PurchaseOrderDetail;
import com.jwipc.order.model.po.PurchaseOrderDetailPO;
import com.jwipc.order.service.IPurchaseOrderDetailService;
import com.jwipc.sys.entity.MoldForm;
import com.jwipc.sys.entity.MoldSettings;
import com.jwipc.sys.entity.SysConfig;
import com.jwipc.sys.service.IMoldFormService;
import com.jwipc.sys.service.IMoldSettingsService;
import com.jwipc.sys.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: swq
 * @Date: 2024/3/28 13:50
 */
@PersistJobDataAfterExecution
@DisallowConcurrentExecution
@Slf4j
@Component
public class StatisticsMaterialJob extends QuartzJobBean implements InterruptableJob {
    @Autowired
    private IMoldFormService moldFormService;
    @Autowired
    private IMoldSettingsService moldSettingsService;
    @Autowired
    private IPurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Override
    public void interrupt() throws UnableToInterruptJobException {

    }

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("统计物料下单数量任务开始");
        //查询所有模具信息
        List<MoldForm> moldFormList = moldFormService.list();
        //查询所有模具产品信息
        List<MoldSettings> settingsList =moldSettingsService.list();
        List<PurchaseOrderDetail> purchaseOrderDetailList =purchaseOrderDetailService.list();
        List<MoldForm> updateMoldList = new ArrayList<>();
        List<MoldSettings> updateMoldSettingsList = new ArrayList<>();
        //查出模具中的所有物料的下单数量
        List<PurchaseOrderDetailPO> numList = purchaseOrderDetailService.findNumByMaterialCodeList();
        if (moldFormList != null && moldFormList.size() > 0) {
            for (MoldForm moldForm : moldFormList) {
                //查询一个模具对应的产品信息列表
                List<MoldSettings> moldCodeList =settingsList.stream().filter(t->t.getMoldId().equals(moldForm.getId())).collect(Collectors.toList());
                if(moldCodeList != null && moldCodeList.size() > 0){
                    //查出一个模具对应的所有物料
                    List<String> prodCodeList = moldCodeList.stream().map(MoldSettings::getProductCode).collect(Collectors.toList());
                    //查出所有的物料
                    List<PurchaseOrderDetailPO> poLst =numList.stream().filter(t -> prodCodeList.contains(t.getMaterialCode())).collect(Collectors.toList());
                    if(poLst!=null && poLst.size()>0){
                        BigDecimal sumNum= new BigDecimal("0.000");
                        for(PurchaseOrderDetailPO orderDetailPO:poLst){
                            sumNum = sumNum.add(orderDetailPO.getNum());
                        }
                        int res = sumNum.divide(new BigDecimal(moldForm.getDosage()),3,BigDecimal.ROUND_HALF_UP).setScale(0, RoundingMode.HALF_UP).intValue()+moldForm.getInitialTimes();
                        //设置实际使用次数的值
                        moldForm.setActualUseTimes(res);
                        SysConfig sysConfig = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getConfigKey,"mould_life_alarm_rate_config").eq(SysConfig::getConfigType,1).last(" limit 1"));
                        String conValue = sysConfig.getConfigValue();
                        // 使用 BigDecimal 进行除法计算
                        BigDecimal result = BigDecimal.valueOf(res).divide(BigDecimal.valueOf(moldForm.getUseTimes()), 2, RoundingMode.HALF_UP);
                        //如果result>=系统参数配置表中mould_life_alarm_rate_config 的值conValue
                        if(result.compareTo(new BigDecimal(conValue))>0 ||result.compareTo(new BigDecimal(conValue))==0 ){
                            moldForm.setIsCallPolice(1);//设置报警
                            moldForm.setPoliceTime(LocalDateTime.now());
                        }else{
                            moldForm.setIsCallPolice(0);
                        }
//                        SysConfig sysConfig1 = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getConfigKey,"mold_cost_warn_rate_config").eq(SysConfig::getConfigType,1).last(" limit 1"));
//                        String conValue1 = sysConfig1.getConfigValue();
//                        BigDecimal resultQuantity = BigDecimal.valueOf(res).divide(BigDecimal.valueOf(moldForm.getQuantity()), 2, RoundingMode.HALF_UP);
//                        if(resultQuantity.compareTo(new BigDecimal(conValue1))>0 ||resultQuantity.compareTo(new BigDecimal(conValue1))==0 ){
//                            moldForm.setIsQuantityPolice(1);//设置报警
//                            moldForm.setQuantityPoliceTime(LocalDateTime.now());
//                        }else{
//                            moldForm.setIsQuantityPolice(0);
//                        }
                        updateMoldList.add(moldForm);
                    }

                }

            }
        }
        if(updateMoldList.size()>0){
            //批量更新
            moldFormService.updateBatchById(updateMoldList);
        }
        log.info("{统计物料下单数量任务结束}", updateMoldList);
        //模具关联 产品数量统计
        if (settingsList != null && settingsList.size() > 0) {
            //查出一个模具对应的所有物料
            List<String> prodCodeList1 = settingsList.stream().map(MoldSettings::getProductCode).collect(Collectors.toList());
            //查出所有的物料
            List<PurchaseOrderDetailPO> poLst1 =numList.stream().filter(t -> prodCodeList1.contains(t.getMaterialCode())).collect(Collectors.toList());

//            List<PurchaseOrderDetailPO> poLst1 =numList.stream().filter(t -> purchaseOrderDetailList.contains(t.getMaterialCode())).collect(Collectors.toList());
            for (MoldSettings moldSettings : settingsList) {
//                String productCode = moldSettings.getProductCode();

                if(poLst1!=null && poLst1.size()>0) {
//                    BigDecimal sumNum1 = new BigDecimal("0.000");
                    for (PurchaseOrderDetailPO orderDetailPO : poLst1) {
                        if(moldSettings.getProductCode().equals(orderDetailPO.getMaterialCode())){
//                            sumNum1 = sumNum1.add(orderDetailPO.getNum());
                            moldSettings.setPurchaseAmount(orderDetailPO.getNum().longValue());
                        }
                    }

                }
                updateMoldSettingsList.add(moldSettings);
//                List<PurchaseOrderDetailPO> numList1 = purchaseOrderDetailService.findNumByMaterialCodeList1(productCode);

            }
        }
        if(updateMoldSettingsList.size()>0){
            //批量更新
            moldSettingsService.updateBatchById(updateMoldSettingsList);
        }
        log.info("{统计产品数量任务结束}", updateMoldSettingsList);
    }
}
