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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.DictUtil;
import com.huigou.context.Operator;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.sap.costCenter.application.CostCenterApplication;
import com.huigou.topsun.sap.costCenter.domain.CostCenter;
import com.huigou.topsun.sap.costCenter.domain.query.CostCenterQueryRequest;
import com.huigou.topsun.sap.costCenter.domain.vo.CostCenterReturnVo;
import com.huigou.topsun.sap.costCenter.domain.vo.CostCenterVo;
import com.huigou.topsun.sap.costCenter.repository.CostCenterRepository;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.util.ClassHelper;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Auther: xin.lu
 * @Date: 2023/12/13/11:09
 * @Description:
 */
@Service("costCenterApplication")
public class CostCenterApplicationImpl extends FlowBroker implements CostCenterApplication {

    @Autowired
    private CostCenterRepository costCenterRepository;

    @Override
    public Map<String, Object> getCostCenterList(CostCenterQueryRequest costCenterQueryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "costCenter");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, costCenterQueryRequest);
        queryModel.putDictionary("kosar", DictUtil.getDictionary("KOSAR"));
        queryModel.putDictionary("prctr", DictUtil.getDictionary("PRCTR"));
        Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        return map;
    }

    @Override
    public CostCenterVo findCostCenterById(String id) {
        CostCenter costCenter = costCenterRepository.findOne(id);
        return CostCenterVo.getCostCenterVo(costCenter);
    }

    @Override
    public void deleteCostCenterById(List<String> ids) {
        for (String id : ids) {
            costCenterRepository.delete(id);
        }
    }

    @Override
    public void updateCostCenter(CostCenter costCenter) {
        costCenterRepository.saveAndFlush(costCenter);
    }

    @Override
    public void saveCostCenter(CostCenter costCenter) {

    }

    @Override
    public CostCenterVo saveAndUpdate(CostCenter costCenter) {
        return CostCenterVo.getCostCenterVo(costCenterRepository.saveAndFlush(costCenter));

    }

    @Override
    public Map<String, Object> slicedCostCenterList(CostCenterQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedCostCenterList");
        QueryModel queryModel = sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        return this.sqlExecutorDao.executeSlicedQuery(queryModel);
    }

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

        // 封装JSON数据
        String returnJSON = getReturnVo(costCenter);
    }

    /**
     * 封装返回JSON
     */
    private String getReturnVo(CostCenter costCenter) {
        CostCenterReturnVo costCenterReturnVo = new CostCenterReturnVo();
        BeanUtils.copyProperties(costCenter, costCenterReturnVo);
        // 转换为JSON
        ObjectMapper objectMapper = new ObjectMapper();
        String returnJson = null;
        try {
            returnJson = objectMapper.writeValueAsString(costCenterReturnVo);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return returnJson;
    }

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

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

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

    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        CostCenter costCenter = getBizEntity(CostCenter.class);
        if (costCenter.isNew()) {
            Operator operator = this.getOperator();
            BeanUtils.copyProperties(operator, costCenter);
            costCenter.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            costCenter = (CostCenter) commonDomainService.loadAndFillinProperties(costCenter);
        }
        costCenter = costCenterRepository.save(costCenter);
        return costCenter.getId();
    }
}
