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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
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.store.api.model.*;
import com.kxs.transfer.api.mapper.store.KxsMachineApplyDetailMapper;
import com.kxs.transfer.api.mapper.store.KxsMachineApplyMapper;
import com.kxs.transfer.api.mapper.user.KxsUserMapper;
import com.kxs.transfer.api.model.table.DMLData;
import com.kxs.transfer.api.model.table.FieldData;
import com.kxs.user.api.model.KxsUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

/**
 * 客小爽机具申请表(KxsMachineApply)表服务实现类
 *
 * @author 系统
 * @since 2024-01-08 09:46:02
 */
@Service("kxsMachineApplyService")
@RequiredArgsConstructor
public class KxsMachineApplyService extends ServiceImpl<KxsMachineApplyMapper, KxsMachineApply> {

    private final KxsMachineApplyDetailMapper kxsMachineApplyDetailMapper;

    private final KxsUserMapper kxsUserMapper;

    public void changeData(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());

        KxsMachineApply machineApply = new KxsMachineApply();

        List<KxsMachineApplyDetail> machineApplyDetailList = new ArrayList<>();

        //操作类型
        OperationType operation = dmlData.getOperation();
        if (operation.equals(OperationType.DELETE)) {
            baseMapper.deleteById(id);
            kxsMachineApplyDetailMapper.delete(Wrappers.<KxsMachineApplyDetail>lambdaQuery().eq(KxsMachineApplyDetail::getOrderId, id));
            return;
        }
        for (String field : changeFieldList) {

            switch (field) {
                case "UserId":
                    int userId = Integer.parseInt(validFieldDataMap.get(field).toString());
                    KxsUser user = kxsUserMapper.selectById(userId);
                    if (user != null) {
                        machineApply.setUsername(user.getUsername());
                        machineApply.setUserCode(user.getUserCode());
                    }
                    machineApply.setUserId(userId);
                    break;
                case "ApplyNo":
                    machineApply.setOrderSn(validFieldDataMap.get(field).toString());
                    break;
                case "BrandId":
                    machineApply.setBrandId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "ProductName":
                    machineApply.setBrandName(validFieldDataMap.get(field).toString());
                    break;
                case "RealName":
                    machineApply.setContacts(validFieldDataMap.get(field).toString());
                    break;
                case "Mobile":
                    machineApply.setPhone(validFieldDataMap.get(field).toString());
                    break;
                case "StoreId":
                    machineApply.setWarehouseId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "ApplyDeviceNum":
                    machineApply.setApplyNum(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "TopUserId":
                    machineApply.setTopUserId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "Areas":
                    String[] split = validFieldDataMap.get(field).toString().split(",");
                    if (split.length == 3) {
                        machineApply.setAddress(split[0] + split[1] + split[2]);
                    }
                    break;
                case "Address":
                    machineApply.setAddress(machineApply.getAddress() + validFieldDataMap.get(field).toString());
                    break;
                case "OperateId":
                    machineApply.setPartnerId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "Sort":
                    int sort = Integer.parseInt(validFieldDataMap.get(field).toString());
                    machineApply.setApplyType(sort == 0 ? 0 : 1);

                    if (fieldDataMap.get("SwapSnExpand").getValue() != null && fieldDataMap.get("OrderExpand").getValue() != null) {
                        String swapSnExpand = fieldDataMap.get("SwapSnExpand").getValue().toString();
                        String orderExpand = fieldDataMap.get("OrderExpand").getValue().toString();
                        if (sort == 0) {
                            //循环机申请
                            String[] machineIds = orderExpand.split(",");
                            for (String machineId : machineIds) {
                                KxsMachineApplyDetail machineApplyDetail = new KxsMachineApplyDetail();
                                machineApplyDetail.setRecycleMachineId(Integer.valueOf(machineId));
                                machineApplyDetail.setOrderId(id);
                                machineApplyDetail.setApplyType(0);
                                machineApplyDetailList.add(machineApplyDetail);
                            }
                        } else {
                            //兑换券申请
                            swapSnExpand = swapSnExpand.replace("\n", ",");
                            String[] ticketCodes = swapSnExpand.split(",");
                            String[] ticketIds = orderExpand.split(",");
                            for (int i = 0; i < ticketCodes.length; i++) {
                                String[] sns = ticketCodes[i].split(":");
                                KxsMachineApplyDetail machineApplyDetail = new KxsMachineApplyDetail();
                                machineApplyDetail.setTicketCode(sns[0]);
                                machineApplyDetail.setApplyType(1);
                                machineApplyDetail.setTicketId(Integer.valueOf(ticketIds[i]));
                                machineApplyDetail.setOrderId(id);
                                machineApplyDetailList.add(machineApplyDetail);
                            }
                        }
                    }
                    break;
                case "Status":
                    int status = Integer.parseInt(validFieldDataMap.get(field).toString());
                    machineApply.setStatus(status == -1 ? 2 : status);
                    break;
                case "DeliveryType":
                    int deliveryType = Integer.parseInt(validFieldDataMap.get(field).toString());
                    machineApply.setGetMode(deliveryType == 1 ? 1 : 0);
                    break;
                case "CreateDate":
                    machineApply.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    machineApply.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;

            }
        }
        if (operation.equals(OperationType.UPDATE)) {
            machineApply.setId(id);
            baseMapper.updateById(machineApply);
        }
        if (operation.equals(OperationType.INSERT)) {
            KxsMachineApply kxsMachineApply = baseMapper.selectById(id);
            if (kxsMachineApply == null) {
                machineApply.setId(id);
                baseMapper.insert(machineApply);
                if (!machineApplyDetailList.isEmpty()) {
                    for (KxsMachineApplyDetail machineApplyDetail : machineApplyDetailList) {
                        kxsMachineApplyDetailMapper.insert(machineApplyDetail);
                    }
                }
            }
        }
    }


}

