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

import com.huigou.cache.DictUtil;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.base.coderule.application.CodeRuleApplication;

import com.huigou.topsun.sap.componentSupply.application.ComponentSupplyItemApplication;
import com.huigou.topsun.sap.componentSupply.domain.ComponentSupplyItem;
import com.huigou.topsun.sap.dull.application.SapDullApplication;
import com.huigou.topsun.sap.dull.application.SapDullItemApplication;
import com.huigou.topsun.sap.dull.domain.SapDull;
import com.huigou.topsun.sap.dull.domain.SapDullItem;
import com.huigou.topsun.sap.dull.domain.query.SapDullQueryRequest;
import com.huigou.topsun.sap.dull.repository.SapDullItemRepository;
import com.huigou.topsun.sap.dull.repository.SapDullRepository;
import com.huigou.topsun.sap.purchase.domain.SapPurchase;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.doc.attachment.application.AttachmentApplication;
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 java.util.List;
import java.util.Map;

/**
 * @Auther: Lxh
 * @Date: 2024/03/28/19:55
 * @Description:
 */
@Service("sapDullApplication")
public class SapDullApplicationImpl extends FlowBroker implements SapDullApplication {
    @Autowired
    private SapDullRepository sapDullRepository;
    @Autowired
    private SapDullItemApplication sapDullItemApplication;
    @Autowired
    private SapDullItemRepository sapDullItemRepository;
   // @Autowired
   // private SapDullItemRepository sapDullItemRepository;
    @Autowired
    private AttachmentApplication attachmentApplication;
    @Autowired
    private CodeRuleApplication codeRuleApplication;
    @Override
    public Map<String, Object> getDullList(SapDullQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "sapDull");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        queryModel.putDictionary("status", DictUtil.getDictionary("bizBillStatus"));
        queryModel.putDictionary("isFinished", DictUtil.getDictionary("yesorno"));
        queryModel.addCriteria(" order by bill_code desc ");
        Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        return map;
    }

    @Override
    public SapDull getDullById(String id) {
        return sapDullRepository.findOne(id);
    }

    @Override
    public void deleteByIds(List<String> ids) {
        ids.forEach(id->{
             sapDullRepository.delete(id);
            List<SapDullItem> list=sapDullItemRepository.findBySapDullId(id);
            for (SapDullItem sapDullItem:list){
                sapDullItemRepository.delete(sapDullItem);
            }
        });

    }

    @Override
    public void updateStatus(String id, String status) {
        SapDull sapDull = sapDullRepository.findOne(id);
        sapDull.setIsFinished(status);
        sapDullRepository.save(sapDull);
    }

    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (this.isApplyProcUnit(delegateTask) && this.getApprovalParameter().isAdvanceProcessAction()) {
            SapDull sapDull = sapDullRepository.findOne(bizId);
            sapDull.setStatusId(BizBillStatus.APPROVING.getId());
            sapDullRepository.save(sapDull);
        }
    }

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

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

    @Override
    protected void onBack(DelegateTask delegateTask, String destActivityId) {
        super.onBack(delegateTask, destActivityId);
        if ("Apply".equalsIgnoreCase(destActivityId)) {
            String bizId = delegateTask.getExecution().getProcessBusinessKey();
            SapDull Dull = sapDullRepository.findOne(bizId);
            Dull.setStatusId(BizBillStatus.APPLYING.getId());
            sapDullRepository.save(Dull);
        }
    }

    @Override
    protected Map<String, Object> getProcessBizParams(String bizId) {
        return ClassHelper.toMap(sapDullRepository.getOne(bizId));
    }

    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        SapDull dull = getBizEntity(SapDull.class);
        if (dull.isNew()) {
            dull.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            dull = (SapDull) commonDomainService.loadAndFillinProperties(dull);
        }
        dull = sapDullRepository.save(dull);

        List<SapDullItem> items = getBizEntities(SapDullItem.class, "items");
        if (items.size()<1){
            throw new IllegalArgumentException("没有呆滞物料明细信息!");
        }
        sapDullItemApplication.saveSapDullItems(dull.getId(),items);
        return dull.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) {
        SapDull sapDull = this.sapDullRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", sapDull.getFillinDate());
        //设置标题
        return String.format("%s-%s(%s)", "呆滞物料或异常物料", sapDull.getBillCode(), fillinDateStr);
    }



}
