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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.DictUtil;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
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.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;

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

        String id = fixedAssets.getId();

        SapPriceMasterDataItem item = new SapPriceMasterDataItem();
        item.setPriceMasterDataId(id);
        Example<SapPriceMasterDataItem> of = Example.of(item);
        List<SapPriceMasterDataItem> sapPriceMasterDataItemList = sapPriceMasterDataItemRepository.findAll(of);
        String returnVo = getReturnVo(fixedAssets, 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接口

        // 需要获取priceMasterDataId
//        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "sapFixedAssets");
//        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
//        Map<String, Object> map = this.sqlExecutorDao.executeSlicedQuery(queryModel);
//        return map;
        return null;
    }

    /**
     * 根据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);
            System.out.println(returnJson);
        } 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();
    }

}
