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

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.DictUtil;
import com.huigou.cache.SystemCache;
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.costCenter.domain.vo.CostCenterMessageVo;
import com.huigou.topsun.sap.priceMasterData.application.SapPriceMasterDataApplication;
import com.huigou.topsun.sap.priceMasterData.domain.SapPriceMasterData;
import com.huigou.topsun.sap.priceMasterData.domain.SapPriceMasterDataItem;
import com.huigou.topsun.sap.priceMasterData.domain.query.SapPriceMasterDataItemQueryRequest;
import com.huigou.topsun.sap.priceMasterData.domain.query.SapPriceMasterDataQueryRequest;
import com.huigou.topsun.sap.priceMasterData.domain.vo.SapPriceMasterDataReturnVo;
import com.huigou.topsun.sap.priceMasterData.domain.vo.SapPriceMasterDataVo;
import com.huigou.topsun.sap.priceMasterData.repository.SapPriceMasterDataItemRepository;
import com.huigou.topsun.sap.priceMasterData.repository.SapPriceMasterDataRepository;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.util.ClassHelper;
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.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * title:
 * author:ZHT
 * date:2023/12/25
 * description:
 */
@Service("sapPriceMasterDataApplication")
public class SapPriceMasterDataApplicationImpl extends FlowBroker implements SapPriceMasterDataApplication {

    @Autowired
    private SapPriceMasterDataRepository sapPriceMasterDataRepository;

    @Resource
    private SapPriceMasterDataItemRepository sapPriceMasterDataItemRepository;

    @Autowired
    private HttpClient httpClient;

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

        String id = sapPriceMasterData.getId();

        SapPriceMasterDataItem item = new SapPriceMasterDataItem();
        item.setPriceMasterDataId(id);
        Example<SapPriceMasterDataItem> of = Example.of(item);
        List<SapPriceMasterDataItem> sapPriceMasterDataItemList = sapPriceMasterDataItemRepository.findAll(of);
        String returnVo = getReturnVo(sapPriceMasterData, sapPriceMasterDataItemList);
//        System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
//        System.out.println(returnVo);
        // TODO 调接口-價格主數據維護接口


    }


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

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

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

    }

    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();

        SapPriceMasterData sapPriceMasterData = getBizEntity(SapPriceMasterData.class);
        List<SapPriceMasterDataItem> sapPriceMasterDataItemList = getBizEntities(SapPriceMasterDataItem.class, "priceMasterDataItem");

        if (sapPriceMasterData.isNew()) {
            sapPriceMasterData.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            sapPriceMasterData = (SapPriceMasterData) commonDomainService.loadAndFillinProperties(sapPriceMasterData);
        }
        sapPriceMasterData = sapPriceMasterDataRepository.save(sapPriceMasterData);
        String sapPriceMasterDataId = sapPriceMasterData.getId();

        // 保存item数据
        sapPriceMasterDataItemList.forEach(sapPriceMasterDataItem -> {
            sapPriceMasterDataItem.setPriceMasterDataId(sapPriceMasterDataId);

            // 判断终止时间
            if (StringUtil.isBlank(String.valueOf(sapPriceMasterDataItem.getDatbi()))) {
                Calendar instance = Calendar.getInstance();
                //9999-12-31 23:59:59
                instance.set(9999, 12, 31, 23, 59, 59);
                sapPriceMasterDataItem.setDatbi(instance.getTime());
            }
        });
        sapPriceMasterDataItemRepository.save(sapPriceMasterDataItemList);

//        String returnVo = getReturnVo(sapPriceMasterData, sapPriceMasterDataItemList);
        return sapPriceMasterDataId;
    }


    @Override
    public SapPriceMasterDataVo getPriceMasterDataById(String id) {
        return SapPriceMasterDataVo.getSapPriceMasterDataVo(sapPriceMasterDataRepository.getOne(id));
    }

    @Override
    public Map<String, Object> queryPriceMasterDataList(SapPriceMasterDataQueryRequest queryRequest) {
        // TODO 需调用ICP接口--價格主數據查詢接口
        // ps: 顺序问题,需商量后选择

        // 获取URL地址
        String url = SystemCache.getParameter("sap.service.priceMasterData.url", String.class);
        // 封装查询参数
        Map<String, Object> param = new HashMap<>();
        param.put("KSCHL", queryRequest.getKschl());
        param.put("VKORG", queryRequest.getVkorg());
        param.put("VTWEG", queryRequest.getVtweg());
        param.put("KUNNR", queryRequest.getKunnr());
        param.put("MATNR", queryRequest.getMatnr());

        List<Object> objectArrayList = new ArrayList<>();
        objectArrayList.add(param);
        List<SapPriceMasterDataItem> sapPriceMasterDataItemList = new ArrayList<>();
        try {
            // 调用接口,获取返回数据
            String execute = httpClient.execute(objectArrayList, url);
            // 解析返回数据
            execute = execute.replaceAll("MATNR", "matnr")
                    .replaceAll("KBETR", "kbetr")
                    .replaceAll("KONWA", "konwa")
                    .replaceAll("KMEIN", "kmein")
                    .replaceAll("DATAB", "datab")
                    .replaceAll("DATBI", "datbi");
            sapPriceMasterDataItemList = JSONObject.parseArray(execute,SapPriceMasterDataItem.class);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 封装返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("Total", sapPriceMasterDataItemList.size());
        map.put("Page", 1);
        map.put("Rows", sapPriceMasterDataItemList);
        return map;
    }

    /**
     * 根据priceMaterDataId获取List
     */
//    public List<SapPriceMasterDataItem> queryPriceMasterDataItemList(String priceMasterDataId) {
//        List<SapPriceMasterDataItem> queryRequest = sapPriceMasterDataItemRepository.selectListByPriceMasterDataId(priceMasterDataId);
//        return queryRequest;
//    }
    @Override
    public void deletePriceMasterDataById(List<String> ids) {
        ids.forEach(id -> sapPriceMasterDataItemRepository.delete(id));
    }

    @Override
    public Map<String, Object> queryPriceMasterDataItemList(SapPriceMasterDataItemQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedPriceMasterDataItemList");
        if (StringUtil.isBlank(queryRequest.getPriceMasterDataId()))
            queryRequest.setPriceMasterDataId("0");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        queryModel.putDictionary("konwa", DictUtil.getDictionary("currency"));
        return this.sqlExecutorDao.executeSlicedQuery(queryModel);
    }

    /**
     * 封装返回数据
     */
    public String getReturnVo(SapPriceMasterData sapPriceMasterData, List<SapPriceMasterDataItem> sapPriceMasterDataItemList) {

        List<SapPriceMasterDataReturnVo> sapPriceMasterDataReturnVos = new ArrayList<>();

        sapPriceMasterDataItemList.forEach(sapPriceMasterDataItem -> {
            SapPriceMasterDataReturnVo returnVo = new SapPriceMasterDataReturnVo();
            BeanUtils.copyProperties(sapPriceMasterData, returnVo);
            returnVo.setKSCHL(sapPriceMasterData.getKschl());
            returnVo.setVKORG(sapPriceMasterData.getVkorg());
            returnVo.setVTWEG(sapPriceMasterData.getVtweg());
            returnVo.setKUNNR(sapPriceMasterData.getKunnr());
            // 封装item
            returnVo.setMATNR(sapPriceMasterDataItem.getMatnr());
            returnVo.setKBETR(sapPriceMasterDataItem.getKbetr());
            returnVo.setKONWA(sapPriceMasterDataItem.getKonwa());
            returnVo.setKMEIN(sapPriceMasterDataItem.getKmein());

            returnVo.setDATAB(sapPriceMasterDataItem.getDatab());

            Date datbi = sapPriceMasterDataItem.getDatbi();
            if (datbi == null || datbi.getTime() == 0) {
                Calendar instance = Calendar.getInstance();
                //9999-12-31 23:59:59
                instance.set(9999, 12, 31, 23, 59, 59);
                returnVo.setDATBI(instance.getTime());
            } else
                returnVo.setDATBI(sapPriceMasterDataItem.getDatbi());

            // 保存到list中
            sapPriceMasterDataReturnVos.add(returnVo);
        });
        ObjectMapper objectMapper = new ObjectMapper();
        String returnJson = null;
        try {
            returnJson = objectMapper.writeValueAsString(sapPriceMasterDataReturnVos);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return returnJson;
    }

    /**
     * 装换日期格式
     */
    @Deprecated
    public String dateToString(Date date) {

        int year = date.getYear() + 1900;
        int month = date.getMonth() + 1;
        int day = date.getDate();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(year);

        if (month < 10)
            stringBuilder.append(0).append(month);
        else stringBuilder.append(month);

        if (day < 10)
            stringBuilder.append(0).append(day);
        else stringBuilder.append(day);

        return stringBuilder.toString();
    }

}
