package com.artfess.yhxt.taskcallback;

import com.artfess.base.groovy.IScript;
import com.artfess.base.query.QueryFilter;
import com.artfess.base.query.QueryOP;
import com.artfess.bpm.api.cmd.ActionCmd;
import com.artfess.bpm.api.model.delegate.BpmDelegateTask;
import com.artfess.bpm.api.model.process.nodedef.BpmNodeDef;

import com.artfess.uc.util.ContextUtil;
import com.artfess.yhxt.budget.dao.YearBudgetDetailedDao;
import com.artfess.yhxt.budget.manager.YearBudgetDetailedManager;
import com.artfess.yhxt.budget.manager.YearBudgetManager;
import com.artfess.yhxt.budget.model.YearBudget;
import com.artfess.yhxt.budget.model.YearBudgetDetailed;
import com.artfess.yhxt.contract.manager.WorkOrderInformationManager;
import com.artfess.yhxt.contract.model.BillOfQuantities;
import com.artfess.yhxt.contract.model.WorkOrderInformation;
import com.artfess.yhxt.contract.vo.WorkOrderInformationVo;
import com.artfess.yhxt.disease.manager.DiseaseManager;
import com.artfess.yhxt.disease.model.Disease;
import com.artfess.yhxt.util.ArithUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.Arrays;
import java.util.List;

/**
 * 养护工单某些流程节点执行完后的回调方法
 */
@Component
public class TaskCallBackScript implements IScript {

    @Resource
    private DiseaseManager diseaseManager;

    @Resource
    private YearBudgetManager yearBudgetManager;

    @Resource
    private WorkOrderInformationManager workOrderInformationManager;

    @Resource
    private YearBudgetDetailedManager yearBudgetDetailedManager;

    @Resource
    private YearBudgetDetailedDao yearBudgetDetailedDao;
    /**
     *养护工单流程节点处理完成后，需要执行的回调函数，如果还有其他节点需要执行回调，则传入对应的node编号
     * @param nodeDef 节点信息
     * @param delegateTask 任务信息
     * @param cmd 流转信息
     * @param node 节点，可以通过节点来实现不同的处理
     * @throws Exception
     */
    public void updateHandlingSituatioByWorkId(BpmNodeDef nodeDef, BpmDelegateTask delegateTask, ActionCmd cmd, int node) throws Exception {

        //施工完成,修改施工完成时间
        if(null == nodeDef && null == delegateTask && null == cmd ){
            return;
        }
        if(3 == node){
            String businessKey = cmd.getBusinessKey();
            if(StringUtils.isBlank(businessKey))return;;
            WorkOrderInformationVo vo = workOrderInformationManager.getVo(businessKey);
            WorkOrderInformation workOrderInformation = vo.getWorkOrderInformation();
            workOrderInformation.setConstructionFinishTime(LocalDateTime.now());
            workOrderInformationManager.update(workOrderInformation);
        }
        //收方完成
        if(4 == node){
            String businessKey = cmd.getBusinessKey();
            if(StringUtils.isBlank(businessKey))return;;
            WorkOrderInformationVo vo = workOrderInformationManager.getVo(businessKey);
            WorkOrderInformation workOrderInformation = vo.getWorkOrderInformation();
            workOrderInformation.setReceiveror(ContextUtil.getCurrentUserId());
            workOrderInformation.setReceiverDate(LocalDate.now());
            workOrderInformationManager.update(workOrderInformation);
        }
        //审核完成
        if(5 == node){
            String businessKey = cmd.getBusinessKey();
            if(StringUtils.isBlank(businessKey))return;
            WorkOrderInformationVo vo = workOrderInformationManager.getVo(businessKey);
            WorkOrderInformation workOrderInformation = vo.getWorkOrderInformation();
            workOrderInformation.setAuditor(ContextUtil.getCurrentUserId());
            workOrderInformation.setAuditDate(LocalDate.now());
            workOrderInformationManager.update(workOrderInformation);
        }
        // 流程结束
        if(99 == node){

            String businessKey = cmd.getBusinessKey();
            if(StringUtils.isBlank(businessKey))return;;
            WorkOrderInformationVo vo = workOrderInformationManager.getVo(businessKey);
            WorkOrderInformation workOrderInformation = vo.getWorkOrderInformation();
            workOrderInformation.setEndTime(LocalDate.now());
            workOrderInformation.setStatus("1");
            //完成不计入逾期
            workOrderInformation.setOverdue(0);
            //修改处理完成时间
            workOrderInformationManager.update(workOrderInformation);
            //获取病害ID
            String diseaseId = workOrderInformation.getDiseaseId();
            //修改病害处理状态
            if (StringUtils.isNotEmpty(diseaseId)) {
                //所有病害ID集合ids.split(",")
                List<String> ids = Arrays.asList(diseaseId.split(";"));
                LocalDateTime deadLineHandledTime = LocalDateTime.now();
                for (String id : ids) {
                    Disease disease = this.diseaseManager.getById(id);
                    //计算超时，写入超时日期
                    LocalDate demandFinishTime = workOrderInformation.getDemandFinishTime(); //要求修复时间
                    if(null != demandFinishTime){
                        Period between = Period.between(demandFinishTime, LocalDate.now());
//                        LocalDateTime deadlineTime = demandFinishTime.atTime(23, 59, 59);
//                        disease.setDeadline(deadlineTime);
//                        disease.setDeadlineStart(deadlineTime);
                        if(between.getDays() > 0){
                            disease.setDeadlineStatus(1);
                            disease.setDeadlineEnd(deadLineHandledTime);
                        }else {
                            disease.setDeadlineStatus(0);
                        }
                    }
                    //修改病害处理状态
                    if (disease.getHandlingSituation() ==null ||disease.getHandlingSituation()==1) {
                        disease.setHandlingSituation(2);
                        disease.setHandledTimeEnd(deadLineHandledTime);
                        this.diseaseManager.update(disease);
                    }
                }
            }
            //计算已用金额
            Double zf = 0.0;
            List<BillOfQuantities> billOfQuantities = vo.getBillOfQuantities();
            for(BillOfQuantities billOfQuantitie : billOfQuantities){
                Float auditMoney = billOfQuantitie.getTaxMoney();
                if (auditMoney!=null)zf = ArithUtil.add(zf, auditMoney);
            }
            //修改预算使用金额
            if(zf > 0){
                String roadSegmentId = workOrderInformation.getRoadSegmentId();
                QueryFilter<YearBudget> queryFilter = QueryFilter.build();
                LocalDate localDate = LocalDate.now();
                queryFilter.addFilter("ASCRIPTION_YEAR_", localDate.getYear(), QueryOP.EQUAL);
                queryFilter.addFilter("ROAD_SEGMENT_ID_", roadSegmentId, QueryOP.EQUAL);
                queryFilter.addFilter("IS_DELE_", "0", QueryOP.EQUAL);
                List<YearBudget> yearBudgetList = yearBudgetManager.queryNoPage(queryFilter);
                if(null != yearBudgetList && yearBudgetList.size() > 0){
                    for (YearBudget yearBudget : yearBudgetList){

//                        BigDecimal alreadyCount = yearBudget.getAlreadyCount();
//                        if (alreadyCount==null){
//                            alreadyCount=new BigDecimal(0);
//                        }
//                        BigDecimal decimal = alreadyCount.add(BigDecimal.valueOf(zf/10000));
//                        yearBudget.setAlreadyCount(decimal);
                        //计算形象金额
                        QueryWrapper<YearBudgetDetailed> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("YEAR_BUDGET_ID_",yearBudget.getId());
                        queryWrapper.eq("IS_DELE_","0");
                        queryWrapper.eq("EXPENDITURE_TYPE_","FXCBXZC");
                        queryWrapper.eq("BUDGET_TYPE_","RCJF");
                        queryWrapper.eq("BUDGET_ITEM_","RCYH");
                        queryWrapper.eq("BUDGET_CONTENT","日常养护");
                        List<YearBudgetDetailed> detaileds = yearBudgetDetailedManager.list(queryWrapper);
                        for (YearBudgetDetailed detailed:detaileds){
                            BigDecimal imageProgress = detailed.getImageProgress();
                            if (imageProgress==null){
                                imageProgress=new BigDecimal(0);
                            }
                            BigDecimal bigDecimal = imageProgress.add(BigDecimal.valueOf(zf/10000));
                            detailed.setImageProgress(bigDecimal);
                            yearBudgetDetailedManager.update(detailed);
                        }
                        yearBudget.setAlreadyCount(yearBudgetDetailedDao.sumImageProgress(yearBudget.getId()));
                        yearBudgetManager.updateById(yearBudget);
                    }
                }
            }
        }

    }
}
