package cn.superdesk.uniorder.service.order.receive.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.enums.common.*;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
import cn.superdesk.uniorder.common.numerical.AnDateHelper;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrder;
import cn.superdesk.uniorder.dao.entity.base.UnifiedOrderGoods;
import cn.superdesk.uniorder.dao.mapper.base.*;
import cn.superdesk.uniorder.dto.param.operation.UnifiedOrderIssuesFlowingParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.ipostoffice.PostOfficeOrderGoodsReceiveParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.ipostoffice.PostOfficeOrderReceiveParam;
import cn.superdesk.uniorder.event.CommonEventPublisher;
import cn.superdesk.uniorder.service.order.base.CommonMergeOrderCreditProcessService;
import cn.superdesk.uniorder.service.order.base.CommonMergeOrderGoodsProcessService;
import cn.superdesk.uniorder.service.order.base.CommonOrderProcessService;
import cn.superdesk.uniorder.service.order.receive.ReceivePostOfficeOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Description: 新版小邮局 订单
 * @Author: linjinyu
 * @CreateDate: 2020/12/3 上午11:32
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020/12/3 上午11:32
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class ReceivePostOfficeOrderServiceImpl implements ReceivePostOfficeOrderService {

    @Autowired
    private UnifiedOrderMapper unifiedOrderMapper;
    @Autowired
    private UnifiedOrderMapperEx unifiedOrderMapperEx;
    @Autowired
    private UnifiedOrderMapperExSupplierDimOrder unifiedOrderMapperExSupplier;
    @Autowired
    private UnifiedOrderGoodsMapper unifiedOrderGoodsMapper;
    @Autowired
    private UnifiedOrderGoodsMapperEx unifiedOrderGoodsMapperEx;


    @Autowired
    private CommonOrderProcessService commonOrderProcessService;
    @Autowired
    private CommonMergeOrderGoodsProcessService commonOrderGoodsMergeProcessService;
    @Autowired
    private CommonMergeOrderCreditProcessService commonOrderCreditMergeProcessService;

    @Autowired
    private CommonEventPublisher commonEventPublisher;


    /****************************************** kafka 服务之窗 小邮局 start ******************************************/
    public UnifiedOrderIssuesFlowingParam kafkaPostOfficeOrderMergeReceive(PostOfficeOrderReceiveParam receiveParam) {

        UnifiedOrderIssuesFlowingParam callback = new UnifiedOrderIssuesFlowingParam();
        callback.setUid(receiveParam.getUid());
        callback.setProcessResult(CommonProcessResultEnum.正常.getKey());
        callback.setProcessReport("");


        // 如果这个单的价格为 0 为过来还有什么意义呢?
        if (null == receiveParam.getOrderAmount() && receiveParam.getOrderAmount().compareTo(BigDecimal.ZERO) == 0) {
            // TODO 记录 问题单
            callback.setProcessResult(CommonProcessResultEnum.异常_数据本身缺失.getKey());
            callback.setProcessReport("订单金额为空");
            return callback;
        }

        // 如果 这个单 没有商品 直接 返回
        if (AnCollectionUtils.isEmpty(receiveParam.getGoodsList())) {
            // TODO 记录 问题单
            callback.setProcessResult(CommonProcessResultEnum.异常_数据本身缺失.getKey());
            callback.setProcessReport("订单商品为空");
            return callback;
        }


        // 处理订单
        UnifiedOrder unifiedOrderEntity = new UnifiedOrder();
        convertPostOfficeOrderReceiveParam2Entity(receiveParam, unifiedOrderEntity);


        // 处理订单 商品
        BigDecimal costAmount = new BigDecimal(0);

        List<UnifiedOrderGoods> processUnifiedOrderGoodsList = new ArrayList<>();
        List<PostOfficeOrderGoodsReceiveParam> postOfficeOrderReceiveParamGoodsList = receiveParam.getGoodsList();

        for (PostOfficeOrderGoodsReceiveParam postOfficeOrderGoodsReceiveParam : postOfficeOrderReceiveParamGoodsList) {

            UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
            convertPostOfficeOrderGoodsReceiveParam2Entity(postOfficeOrderGoodsReceiveParam, unifiedOrderGoods);

            unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());

            processUnifiedOrderGoodsList.add(unifiedOrderGoods);

            // 计算成本金额合计
//			costAmount = costAmount.add(new BigDecimal(unifiedOrderGoods.getQuantity().doubleValue() * unifiedOrderGoods.getCostPrice().doubleValue()));
            costAmount = costAmount.add(unifiedOrderGoods.getCostPrice().multiply(new BigDecimal(unifiedOrderGoods.getQuantity())));
        }

        // add 20191122 成本金额
        unifiedOrderEntity.setCostAmount(costAmount);


        // 将运费转换为商品 同 (一般订单 add 20190925)
        if (null != unifiedOrderEntity.getTransportAmount() && unifiedOrderEntity.getTransportAmount().compareTo(BigDecimal.ZERO) > 0) {

            UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();

            unifiedOrderGoods.setGoodsType(CommonOrderGoodsTypeEnum.运费.getKey());
            unifiedOrderGoods.setDirection(CommonDirectionEnum.正向.getKey());

            unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
            unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

            unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
            unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

            unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());
            unifiedOrderGoods.setGoodsName(CommonOrderGoodsIdEnum.运费.getDesc());
            unifiedOrderGoods.setGoodsType(CommonOrderGoodsTypeEnum.运费.getKey());
            unifiedOrderGoods.setQuantity(1);
            unifiedOrderGoods.setUnit(CommonOrderGoodsUnitEnum.项.getDesc());
            unifiedOrderGoods.setPrice(unifiedOrderEntity.getTransportAmount());
            unifiedOrderGoods.setCostPrice(unifiedOrderEntity.getTransportAmount());


            unifiedOrderGoods.setCreateTime(DateUtil.date());
            unifiedOrderGoods.setCreateUserId(1L);

            unifiedOrderGoods.setUpdateTime(DateUtil.date());
            unifiedOrderGoods.setUpdateUserId(1L);

            processUnifiedOrderGoodsList.add(unifiedOrderGoods);

        }


        // 状态 -1:已关闭,0:待付款,1:待发货,2:待收货,3:已完成
        UnifiedOrder checkExistUnifiedOrder = unifiedOrderMapperEx.findByOrderSn(unifiedOrderEntity.getOrderSn());

        // 不存在就好办了
        if (checkExistUnifiedOrder == null) {

            // 没有商品 不保存订单数据
            if (AnCollectionUtils.isNotEmpty(processUnifiedOrderGoodsList)) {

                // TODO 重新计算运费等等 change dz 1105
//				if(order.getTransportAmount().doubleValue()>0) {
//					BigDecimal new_amount = order.getAmount().add(order.getTransportAmount());
//					order.setAmount(new_amount);
//				}

                // 保存订单数据
                commonOrderProcessService.attachInsert(unifiedOrderEntity);

                for (UnifiedOrderGoods unifiedOrderGoods : processUnifiedOrderGoodsList) {
                    unifiedOrderGoodsMapper.insert(unifiedOrderGoods);
                }
            }

        } else {

            // TODO 重新计算运费等等
//			if(order.getTransportAmount().doubleValue()>0) {
//				BigDecimal new_amount = order.getAmount().add(order.getTransportAmount());
//				order.setAmount(new_amount);
//			}

            unifiedOrderEntity.setId(checkExistUnifiedOrder.getId());//要先set id 在更新

            unifiedOrderEntity.setUpdateTime(DateUtil.date());

            unifiedOrderEntity.setAccountingStateCustomer(checkExistUnifiedOrder.getAccountingStateCustomer());
            unifiedOrderEntity.setAccountingStateSupplier(checkExistUnifiedOrder.getAccountingStateSupplier());

            commonOrderProcessService.attachUpdate(unifiedOrderEntity);


            // 重构 by linjinyu 20200915 start
            commonOrderGoodsMergeProcessService.processUnifiedOrderGoodsBykafkaPushOrderReceive(unifiedOrderEntity, processUnifiedOrderGoodsList, 1);
            // 重构 by linjinyu 20200915   end

        }

        /****************************************** 分润 先屏蔽 start ******************************************/
//		commonEventPublisher.triggerUnifiedOrderProfitCalculationEvent(unifiedOrderEntity);
        /****************************************** 分润 先屏蔽 start ******************************************/


        log.info("##################### kafkaPostOfficeOrderMergeReceive end #####################");

        return callback;
    }

    public void kafkaPostOfficeOrderDeleteReceive(String message) {
        // TODO to be conttinued
    }

    /****************************************** kafka 服务之窗 小邮局 start ******************************************/

    private void convertPostOfficeOrderReceiveParam2Entity(PostOfficeOrderReceiveParam postOfficeOrderReceiveParam, UnifiedOrder unifiedOrderEntity) {


        unifiedOrderEntity.setOrderType(CommonOrderTypeEnum.订单.getKey());

        unifiedOrderEntity.setOrderSn(postOfficeOrderReceiveParam.getOrderSn());
        unifiedOrderEntity.setOrderSnOutTrade(postOfficeOrderReceiveParam.getOrderSn());

        unifiedOrderEntity.setAmount(postOfficeOrderReceiveParam.getOrderAmount());

        // TODO 写死
        unifiedOrderEntity.setCostAmount(new BigDecimal("0"));

        unifiedOrderEntity.setCreateTime(postOfficeOrderReceiveParam.getCreateTime());
        unifiedOrderEntity.setCreateUserId(null);




        // TODO 处理 deleted 这个状态 归一要再定义 mark by linjinyu at 20201211 1740
//		unifiedOrder.setCompletState(UnifiedOrderCompletStateUtils.convertBySuperDeskMallOrderStatus(postOfficeOrderReceiveParam.getOrderState(), postOfficeOrderReceiveParam.getDeleted()));


        // TODO 设定 订单来源
//		unifiedOrderEntity.setServiceNo(UnifiedServiceEnum.getServiceNo(postOfficeOrderReceiveParam.getOrderType()));
//		unifiedOrderEntity.setServiceName(UnifiedServiceEnum.getServiceName(postOfficeOrderReceiveParam.getOrderType()));
        unifiedOrderEntity.setServiceNo(postOfficeOrderReceiveParam.getServiceNo());
        unifiedOrderEntity.setServiceName(postOfficeOrderReceiveParam.getServiceName());

        Map<String, String> otherParams = new HashMap<>();
        otherParams.put("sendTime", AnDateHelper.parseDateToStrFormat(postOfficeOrderReceiveParam.getSendTime(), AnDateHelper.DATE_TIME_STRING));
        unifiedOrderEntity.setOtherParams(otherParams.toString());


        // TODO mark by linjinyu at 2022-07-22 10:28:33 - 统一修正 支付方式 支付状态 订单状态 都不定义 start

//        //		是定义还是 传过来呢？先当是传过来吧
////		unifiedOrderEntity.setOrderStateName(SuperDeskMallOrderStatusEnum.getDesc(postOfficeOrderReceiveParam.getOrderState()));
//        unifiedOrderEntity.setOrderState(postOfficeOrderReceiveParam.getOrderState());
//        unifiedOrderEntity.setOrderStateName(postOfficeOrderReceiveParam.getOrderStateName());
//        unifiedOrderEntity.setPayType(postOfficeOrderReceiveParam.getPayType());
//        unifiedOrderEntity.setPayState(2); // TODO 写死 标记20200708

        unifiedOrderEntity.setOrderState(postOfficeOrderReceiveParam.getOrderState());
        unifiedOrderEntity.setOrderStateName(postOfficeOrderReceiveParam.getOrderStateName());

        unifiedOrderEntity.setPayType(postOfficeOrderReceiveParam.getPayType());
        unifiedOrderEntity.setPayTypeName(postOfficeOrderReceiveParam.getPayTypeName());

        unifiedOrderEntity.setPayState(ObjectUtil.isNull(postOfficeOrderReceiveParam.getPayState()) ? 2 : postOfficeOrderReceiveParam.getPayState());
        unifiedOrderEntity.setPayStateName(postOfficeOrderReceiveParam.getPayStateName());

        // TODO mark by linjinyu at 2022-07-22 10:28:33 - 统一修正 支付方式 支付状态 订单状态 都不定义 start



        unifiedOrderEntity.setProjectId(postOfficeOrderReceiveParam.getPurchaseOrgId());
        // TODO 要去查
//		unifiedOrder.setProjectName();

        unifiedOrderEntity.setPurchaseUserId(postOfficeOrderReceiveParam.getPurchaseUserId());
        unifiedOrderEntity.setPurchaseUserName(postOfficeOrderReceiveParam.getPurchaseUserName());
        unifiedOrderEntity.setPurchasePhone(postOfficeOrderReceiveParam.getPurchasePhone());

        unifiedOrderEntity.setPurchaseVirtId(postOfficeOrderReceiveParam.getPurchaseVirtId());
        unifiedOrderEntity.setPurchaseVirtName(postOfficeOrderReceiveParam.getPurchaseVirtName());

        unifiedOrderEntity.setOrderLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        unifiedOrderEntity.setOrderLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

        unifiedOrderEntity.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
        unifiedOrderEntity.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

        unifiedOrderEntity.setSaleId(postOfficeOrderReceiveParam.getSaleId());
        unifiedOrderEntity.setSaleName(postOfficeOrderReceiveParam.getSaleName());

        // TODO 写死
        unifiedOrderEntity.setSettlementType(2);
        // TODO 写死
        unifiedOrderEntity.setSourceChannel(1);
        // TODO 写死
        unifiedOrderEntity.setAppraiseState(2);


        unifiedOrderEntity.setTransportAmount(postOfficeOrderReceiveParam.getTransportAmount());


        unifiedOrderEntity.setRecAddress(postOfficeOrderReceiveParam.getRecAddress());
        unifiedOrderEntity.setRecUserName(postOfficeOrderReceiveParam.getRecUserName());
        unifiedOrderEntity.setRecUserPhone(postOfficeOrderReceiveParam.getRecUserPhone());
//		unifiedOrder.setRemarks();

        unifiedOrderEntity.setUpdateTime(postOfficeOrderReceiveParam.getFinishTime());
        unifiedOrderEntity.setUpdateUserId(1L);


        unifiedOrderEntity.setUserType("2");
        unifiedOrderEntity.setUserName("系统");

    }

    private void convertPostOfficeOrderGoodsReceiveParam2Entity(PostOfficeOrderGoodsReceiveParam postOfficeOrderGoodsReceiveParam, UnifiedOrderGoods unifiedOrderGoods) {

        unifiedOrderGoods.setGoodsId(postOfficeOrderGoodsReceiveParam.getGoodsId());
        unifiedOrderGoods.setOutSnapshotOrderGoodsId(postOfficeOrderGoodsReceiveParam.getOutSnapshotOrderGoodsId());

        unifiedOrderGoods.setGoodsType(CommonOrderGoodsTypeEnum.商品.getKey());
        unifiedOrderGoods.setDirection(CommonDirectionEnum.正向.getKey());

        unifiedOrderGoods.setGoodsLockingCustomer(CommonAccountingLockingEnum.正常.getKey());
        unifiedOrderGoods.setGoodsLockingSupplier(CommonAccountingLockingEnum.正常.getKey());

        unifiedOrderGoods.setAccountingStateCustomer(CommonAccountingStateEnum.未对账.getKey());
        unifiedOrderGoods.setAccountingStateSupplier(CommonAccountingStateEnum.未对账.getKey());

        unifiedOrderGoods.setGoodsName(postOfficeOrderGoodsReceiveParam.getGoodsName());


        unifiedOrderGoods.setGoodsParams(postOfficeOrderGoodsReceiveParam.getGoodsParams());

        unifiedOrderGoods.setUnit(StrUtil.isBlank(postOfficeOrderGoodsReceiveParam.getUnit()) ? CommonOrderGoodsUnitEnum.项.getDesc() : postOfficeOrderGoodsReceiveParam.getUnit());

        // 销售价 单价
        unifiedOrderGoods.setPrice(postOfficeOrderGoodsReceiveParam.getPrice());
        // 成本价 单价
        unifiedOrderGoods.setCostPrice(postOfficeOrderGoodsReceiveParam.getCostPrice());
        // 数量
        unifiedOrderGoods.setQuantity(postOfficeOrderGoodsReceiveParam.getQuantity());


        /************************************** update by linjinjy 20200904 20200723_林志鹏_税率,退款格式.docx **************************************/

        unifiedOrderGoods.setTaxCode(postOfficeOrderGoodsReceiveParam.getTaxCode());
        unifiedOrderGoods.setTaxRate(postOfficeOrderGoodsReceiveParam.getTaxRate());

        /************************************** update by linjinjy 20200904 20200723_林志鹏_税率,退款格式.docx **************************************/

        /****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/

        unifiedOrderGoods.setCateIdLv1(postOfficeOrderGoodsReceiveParam.getCateIdLv1());
        unifiedOrderGoods.setCateIdLv2(postOfficeOrderGoodsReceiveParam.getCateIdLv2());
        unifiedOrderGoods.setCateIdLv3(postOfficeOrderGoodsReceiveParam.getCateIdLv3());
        unifiedOrderGoods.setCateNameLv1(postOfficeOrderGoodsReceiveParam.getCateNameLv1());
        unifiedOrderGoods.setCateNameLv2(postOfficeOrderGoodsReceiveParam.getCateNameLv2());
        unifiedOrderGoods.setCateNameLv3(postOfficeOrderGoodsReceiveParam.getCateNameLv3());

        /****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/

        unifiedOrderGoods.setCreateUserId(1L);
        unifiedOrderGoods.setCreateTime(DateUtil.date());
        unifiedOrderGoods.setUpdateUserId(1L);
        unifiedOrderGoods.setUpdateTime(DateUtil.date());
    }
}
