package com.kxs.transfer.api.service.product.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.dts.subscribe.clients.record.OperationType;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.product.api.model.*;
import com.kxs.store.api.model.KxsMachineApplyDetail;
import com.kxs.system.api.model.KxsMorningLog;
import com.kxs.system.api.model.KxsSchoolMenu;
import com.kxs.transfer.api.mapper.product.KxsMachineMapper;
import com.kxs.transfer.api.mapper.product.KxsShopOrderInfoMapper;
import com.kxs.transfer.api.mapper.product.KxsShopOrderMapper;
import com.kxs.transfer.api.mapper.product.KxsTicketMapper;
import com.kxs.transfer.api.mapper.store.KxsMachineApplyDetailMapper;
import com.kxs.transfer.api.mapper.store.KxsMachineApplyMapper;
import com.kxs.transfer.api.model.table.DMLData;
import com.kxs.transfer.api.model.table.FieldData;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 商城订单表(KxsShopOrder)表服务实现类
 *
 * @author 系统
 * @since 2023-12-20 10:09:35
 */
@Service("kxsShopOrderService")
@RequiredArgsConstructor
public class KxsShopOrderService extends ServiceImpl<KxsShopOrderMapper, KxsShopOrder>  {

    private final KxsShopOrderInfoMapper kxsShopOrderInfoMapper;

    private final KxsMachineMapper kxsMachineMapper;

    private final KxsMachineApplyDetailMapper kxsMachineApplyDetailMapper;
    private final KxsTicketMapper kxsTicketMapper;


    public void changeData(DMLData dmlData) {
        //修改的字段值
        Map<String, Object> validFieldDataMap = dmlData.getValidFieldDataMap();
        //全部字段值
        Map<String, FieldData> fieldDataMap = dmlData.getFieldDataMap();
        //修改的字段
        List<String> changeFieldList = dmlData.getChangeFieldList();

        if(fieldDataMap.get("Sort") == null){
            return;
        }
        if(fieldDataMap.get("Sort").getValue() == null){
            return;
        }
        int sort = Integer.parseInt(fieldDataMap.get("Sort").getValue().toString());
        if(sort != 0){
            //获取发货的机具号列表
            if(fieldDataMap.get("SnNos").getValue() != null){
                String sns = fieldDataMap.get("SnNos").getValue().toString();
                String[] split = sns.split(",");
                //机具申请订单，把发货的机具绑定的机具申请的订单详情表里
                List<KxsMachineApplyDetail> kxsMachineApplyDetails = kxsMachineApplyDetailMapper.selectList(Wrappers.<KxsMachineApplyDetail>lambdaQuery().eq(KxsMachineApplyDetail::getOrderId, sort));
                if(split.length == kxsMachineApplyDetails.size()){
                    for (int i = 0; i < kxsMachineApplyDetails.size(); i++) {
                        kxsMachineApplyDetails.get(i).setPosSn(split[i]);
                        KxsMachine kxsMachine = kxsMachineMapper.selectOne(Wrappers.<KxsMachine>lambdaQuery().eq(KxsMachine::getPosSn, split[i]));
                        if(kxsMachine != null){
                            kxsMachineApplyDetails.get(i).setMachineId(kxsMachine.getId());
                            kxsMachineApplyDetailMapper.updateById(kxsMachineApplyDetails.get(i));
                        }
                    }
                }
            }
            return;
        }else{
            //机具券订单
            if(fieldDataMap.get("SnNos").getValue() != null){
                String sns = fieldDataMap.get("SnNos").getValue().toString();
                String[] split = sns.split(StrUtil.COMMA);
                List<KxsTicket> kxsTickets = kxsTicketMapper.selectList(Wrappers.<KxsTicket>lambdaQuery().in(KxsTicket::getTicketCode, split));
                if(kxsTickets != null){
                    for (KxsTicket kxsTicket : kxsTickets) {
                        kxsTicket.setOrderId(Integer.valueOf(dmlData.getId()));
                        kxsTicketMapper.updateById(kxsTicket);
                    }
                }
            }
        }
        //操作的主键
        int id = Integer.parseInt(dmlData.getId());

        KxsShopOrder order = new KxsShopOrder();
        order.setId(id);

        OperationType operation = dmlData.getOperation();
        if(operation.equals(OperationType.DELETE)){
            baseMapper.deleteById(id);
            return;
        }

        for (String field : changeFieldList) {

            switch (field) {
                case "TopUserId":
                    order.setTopUserId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "UserId":
                    order.setUserId(Long.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "OrderNo":
                    order.setOrderSn(validFieldDataMap.get(field).toString());
                    break;
                case "DeliveryType":
                    int deliveryType = Integer.parseInt(validFieldDataMap.get(field).toString());
                    order.setGetMode(deliveryType == 1 ? 1 : 0);
                    break;
                case "PayMode":
                    int payType = Integer.parseInt(validFieldDataMap.get(field).toString());
                    if(payType == 3){
                        order.setPayType(0);
                    } else if (payType == 4){
                        order.setPayType(3);
                    }else {
                        order.setPayType(payType);
                    }
                    break;
                case "PayDate":
                    order.setPayTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "SendDate":
                    order.setSendTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "Remark":
                    order.setRemark(validFieldDataMap.get(field) != null ? validFieldDataMap.get(field).toString(): null);
                    break;
                case "RealName":
                    order.setConsignee(validFieldDataMap.get(field) != null ? validFieldDataMap.get(field).toString(): null);
                    break;
                case "Mobile":
                    order.setPhone(validFieldDataMap.get(field) != null ? validFieldDataMap.get(field).toString(): null);
                    break;
                case "Address":
                    order.setAddress(validFieldDataMap.get(field) != null ? validFieldDataMap.get(field).toString(): null);
                    break;
                case "ErpCode":
                    order.setErpSn(validFieldDataMap.get(field).toString());
                    break;
                case "ErpName":
                    order.setErpName(validFieldDataMap.get(field).toString());
                    break;
                case "RefundReason":
                    order.setReturnReason(validFieldDataMap.get(field).toString());
                    break;
                case "UpdateMan":
                    order.setUpdateBy(validFieldDataMap.get(field).toString());
                    break;
                case "TotalPrice":
                    order.setTotalPrice(new BigDecimal(validFieldDataMap.get(field).toString()));
                    order.setPayPrice(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "RefundActAmount":
                    order.setReturnPrice(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "TradeNo":
                    order.setTradeNo(validFieldDataMap.get(field).toString());
                    break;
                case "StoreId":
                    order.setWarehouseId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "Status":
                    int status = Integer.parseInt(validFieldDataMap.get(field).toString());
                    if(status == -1){
                        order.setStatus(4);
                    } else if (status == 2) {
                        order.setStatus(3);
                    } else if (status == 4) {
                        order.setReturnStatus(2);
                        order.setStatus(2);
                    }else {
                        order.setStatus(status);
                    }
                    break;
                case "RefundStatus":
                    int returnStatus = Integer.valueOf(validFieldDataMap.get(field).toString());
                    if(returnStatus == 1){
                        order.setReturnStatus(2);
                    }else{
                        order.setReturnStatus(0);
                    }
                    break;
                case "CreateDate":
                    order.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    order.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
            }
        }
        if(operation.equals(OperationType.UPDATE)){
            // 更新数据
            baseMapper.updateById(order);
        }
        if(operation.equals(OperationType.INSERT)){
            KxsShopOrder kxsShopOrder = baseMapper.selectById(id);
            if (kxsShopOrder != null){
                baseMapper.updateById(order);
            }else{
                // 插入数据
                baseMapper.insert(order);
            }
        }
    }

    public void changeInfoData(DMLData dmlData) {
        //修改的字段值
        Map<String, Object> validFieldDataMap = dmlData.getValidFieldDataMap();
        //全部字段值
        Map<String, FieldData> fieldDataMap = dmlData.getFieldDataMap();
        //修改的字段
        List<String> changeFieldList = dmlData.getChangeFieldList();
        //操作的主键
        int id = Integer.parseInt(dmlData.getId());

        KxsShopOrderInfo orderInfo = new KxsShopOrderInfo();
        orderInfo.setId(id);

        OperationType operation = dmlData.getOperation();
        if(operation.equals(OperationType.DELETE)){
            baseMapper.deleteById(id);
            return;
        }
        for (String field : changeFieldList) {

            switch (field) {
                case "ProductId":
                    orderInfo.setGoodsId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "OrderId":
                    orderInfo.setOrderId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "ProductName":
                    orderInfo.setGoodsName(validFieldDataMap.get(field).toString());
                    break;
                case "ProductCount":
                    orderInfo.setNumber(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "ProductPhoto":
                    orderInfo.setPicUrl(validFieldDataMap.get(field).toString());
                    break;
                case "NormDetail":
                    if(validFieldDataMap.get(field) == null){
                        orderInfo.setSpecifications("默认");
                    }else{
                        orderInfo.setSpecifications(validFieldDataMap.get(field).toString());
                    }
                    break;
                case "NormId":
                    if(validFieldDataMap.get(field) == null){
                        orderInfo.setSkuId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    }else{
                        orderInfo.setSkuId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    }
                    break;
                case "ProductPrice":
                    orderInfo.setGoodsPrice(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "CreateDate":
                    orderInfo.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    orderInfo.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
            }
        }
        if(StrUtil.isEmpty(orderInfo.getSpecifications())){
            orderInfo.setSpecifications("默认");
        }
        if(operation.equals(OperationType.UPDATE)){
            // 更新数据
            kxsShopOrderInfoMapper.updateById(orderInfo);
        }
        if(operation.equals(OperationType.INSERT)){
            KxsShopOrderInfo kxsShopOrderInfo = kxsShopOrderInfoMapper.selectById(id);
            if (kxsShopOrderInfo != null){
                kxsShopOrderInfoMapper.updateById(orderInfo);
            }else{
                // 插入数据
                kxsShopOrderInfoMapper.insert(orderInfo);
            }
        }
    }
}

