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

import com.huigou.cache.DictUtil;
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.processQuotedPrice.domain.ProcessQuotedPrice;
import com.huigou.topsun.sap.processQuotedPrice.application.ProcessQuotedPriceItemApplication;
import com.huigou.topsun.sap.processQuotedPrice.application.ProcessQuotedPriceItemNumberApplication;
import com.huigou.topsun.sap.processQuotedPrice.application.ProcessQuotedPriceApplication;
import com.huigou.topsun.sap.processQuotedPrice.domain.ProcessQuotedPriceItem;
import com.huigou.topsun.sap.processQuotedPrice.domain.query.ProcessQuotedPriceQueryRequest;
import com.huigou.topsun.sap.processQuotedPrice.repository.ProcessQuotedPriceRepository;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bpm.FlowBroker;
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.util.List;
import java.util.Map;

/**
 * @Auther: xin.lu
 * @Date: 2024/10/30/14:17
 * @Description:
 */
@Service("processQuotedPriceApplication")
public class ProcessQuotedPriceApplicationImpl extends FlowBroker implements ProcessQuotedPriceApplication {
    @Autowired
    private ProcessQuotedPriceRepository processQuotedPriceRepository;
    @Autowired
    private ProcessQuotedPriceItemApplication processQuotedPriceItemApplication;
    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        ProcessQuotedPrice processQuotedPrice = getBizEntity(ProcessQuotedPrice.class);
        if (processQuotedPrice.isNew()) {
            processQuotedPrice.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            processQuotedPrice = (ProcessQuotedPrice) commonDomainService.loadAndFillinProperties(processQuotedPrice);
        }
        processQuotedPrice = processQuotedPriceRepository.save(processQuotedPrice);

        //保存工单明细
        List<ProcessQuotedPriceItem> items = getBizEntities(ProcessQuotedPriceItem.class, "items");
        processQuotedPriceItemApplication.saveProcessQuotedPriceItems(processQuotedPrice.getId(),items);
        return processQuotedPrice.getId();
    }


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

    /**
     * 获取任务标题
     *
     * @param bizId
     * @return
     */
    private String getApprovalSubjectName(String bizId) {
        ProcessQuotedPrice processQuotedPrice = this.processQuotedPriceRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", processQuotedPrice.getFillinDate());
        //设置标题
        return String.format("%s-%s(%s)", "工序外协报价", processQuotedPrice.getBillCode(), fillinDateStr);
    }

    @Override
    protected Map<String, Object> getProcessBizParams(String bizId) {
        // 返回业务数据给流程实例，
        return ClassHelper.toMap(processQuotedPriceRepository.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();
        updateStatus(bizId, BizBillStatus.APPROVING);
    }

    /**
     * 回收事件
     **/
    @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
    protected void updateStatus(String bizId, BizBillStatus status) {
        Assert.hasText(bizId, CommonDomainConstants.ID_NOT_BLANK);
        this.commonDomainService.updateStatus(ProcessQuotedPrice.class, bizId, status.getId());
    }

    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        //super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
        ProcessQuotedPrice processQuotedPrice = processQuotedPriceRepository.findOne(bizId);
        processQuotedPrice.setStatusId(status.getId());
        processQuotedPriceRepository.save(processQuotedPrice);
    }

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

    /**
     * @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();
            ProcessQuotedPrice processQuotedPrice = processQuotedPriceRepository.findOne(bizId);
            processQuotedPrice.setStatusId(BizBillStatus.APPLYING.getId());
            processQuotedPriceRepository.save(processQuotedPrice);
        }
    }
    
    @Override
    public Map<String, Object> slicedProcessQuotedPriceList(ProcessQuotedPriceQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedProcessQuotedPriceList");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        queryModel.putDictionary("status",BizBillStatus.getMap());
        queryModel.putDictionary("payMethod", DictUtil.getDictionary("zwels"));
        return this.sqlExecutorDao.executeSlicedQuery(queryModel);
    }

    @Override
    public ProcessQuotedPrice loadProcessQuotedPrice(String id) {
        return processQuotedPriceRepository.findOne(id);
    }
}
