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

import cn.hutool.core.bean.BeanUtil;
import com.huigou.cache.DictUtil;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.context.ThreadLocalUtil;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.common.CommonUtils;
import com.huigou.topsun.sap.cashSettlementUnPay.application.CashSettlementUnPayApplication;
import com.huigou.topsun.sap.cashSettlementUnPay.application.CashSettlementUnPayItemApplication;
import com.huigou.topsun.sap.cashSettlementUnPay.domain.CashSettlementUnPay;
import com.huigou.topsun.sap.cashSettlementUnPay.domain.CashSettlementUnPayItem;
import com.huigou.topsun.sap.cashSettlementUnPay.domain.query.CashSettlementUnPayQueryRequest;
import com.huigou.topsun.sap.cashSettlementUnPay.repository.CashSettlementUnPayItemRepository;
import com.huigou.topsun.sap.cashSettlementUnPay.repository.CashSettlementUnPayRepository;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.operator.OperatorApplication;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.uasp.bpm.ProcessAction;
import com.huigou.uasp.bpm.ProcessStartModel;
import com.huigou.uasp.bpm.engine.application.WorkflowApplication;
import com.huigou.util.*;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.runtime.ProcessInstance;
import org.krysalis.barcode4j.HumanReadablePlacement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Auther: Lxh
 * @Date: 2024/03/26/11:35
 * @Description:
 */
@Service("cashSettlementUnPayApplication")
public class CashSettlementUnPayApplicationImpl extends FlowBroker implements CashSettlementUnPayApplication {
    @Autowired
    private CashSettlementUnPayRepository cashSettlementUnPayRepository;
    @Autowired
    private CashSettlementUnPayItemRepository cashSettlementUnPayItemRepository;
    @Autowired
    private CashSettlementUnPayItemApplication cashSettlementUnPayItemApplication;

    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        CashSettlementUnPay cashSettlementUnPay = getBizEntity(CashSettlementUnPay.class);
        if (cashSettlementUnPay.isNew()) {
            cashSettlementUnPay.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            cashSettlementUnPay = (CashSettlementUnPay) commonDomainService.loadAndFillinProperties(cashSettlementUnPay);
        }
        cashSettlementUnPay = cashSettlementUnPayRepository.save(cashSettlementUnPay);
        List<CashSettlementUnPayItem> items = getBizEntities(CashSettlementUnPayItem.class, "items");
        cashSettlementUnPayItemApplication.saveCashSettlementUnPayItems(cashSettlementUnPay.getId(),items);
        return cashSettlementUnPay.getId();
    }

    @Override
    public Map<String, Object> getCashSettlementUnPayList(CashSettlementUnPayQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "cashSettlementUnPay");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        queryModel.putDictionary("status", DictUtil.getDictionary("bizBillStatus"));
        Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        return map;
    }

    @Override
    public CashSettlementUnPay getCashSettlementUnPayById(String id) {
        return cashSettlementUnPayRepository.findOne(id);
    }

    @Override
    public void deleteByIds(List<String> ids) {
        ids.forEach(id->{
             cashSettlementUnPayRepository.delete(id);
            List<CashSettlementUnPayItem> list= cashSettlementUnPayItemRepository.findByCashSettlementUnPayId(id);
            for (CashSettlementUnPayItem cashSettlementUnPayItem :list){
                cashSettlementUnPayItemRepository.delete(cashSettlementUnPayItem);
            }
        });
    }

    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        CashSettlementUnPay cashSettlementUnPay = cashSettlementUnPayRepository.findOne(bizId);
        cashSettlementUnPay.setStatusId(BizBillStatus.APPROVING.getId());
        cashSettlementUnPayRepository.save(cashSettlementUnPay);
    }

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

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

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

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

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

    /**
     * 获取任务标题
     *
     * @param bizId
     * @return
     */
    private String getApprovalSubjectName(String bizId) {
        CashSettlementUnPay cashSettlementUnPay = this.cashSettlementUnPayRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", cashSettlementUnPay.getFillinDate());
        //设置标题
        return String.format("%s-%s(%s)", "现结未付款发货", cashSettlementUnPay.getBillCode(), fillinDateStr);
    }

}
