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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.superdesk.uniorder.common.enums.common.*;
import cn.superdesk.uniorder.common.numerical.AnCollectionUtils;
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.meetingroomreservation.MeetingRoomReservationOrderGoodsReceiveParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskappservices.meetingroomreservation.MeetingRoomReservationOrderReceiveParam;
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.ReceiveMeetingRoomReservationOrderService;
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.List;


@Slf4j
@Service
public class ReceiveMeetingRoomReservationOrderServiceImpl implements ReceiveMeetingRoomReservationOrderService {


    @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 kafkaMeetingRoomReservationOrderMergeReceive(MeetingRoomReservationOrderReceiveParam 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();
        convertMeetingRoomReservationOrderReceiveParam2Entity(receiveParam, unifiedOrderEntity);


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

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

        for (MeetingRoomReservationOrderGoodsReceiveParam postOfficeOrderGoodsReceiveParam : postOfficeOrderReceiveParamGoodsList) {

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

            unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());

            processUnifiedOrderGoodsList.add(unifiedOrderGoods);

            // 计算成本金额合计
            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.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.getOrderAmount().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.getOrderAmount().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 kafkaMeetingRoomReservationOrderDeleteReceive(String message) {
        // TODO to be conttinued
    }

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

    private void convertMeetingRoomReservationOrderReceiveParam2Entity(MeetingRoomReservationOrderReceiveParam orderReceiveParam, UnifiedOrder unifiedOrderEntity) {

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

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

        unifiedOrderEntity.setAmount(orderReceiveParam.getOrderAmount());
        unifiedOrderEntity.setCostAmount(orderReceiveParam.getOrderCostAmount());
        unifiedOrderEntity.setTransportAmount(orderReceiveParam.getTransportAmount());

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

        // 设定 订单来源
        unifiedOrderEntity.setServiceNo(orderReceiveParam.getServiceNo());
        unifiedOrderEntity.setServiceName(orderReceiveParam.getServiceName());

        unifiedOrderEntity.setRemarks(orderReceiveParam.getRemarks());
        unifiedOrderEntity.setOtherParams(orderReceiveParam.getOtherParams());

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

        unifiedOrderEntity.setCompletState(orderReceiveParam.getCompletState());

        unifiedOrderEntity.setPayType(orderReceiveParam.getPayType());
        unifiedOrderEntity.setPayType(orderReceiveParam.getPayType());

        unifiedOrderEntity.setPayState(orderReceiveParam.getPayState());
        unifiedOrderEntity.setPayStateName(orderReceiveParam.getPayStateName());

        unifiedOrderEntity.setProjectId(orderReceiveParam.getPurchaseOrgId());
        unifiedOrderEntity.setProjectName(orderReceiveParam.getPurchaseOrgName());

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

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

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

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


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

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

        unifiedOrderEntity.setRecUserName(orderReceiveParam.getRecUserName());
        unifiedOrderEntity.setRecUserPhone(orderReceiveParam.getRecUserPhone());
        unifiedOrderEntity.setRecAddress(orderReceiveParam.getRecAddress());

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

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

    }

    private void convertMeetingRoomReservationOrderGoodsReceiveParam2Entity(MeetingRoomReservationOrderGoodsReceiveParam orderGoodsReceiveParam, UnifiedOrderGoods unifiedOrderGoods) {

        unifiedOrderGoods.setGoodsId(orderGoodsReceiveParam.getGoodsId());
        unifiedOrderGoods.setOutSnapshotOrderGoodsId(orderGoodsReceiveParam.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(orderGoodsReceiveParam.getGoodsName());

        unifiedOrderGoods.setGoodsParams(orderGoodsReceiveParam.getGoodsParams());

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

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


        /************************************** update by linjinjy 20200904 20200723_林志鹏_税率,退款格式.docx **************************************/
        unifiedOrderGoods.setTaxCode(orderGoodsReceiveParam.getTaxCode());
        unifiedOrderGoods.setTaxRate(orderGoodsReceiveParam.getTaxRate());
        /************************************** update by linjinjy 20200904 20200723_林志鹏_税率,退款格式.docx **************************************/

        /****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/
        unifiedOrderGoods.setCateIdLv1(orderGoodsReceiveParam.getCateIdLv1());
        unifiedOrderGoods.setCateIdLv2(orderGoodsReceiveParam.getCateIdLv2());
        unifiedOrderGoods.setCateIdLv3(orderGoodsReceiveParam.getCateIdLv3());
        unifiedOrderGoods.setCateNameLv1(orderGoodsReceiveParam.getCateNameLv1());
        unifiedOrderGoods.setCateNameLv2(orderGoodsReceiveParam.getCateNameLv2());
        unifiedOrderGoods.setCateNameLv3(orderGoodsReceiveParam.getCateNameLv3());
        /****************************************** 三级分类 20200904 by linjinyu 20200904_林志鹏_三极分类 ******************************************/

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