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.enums.order.UnifiedOrderCompletStateUtils;
import cn.superdesk.uniorder.common.json.AnJsonUtils;
import cn.superdesk.uniorder.common.lock.zookeeper.annotation.DistributedLock;
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.dao.mapper.channel.UnifiedChannelProfitSyncMapper;
import cn.superdesk.uniorder.dao.mapper.channel.UnifiedChannelProfitSyncMapperEx;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapper;
import cn.superdesk.uniorder.dao.mapper.unified.UnifiedOrderProfitMapperEx;
import cn.superdesk.uniorder.dto.param.operation.UnifiedOrderIssuesFlowingParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.unified.qyng.UnifiedQyngOrderGoodsReceiveParam;
import cn.superdesk.uniorder.dto.receive.consumer.superdeskmall.unified.qyng.UnifiedQyngOrderReceiveParam;
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.base.CommonOrderTransportProcessService;
import cn.superdesk.uniorder.service.order.receive.ReceiveQyngOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: Java类作用描述
 * @Author: linjinyu
 * @CreateDate: 2020/12/9 下午1:38
 * @UpdateUser: linjinyu
 * @UpdateDate: 2020/12/9 下午1:38
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Slf4j
@Service
public class ReceiveQyngOrderServiceImpl implements ReceiveQyngOrderService {

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

    /****************************************** 退单部分 ******************************************/
    @Autowired
    private UnifiedOrderReturnMapper        unifiedOrderReturnMapper;
    @Autowired
    private UnifiedOrderReturnMapperEx      unifiedOrderReturnMapperEx;
    @Autowired
    private UnifiedOrderReturnGoodsMapper   unifiedOrderReturnGoodsMapper;
    @Autowired
    private UnifiedOrderReturnGoodsMapperEx unifiedOrderReturnGoodsMapperEx;
    /****************************************** 退单部分 ******************************************/

    /****************************************** 分润部分 ******************************************/
    @Autowired
    private UnifiedOrderProfitMapper             unifiedOrderProfitMapper;
    @Autowired
    private UnifiedOrderProfitMapperEx           unifiedOrderProfitMapperEx;
    @Autowired
    private UnifiedChannelProfitSyncMapper       unifiedChannelProfitSyncMapper;
    @Autowired
    private UnifiedChannelProfitSyncMapperEx     unifiedChannelProfitSyncMapperEx;
    /****************************************** 分润部分 ******************************************/

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

    @Autowired
    private CommonEventPublisher commonEventPublisher;

    /**
     * 商城 订单 正常 同步 已证实为-企业采购-福利内购
     *
     * @param receiveParam
     * @return
     */
    @Transactional
    @DistributedLock(name = "#receiveParam.orderSn")
    public UnifiedOrderIssuesFlowingParam kafkaUnifiedQyngOrderReceive(UnifiedQyngOrderReceiveParam receiveParam) {


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

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

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


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


        // 处理订单 商品
        List<UnifiedOrderGoods>                 processUnifiedOrderGoodsList      = new ArrayList<>();
        List<UnifiedQyngOrderGoodsReceiveParam> unifiedOrderGoodsReceiveParamList = receiveParam.getGoods();

        for (UnifiedQyngOrderGoodsReceiveParam unifiedOrderGoodsReceiveParam : unifiedOrderGoodsReceiveParamList) {

            UnifiedOrderGoods unifiedOrderGoods = new UnifiedOrderGoods();
            convertUnifiedQyngOrderGoodsReceiveParam2Entity(unifiedOrderGoodsReceiveParam, unifiedOrderGoods);
            unifiedOrderGoods.setOrderSn(unifiedOrderEntity.getOrderSn());
            processUnifiedOrderGoodsList.add(unifiedOrderGoods);

        }

        /****************************************** 运费要重构 业务逻辑修改 mark by linjinyu at 20201215 start ******************************************/

        commonOrderTransportProcessService.processTransport(unifiedOrderEntity, processUnifiedOrderGoodsList);

        /****************************************** 运费要重构 业务逻辑修改 mark by linjinyu at 20201215   end ******************************************/

        /****************************************** TODO 再核算 20210126 拆单 子单 订单金额有可能是不包含运费 start ******************************************/

        commonOrderProcessService.processOrderAmount(unifiedOrderEntity, processUnifiedOrderGoodsList, receiveParam.getUid());

        /****************************************** TODO 再核算 20210126 拆单 子单 订单金额有可能是不包含运费   end ******************************************/

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


        // TODO ??只接待收货 已完成订单 戴智的注释 进雨??
        // 没有的订单id才可以保存
        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

        }


        // TODO mark by linjinyu 重构 分润 start =================================

        commonEventPublisher.triggerUnifiedOrderProfitCalculationEvent(unifiedOrderEntity);

        // TODO mark by linjinyu 重构 分润  end  =================================


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

        return callback;
    }

    /**
     * 转换程序 order
     *
     * @param unifiedQyngOrderReceiveParam
     * @param unifiedOrderEntity
     */
    public void convertUnifiedQyngOrderReceiveParam2Entity(UnifiedQyngOrderReceiveParam unifiedQyngOrderReceiveParam, UnifiedOrder unifiedOrderEntity) {


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

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

        unifiedOrderEntity.setAmount(unifiedQyngOrderReceiveParam.getPrice());
        unifiedOrderEntity.setCostAmount(BigDecimal.ZERO);

        // 处理 deleted
        unifiedOrderEntity.setCompletState(
                UnifiedOrderCompletStateUtils
                        .convertBySuperDeskMallOrderStatus(
                                unifiedQyngOrderReceiveParam.getOrderState(),
                                unifiedQyngOrderReceiveParam.getDeleted()
                        )
        );

        // 设定 订单来源
        unifiedOrderEntity.setServiceNo(CommonServiceNoEnum.getServiceNoByServiceId(unifiedQyngOrderReceiveParam.getOrderType()));
        unifiedOrderEntity.setServiceName(CommonServiceNoEnum.getServiceNameByServiceId(unifiedQyngOrderReceiveParam.getOrderType()));

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

        unifiedOrderEntity.setCreateUserId(null);
        unifiedOrderEntity.setUpdateUserId(1L);

        unifiedOrderEntity.setCreateTime(unifiedQyngOrderReceiveParam.getCreateTime());
        /****************************************** 加三个时间 start ******************************************/
        unifiedOrderEntity.setPayTime(unifiedQyngOrderReceiveParam.getPayTime());
        unifiedOrderEntity.setSendTime(unifiedQyngOrderReceiveParam.getSendTime());
        unifiedOrderEntity.setFinishTime(unifiedQyngOrderReceiveParam.getFinishTime());
        /****************************************** 加三个时间 start ******************************************/
        unifiedOrderEntity.setUpdateTime(unifiedQyngOrderReceiveParam.getFinishTime());

        unifiedOrderEntity.setProjectId(unifiedQyngOrderReceiveParam.getOrganizationId());
        unifiedOrderEntity.setProjectName(unifiedQyngOrderReceiveParam.getOrganizationName());

        unifiedOrderEntity.setPurchaseUserId(unifiedQyngOrderReceiveParam.getRealNameId());
        unifiedOrderEntity.setPurchaseUserName(unifiedQyngOrderReceiveParam.getRealName());
        unifiedOrderEntity.setPurchasePhone(unifiedQyngOrderReceiveParam.getMobile());

        unifiedOrderEntity.setPurchaseVirtId(unifiedQyngOrderReceiveParam.getEnterpriseId());
        unifiedOrderEntity.setPurchaseVirtName(unifiedQyngOrderReceiveParam.getEnterpriseName());

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

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

        unifiedOrderEntity.setSaleId(unifiedQyngOrderReceiveParam.getMerchId());
        unifiedOrderEntity.setSaleName(unifiedQyngOrderReceiveParam.getMerchName());


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

//        unifiedOrderEntity.setPayType(unifiedQyngOrderReceiveParam.getPayType());
//        unifiedOrderEntity.setPayTypeName(UnifiedOrderPayTypeEnum.get(unifiedQyngOrderReceiveParam.getPayType()).getDesc());
//        unifiedOrderEntity.setOrderState(unifiedQyngOrderReceiveParam.getOrderState());
//        unifiedOrderEntity.setOrderStateName(SuperDeskMallOrderStatusEnum.getDesc(unifiedQyngOrderReceiveParam.getOrderState()));
//        unifiedOrderEntity.setPayState(2); // TODO 写死 标记20200708

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

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

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

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


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

        unifiedOrderEntity.setTransportAmount(unifiedQyngOrderReceiveParam.getDispatchPrice());
        unifiedOrderEntity.setTransportMerchantAssumeAmount(unifiedQyngOrderReceiveParam.getDispatchPriceJd());

        /****************************************** 代客专用 Excel 导入后台账号 start mark by linjinyu at 20201221 ******************************************/
        unifiedOrderEntity.setOperAccount(unifiedQyngOrderReceiveParam.getOperAccount());
        unifiedOrderEntity.setOperName(unifiedQyngOrderReceiveParam.getOperName());
        /****************************************** 代客专用 Excel 导入后台账号   end mark by linjinyu at 20201221 ******************************************/

        // TODO 写死
        unifiedOrderEntity.setUserType("2");
        unifiedOrderEntity.setUserName("系统");

//		unifiedOrderEntity.setRecUserId(); // 没有
        unifiedOrderEntity.setRecUserName(unifiedQyngOrderReceiveParam.getAddressRealName());
        unifiedOrderEntity.setRecUserPhone(unifiedQyngOrderReceiveParam.getAddressMobile());
        unifiedOrderEntity.setRecAddress(unifiedQyngOrderReceiveParam.getAddressAddress());

        unifiedOrderEntity.setRemarks(unifiedQyngOrderReceiveParam.getRemark());

    }

    /**
     * 转换程序 goods
     *
     * @param unifiedOrderGoodsReceiveParam
     * @param unifiedOrderGoods
     */
    public void convertUnifiedQyngOrderGoodsReceiveParam2Entity(UnifiedQyngOrderGoodsReceiveParam unifiedOrderGoodsReceiveParam, UnifiedOrderGoods unifiedOrderGoods) {


        unifiedOrderGoods.setGoodsId(unifiedOrderGoodsReceiveParam.getGoodsId());
        unifiedOrderGoods.setOutSnapshotOrderGoodsId(unifiedOrderGoodsReceiveParam.getOrderGoodsId());

        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(unifiedOrderGoodsReceiveParam.getTitle());

        Map<String, String> goodsParams = new HashMap<>();
        goodsParams.put("taxCode", unifiedOrderGoodsReceiveParam.getTaxCode());
        goodsParams.put("fiscalCode", unifiedOrderGoodsReceiveParam.getFiscalCode());
        unifiedOrderGoods.setGoodsParams(AnJsonUtils.toJson(goodsParams));


        // 关联问题 TAPD_ID_1000681_ 订单管理-导出报表-导出成本EXCEL中添加商品单位(添加至商品数量列后面).md
        // add by linjinyu 20200514 算了就这样修改吧
        unifiedOrderGoods.setUnit(StrUtil.isBlank(unifiedOrderGoodsReceiveParam.getUnit()) ? CommonOrderGoodsUnitEnum.项.getDesc() : unifiedOrderGoodsReceiveParam.getUnit());

        // 销售价 单价
        unifiedOrderGoods.setPrice(unifiedOrderGoodsReceiveParam.getUnitPrice());
        // add costprice 成本价
        unifiedOrderGoods.setCostPrice(unifiedOrderGoodsReceiveParam.getCostPrice());
        // 数量
        unifiedOrderGoods.setQuantity(unifiedOrderGoodsReceiveParam.getTotal());

        // 业务系统 的 订单sn
//		unifiedOrderGoods.setOrderSn(unifiedOrder.getOrderSn());

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

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

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

    }
}
