package com.huigou.topsun.ep.change.application.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huigou.data.domain.model.CommonDomainConstants;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.ep.change.application.EpChangeFormApplication;
import com.huigou.topsun.ep.change.application.EpChangeFormImplItemApplication;
import com.huigou.topsun.ep.change.application.EpChangeFormStockItemApplication;
import com.huigou.topsun.ep.change.domain.EpChangeForm;
import com.huigou.topsun.ep.change.domain.EpChangeFormImplItem;
import com.huigou.topsun.ep.change.domain.EpChangeFormStockItem;
import com.huigou.topsun.ep.change.domain.query.EpChangeFormQueryRequest;
import com.huigou.topsun.ep.change.repository.EpChangeFormImplItemRepository;
import com.huigou.topsun.ep.change.repository.EpChangeFormRepository;
import com.huigou.topsun.ep.change.repository.EpChangeFormStockItemRepository;
import com.huigou.topsun.sap.common.HttpClient;
import com.huigou.topsun.sap.common.application.SapMutualEpLogApplication;
import com.huigou.topsun.sap.common.domain.EpResult;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.opm.domain.model.org.Org;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.uasp.bpm.engine.domain.model.ProcUnitHandler;
import com.huigou.uasp.bpm.engine.domain.model.TaskExtension;
import com.huigou.util.ClassHelper;
import com.huigou.util.DateUtil;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.io.IOException;
import java.util.*;

/**
 * @Auther: xin.lu
 * @Date: 2024/06/19/10:06
 * @Description:
 */
@Service("epChangeFormApplication")
public class EpChangeFormApplicationImpl extends FlowBroker implements EpChangeFormApplication {
    @Autowired
    private EpChangeFormRepository epChangeFormRepository;
    @Autowired
    private EpChangeFormStockItemApplication changeFormStockItemApplication;
    @Autowired
    private EpChangeFormImplItemApplication changeFormImplItemApplication;
    @Autowired
    private HttpClient httpClient;
    @Autowired
    SapMutualEpLogApplication sapMutualEpLogApplication;
    @Autowired
    private EpChangeFormImplItemRepository epChangeFormImplItemRepository;
    @Autowired
    private EpChangeFormStockItemRepository epChangeFormStockItemRepository;
    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        EpChangeForm epChangeForm = getBizEntity(EpChangeForm.class);
        if (epChangeForm.isNew()) {
            epChangeForm.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            epChangeForm = (EpChangeForm) commonDomainService.loadAndFillinProperties(epChangeForm);
        }
        epChangeForm = epChangeFormRepository.save(epChangeForm);
        List<EpChangeFormStockItem> changeFormStockItems = getBizEntities(EpChangeFormStockItem.class, "epChangeFormStockItem");
        changeFormStockItemApplication.saveEpChangeFormStockItems(epChangeForm.getId(),changeFormStockItems);

        List<EpChangeFormImplItem> changeFormImplItems = getBizEntities(EpChangeFormImplItem.class, "EpChangeFormImplItem");
        changeFormImplItemApplication.saveEpChangeFormImplItems(epChangeForm.getId(),changeFormImplItems);
        return epChangeForm.getId();
    }

    @Override
    protected Map<String, Object> getProcessBizParams(String bizId) {
        // 返回业务数据给流程实例，
        return ClassHelper.toMap(epChangeFormRepository.getOne(bizId));
    }

    /**
     * 流程撤销事件
     **/
    @Override
    protected void onRecallProcessInstance(DelegateExecution delegateExecution) {
        String bizId = delegateExecution.getProcessBusinessKey();
        // 修改单据状态为申请
        updateStatus(bizId, BizBillStatus.APPLYING);
    }

    /**
     * 任务完成前执行
     */
    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (this.isApplyProcUnit(delegateTask) && this.getApprovalParameter().isAdvanceProcessAction()) {
            updateStatus(bizId, BizBillStatus.APPROVING);
        }
        if (this.isApprovalProcUnit(delegateTask) && this.getApprovalParameter().isAdvanceProcessAction()){
            TaskExtension te = actApplication.loadRuntimeTaskExtension(delegateTask.getId());
            cn.hutool.core.lang.Assert.notNull(te, String.format("未查询到流程任务【%s】的扩展信息", delegateTask.getId()));
            // 获取流程任务对应的审批环节信息
            ProcUnitHandler procUnitHandler = procUnitHandlerApplication.loadProcUnitHandler(te.getProcUnitHandlerId());
            String subProcUnitName = procUnitHandler.getSubProcUnitName();
            //查询到审批人组织信息
            String fullId = delegateTask.getAssignee();
            Org org = orgApplication.loadOrgByFullId(fullId);
            if (ObjectUtil.isNotNull(org)){
                if ("执行人".equals(subProcUnitName)){
                    //匹配部门执行人审批完，更新确认状态是时间
                    List<EpChangeFormImplItem> formImplItemList = epChangeFormImplItemRepository.findByEpChangeFormId(bizId);
                    for (EpChangeFormImplItem epChangeFormImplItem : formImplItemList) {
                        if (org.getId().equals(epChangeFormImplItem.getExecutorId())){
                            epChangeFormImplItem.setConfirm("1");
                            epChangeFormImplItem.setDate(new Date());
                        }
                    }
                    changeFormImplItemApplication.saveEpChangeFormImplItems(bizId,formImplItemList);
                }
                if ("库存".equals(subProcUnitName)){
                    //匹配仓库环节审批完，更新确认状态是时间
                    List<EpChangeFormStockItem> stockItemList = epChangeFormStockItemRepository.findByEpChangeFormId(bizId);
                    for (EpChangeFormStockItem epChangeFormStockItem : stockItemList) {
                        if (org.getDeptId().equals(epChangeFormStockItem.getDeptId())){
                            epChangeFormStockItem.setConfirm("1");
                            epChangeFormStockItem.setDate(new Date());
                        }
                    }
                    changeFormStockItemApplication.saveEpChangeFormStockItems(bizId,stockItemList);
                }
            }
        }
    }

    /**
     * 回收事件
     **/
    @Override
    protected void onWithdraw(DelegateTask delegateTask, String destActivityId) {
        super.onWithdraw(delegateTask, destActivityId);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (destActivityId.equalsIgnoreCase("apply")) {
            updateStatus(bizId, BizBillStatus.APPLYING);
        }
    }

    @Transactional
    private void updateStatus(String bizId, BizBillStatus status) {
        Assert.hasText(bizId, CommonDomainConstants.ID_NOT_BLANK);
        this.commonDomainService.updateStatus(EpChangeForm.class, bizId, status.getId());
    }

    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
        EpChangeForm epChangeForm = epChangeFormRepository.findOne(bizId);
        epChangeForm.setStatusId(status.getId());
        epChangeFormRepository.save(epChangeForm);
        this.feedBackSaleEcn(epChangeForm);
    }

    @Override
    protected void onAbortProcessInstance(DelegateExecution delegateExecution) {
        super.onAbortProcessInstance(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        EpChangeForm epChangeForm = epChangeFormRepository.findOne(bizId);
        epChangeForm.setStatusId(BizBillStatus.ABORTED.getId());
        epChangeFormRepository.save(epChangeForm);
    }

    /**
     * @param delegateTask
     * @param destActivityId 回退到的目标节点id
     */
    @Override
    protected void onBack(DelegateTask delegateTask, String destActivityId) {
        //super.onBack(delegateTask, destActivityId);
        if ("Apply".equalsIgnoreCase(destActivityId)) {
            String bizId = delegateTask.getExecution().getProcessBusinessKey();
            EpChangeForm epChangeForm = epChangeFormRepository.findOne(bizId);
            epChangeForm.setStatusId(BizBillStatus.APPLYING.getId());
            epChangeFormRepository.save(epChangeForm);
        }
    }

    /**
     * 设置任务名称
     */
    @Override
    protected void setTaskDescription(DelegateTask delegateTask) {
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        delegateTask.setDescription(this.getApprovalSubjectName(bizId));
    }

    /**
     * 获取任务标题
     *
     * @param bizId
     * @return
     */
    private String getApprovalSubjectName(String bizId) {
        EpChangeForm epChangeForm = this.epChangeFormRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", epChangeForm.getFillinDate());
        //设置标题
        return String.format("%s-%s(%s)", "宝绅内部变更申请/通知单", epChangeForm.getBillCode(), fillinDateStr);
    }

    @Override
    public EpChangeForm findEpChangeFormById(String id) {
        return epChangeFormRepository.findOne(id);
    }

    @Override
    public EpChangeForm saveEpChangeForm(EpChangeForm epChangeForm) {
        return epChangeFormRepository.save(epChangeForm);
    }

    @Override
    public Map<String, Object> slicedEpChangeFormList(EpChangeFormQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "epChangeForm");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        queryModel.putDictionary("status", BizBillStatus.getMap());
        Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        return map;
    }

    @Override
    public List<Map<String, Object>> queryApprovalPersons(String bizId) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "queryApprovalPersons");
        return this.sqlExecutorDao.queryToListMap(queryDescriptor.getSql(),bizId);
    }

    public void feedBackSaleEcn(EpChangeForm epChangeForm){
        Map<String,Object> map = new HashMap<>();
        //日志记录
        Map<String, Object> resultMap = new HashMap<>();
        try {
            String execute = httpClient.executeForEp(map, "pro/productionSolution/openEcn?pds="+epChangeForm.getPd());
            EpResult epResult = JSONObject.parseObject(execute, EpResult.class);
            resultMap.put("TYPE", epResult.getCode());
            resultMap.put("message", epResult.getMsg());
            if (!"200".equals(epResult.getCode())){
                throw new RuntimeException("数据传输失败，"+ epResult.getMsg());
            }
            epChangeForm.setCode(epResult.getCode());
            epChangeForm.setMsg(epResult.getMsg());
            epChangeFormRepository.save(epChangeForm);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            resultMap.put("businessType", "ECN");
            resultMap.put("businessId", epChangeForm.getBillCode());
            resultMap.put("parameter", JSON.toJSONString(map));
            resultMap.put("sequence", resultMap.get("row"));
            sapMutualEpLogApplication.saveSapMutualEpLog(resultMap);
        }
    }
}
