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

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.SystemCache;
import com.huigou.context.Operator;
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.fixedAssets.application.SapFixedAssetsApplication;
import com.huigou.topsun.sap.fixedAssets.domain.SapFixedAssets;
import com.huigou.topsun.sap.fixedAssets.domain.query.SapFixedAssetsQueryRequest;
import com.huigou.topsun.sap.fixedAssets.domain.vo.SapFixedAssetsReturnVo;
import com.huigou.topsun.sap.fixedAssets.domain.vo.SapFixedAssetsVo;
import com.huigou.topsun.sap.fixedAssets.repository.SapFixedAssetsRepository;
import com.huigou.topsun.sap.purchase.domain.SapPurchase;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.util.ClassHelper;
import com.huigou.util.DateUtil;
import com.huigou.util.StringUtil;
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.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Auther: xin.lu
 * @Date: 2023/12/21/9:37
 * @Description:
 */
@Service("sapFixedAssetsApplication")
public class SapFixedAssetsApplicationImpl extends FlowBroker implements SapFixedAssetsApplication {

    @Autowired
    private SapFixedAssetsRepository sapFixedAssetsRepository;

    @Autowired
    private HttpClient httpClient;

    @Override
    public Map<String, Object> getFixedAssetsList(SapFixedAssetsQueryRequest sapFixedAssetsQueryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "sapFixedAssets");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, sapFixedAssetsQueryRequest);
        queryModel.putDictionary("status",BizBillStatus.getMap());
        Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
        return map;

    }

    @Override
    public SapFixedAssetsVo getFixedAssetsById(String id) {
        return SapFixedAssetsVo.getSapFixedAssetsVo(sapFixedAssetsRepository.getOne(id));
    }

    @Override
    public void deleteByIds(List<String> ids) {
        ids.forEach(id -> sapFixedAssetsRepository.delete(id));
    }

    @Override
    public SapFixedAssetsVo saveAndUpdate(SapFixedAssets sapFixedAssets, Operator operator) {
        // 判断修改还是新增
        if (StringUtil.isNotBlank(sapFixedAssets.getId())) {
            // 修改
            // 将标识修改为2
            sapFixedAssets.setZfiflg(2);
            sapFixedAssets = sapFixedAssetsRepository.saveAndFlush(sapFixedAssets);
        } else {
            // 新增
            // 封装填报时间
            BeanUtils.copyProperties(operator, sapFixedAssets);
//            sapFixedAssets.setStatusId(BizBillStatus.APPLYING.getId());
            sapFixedAssets.setZfiflg(1);
            sapFixedAssets = sapFixedAssetsRepository.saveAndFlush(sapFixedAssets);
        }
        return SapFixedAssetsVo.getSapFixedAssetsVo(sapFixedAssets);
    }

    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        //super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
        SapFixedAssets fixedAssets = sapFixedAssetsRepository.findOne(bizId);
        fixedAssets.setStatusId(status.getId());

        // 封装返回数据
        List<SapFixedAssetsReturnVo> sapFixedAssetsReturnVoList = getReturnVo(fixedAssets);
        String url = SystemCache.getParameter("sap.service.fixedAssets.url", String.class);
        SapFixedAssets message;
        try {
            String execute = httpClient.execute(sapFixedAssetsReturnVoList, url);
            List<SapFixedAssets> sapFixedAssets = JSONObject.parseArray(execute, SapFixedAssets.class);
            SapFixedAssets assets = sapFixedAssets.get(0);
            if (!"S".equals(assets.getType())) {
                throw new RuntimeException("数据传输失败，"+assets.getMessage());
            }
            fixedAssets.setType(assets.getType());
            fixedAssets.setMessage(assets.getMessage());
            fixedAssets.setAnln1(assets.getMessageV1());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        sapFixedAssetsRepository.save(fixedAssets);
    }

    /**
     * 封装返回JSON
     */
    private List<SapFixedAssetsReturnVo> getReturnVo(SapFixedAssets fixedAssets) {
        SapFixedAssetsReturnVo sapFixedAssetsReturnVo = new SapFixedAssetsReturnVo();
        BeanUtils.copyProperties(fixedAssets, sapFixedAssetsReturnVo);
        sapFixedAssetsReturnVo.setAnln1("0");
        List<SapFixedAssetsReturnVo> sapFixedAssetsReturnVos = new ArrayList<>();
        sapFixedAssetsReturnVos.add(sapFixedAssetsReturnVo);
        return sapFixedAssetsReturnVos;
    }

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

    /**
     * 获取任务标题
     *
     * @param bizId
     * @return
     */
    private String getApprovalSubjectName(String bizId) {
        SapFixedAssets fixedAssets = this.sapFixedAssetsRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", fixedAssets.getFillinDate());
        //设置标题
        return String.format("%s-%s-%s(%s)", "固定资产", fixedAssets.getBillCode(),fixedAssets.getTxt50(), fillinDateStr);
    }

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

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

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

    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        SapFixedAssets sapFixedAssets = getBizEntity(SapFixedAssets.class);
        Operator operator = this.getOperator();
        if (sapFixedAssets.isNew()) {
            sapFixedAssets.setStatusId(BizBillStatus.APPLYING.getId());
            sapFixedAssets.setZfiflg(1);
            BeanUtils.copyProperties(operator, sapFixedAssets);
            sapFixedAssets.setZfibpmnr(sapFixedAssets.getBillCode());
        } else {
            sapFixedAssets.setZfiflg(2);
            sapFixedAssets = (SapFixedAssets) commonDomainService.loadAndFillinProperties(sapFixedAssets);
        }
        sapFixedAssets = sapFixedAssetsRepository.save(sapFixedAssets);
        return sapFixedAssets.getId();
    }
}
