package com.huigou.topsun.sap.qualityInfoRecord.application.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.huigou.cache.SystemCache;
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.sap.common.HttpClient;
import com.huigou.topsun.sap.common.domain.SapResult;
import com.huigou.topsun.sap.costReimbursement.domain.SapCostReimbursement;
import com.huigou.topsun.sap.qualityInfoRecord.application.SapQualityInfoRecordApplication;
import com.huigou.topsun.sap.qualityInfoRecord.application.SapQualityInfoRecordItemApplication;
import com.huigou.topsun.sap.qualityInfoRecord.domain.SapQualityInfoRecord;
import com.huigou.topsun.sap.qualityInfoRecord.domain.query.SapQualityInfoRecordQueryRequest;
import com.huigou.topsun.sap.qualityInfoRecord.domain.vo.SapQualityInfoRecordItemVo;
import com.huigou.topsun.sap.qualityInfoRecord.repository.SapQualityInfoRecordRepository;
import com.huigou.topsun.sap.suppliers.domain.SuppliersInfo;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.fn.CodeGenerator;
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.StringUtil;
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 javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xin.lu
 * @Date: 2024/02/28/15:40
 * @Description:
 */
@Service("sapQualityInfoRecordApplication")
public class SapQualityInfoRecordApplicationImpl extends FlowBroker implements SapQualityInfoRecordApplication {

    @Autowired
    private SapQualityInfoRecordRepository sapQualityInfoRecordRepository;
    //@Autowired
    //private SapQualityInfoRecordItemApplication sapQualityInfoRecordItemApplication;
    @Autowired
    private HttpClient httpClient;
    @Autowired
    private CodeGenerator codeGenerator;
    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        SapQualityInfoRecord sapQualityInfoRecord = getBizEntity(SapQualityInfoRecord.class);
        if (sapQualityInfoRecord.isNew()) {
            sapQualityInfoRecord.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            sapQualityInfoRecord = (SapQualityInfoRecord) commonDomainService.loadAndFillinProperties(sapQualityInfoRecord);
        }
        if (StringUtil.isBlank(sapQualityInfoRecord.getZqinfno())){
            String nextCode = codeGenerator.getNextCode("zqinfno");
            String zqinfno =  sapQualityInfoRecord.getWerks() + "-" + nextCode.replace("-0", "-00");
            sapQualityInfoRecord.setZqinfno(zqinfno);
        }
        sapQualityInfoRecordRepository.save(sapQualityInfoRecord);
        //List<SapQualityInfoRecordItem> sapQualityInfoRecordItems = getBizEntities(SapQualityInfoRecordItem.class, "items");
        //sapQualityInfoRecordItemApplication.saveSapQualityInfoRecordItem(sapQualityInfoRecord.getId(), sapQualityInfoRecordItems);

        return sapQualityInfoRecord.getId();
    }

    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        SapQualityInfoRecord sapQualityInfoRecord = sapQualityInfoRecordRepository.findOne(bizId);
        if (this.isApplyProcUnit(delegateTask) && this.getApprovalParameter().isAdvanceProcessAction()) {
            sapQualityInfoRecord.setStatusId(BizBillStatus.APPROVING.getId());
        }
        if (!isApplyProcUnit(delegateTask)) {
            TaskExtension te = actApplication.loadRuntimeTaskExtension(delegateTask.getId());
            Assert.notNull(te, String.format("未查询到流程任务【%s】的扩展信息", delegateTask.getId()));
            // 获取流程任务对应的审批环节信息
            ProcUnitHandler procUnitHandler = procUnitHandlerApplication.loadProcUnitHandler(te.getProcUnitHandlerId());
            String subProcUnitId = procUnitHandler.getSubProcUnitId();
            if ("stage1".equals(subProcUnitId)){
                sapQualityInfoRecord.setZqavfn1("S1");
                sapQualityInfoRecord.setZvfnc1("A");
                sapQualityInfoRecord.setZqafst("02");
            }
            if ("stage2".equals(subProcUnitId)){
                sapQualityInfoRecord.setZqavfn2("Q1");
                sapQualityInfoRecord.setZvfnc2("A");
                sapQualityInfoRecord.setZqafst("04");
            }
        }
        sapQualityInfoRecordRepository.save(sapQualityInfoRecord);
    }


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

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

    /**
     * 回收事件
     **/
    @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) {
        org.springframework.util.Assert.hasText(bizId, CommonDomainConstants.ID_NOT_BLANK);
        this.commonDomainService.updateStatus(SapQualityInfoRecord.class, bizId, status.getId());
    }

    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
        SapQualityInfoRecord sapQualityInfoRecord = sapQualityInfoRecordRepository.findOne(bizId);
        sapQualityInfoRecord.setStatusId(status.getId());
        sapQualityInfoRecordRepository.save(sapQualityInfoRecord);

        this.getSapPurchaseInfoRecordItemVo(sapQualityInfoRecord);
    }

    public void getSapPurchaseInfoRecordItemVo(SapQualityInfoRecord sapQualityInfoRecord){
        //List<SapQualityInfoRecordItem> purchaseInfoRecordItemList = sapQualityInfoRecordItemApplication.findBySapQualityInfoRecordId(sapQualityInfoRecord.getId());
        List<SapQualityInfoRecordItemVo> sapQualityInfoRecordItemVoList = new ArrayList<>();
        //purchaseInfoRecordItemList.forEach(sapQualityInfoRecordItem -> {
        SapQualityInfoRecordItemVo sapQualityInfoRecordItemVo = new SapQualityInfoRecordItemVo();
        sapQualityInfoRecord.setZqavfn3("M1");
        sapQualityInfoRecord.setZvfnc3("A");
        sapQualityInfoRecord.setZqafst("11");
            BeanUtil.copyProperties(sapQualityInfoRecord, sapQualityInfoRecordItemVo);
            if ("0".equals(sapQualityInfoRecordItemVo.getGrsrq())){
                sapQualityInfoRecordItemVo.setGrsrq("");
            }
            if ("0".equals(sapQualityInfoRecordItemVo.getFscrq())){
                sapQualityInfoRecordItemVo.setFscrq("");
            }
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            if (sapQualityInfoRecord.getGrscertdatai() !=null){
                String datab = dateFormat.format(sapQualityInfoRecord.getGrscertdatai());
                sapQualityInfoRecordItemVo.setGrscertdatai(datab);
            }
            if (sapQualityInfoRecord.getFsccertdatai() != null){
                String datbi = dateFormat.format(sapQualityInfoRecord.getFsccertdatai());
                sapQualityInfoRecordItemVo.setFsccertdatai(datbi);
            }
            if (sapQualityInfoRecord.getZvdatab() != null){
                String zvdatab = dateFormat.format(sapQualityInfoRecord.getZvdatab());
                sapQualityInfoRecordItemVo.setZvdatab(zvdatab);
            }
            if (sapQualityInfoRecord.getZvdatai() != null){
                String zvdatai = dateFormat.format(sapQualityInfoRecord.getZvdatai());
                sapQualityInfoRecordItemVo.setZvdatai(zvdatai);
            }
            if (sapQualityInfoRecord.getFillinDate() != null){
                String fillinDate = dateFormat.format(sapQualityInfoRecord.getFillinDate());
                sapQualityInfoRecordItemVo.setErstelldat(fillinDate);
            }
            sapQualityInfoRecordItemVo.setErsteller(sapQualityInfoRecord.getPersonMemberName());
            sapQualityInfoRecordItemVoList.add(sapQualityInfoRecordItemVo);
        //});
        try {
            String url = SystemCache.getParameter("sap.QualityInfoRecord.url", String.class);
            String execute = httpClient.execute(sapQualityInfoRecordItemVoList, url);
            List<SapResult> resultList = JSONObject.parseArray(execute, SapResult.class);
            for (SapResult sapResult : resultList) {
                if (!"S".equals(sapResult.getTYPE())){
                    throw new RuntimeException("数据传输失败，"+ sapResult.getMESSAGE());
                }
            }
            sapQualityInfoRecord.setType(resultList.get(0).getTYPE());
            sapQualityInfoRecord.setMessage(resultList.get(0).getMESSAGE());
            this.sapQualityInfoRecordRepository.save(sapQualityInfoRecord);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

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

    /**
     * @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();
            SapQualityInfoRecord sapQualityInfoRecord = sapQualityInfoRecordRepository.findOne(bizId);
            sapQualityInfoRecord.setStatusId(BizBillStatus.APPLYING.getId());
            sapQualityInfoRecordRepository.save(sapQualityInfoRecord);
        }
    }

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

    @Override
    public SapQualityInfoRecord loadSapQualityInfoRecord(String id) {
        return sapQualityInfoRecordRepository.findOne(id);
    }

}
