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 cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.KxsBrand;
import com.kxs.product.api.model.KxsMachine;
import com.kxs.store.api.model.*;
import com.kxs.system.api.model.SysUserRole;
import com.kxs.transfer.api.mapper.product.KxsBrandMapper;
import com.kxs.transfer.api.mapper.product.KxsMachineMapper;
import com.kxs.transfer.api.mapper.store.KxsWarehouseMachineApplyDetailMapper;
import com.kxs.transfer.api.mapper.store.KxsWarehouseMachineApplyMapper;
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 com.kxs.user.api.model.KxsUserAdvance;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 客小爽分仓申请补货订单表(KxsWarehouseMachineApply)表服务实现类
 *
 * @author 系统
 * @since 2024-01-08 09:46:02
 */
@Service("kxsWarehouseMachineApplyService")
@RequiredArgsConstructor
public class KxsWarehouseMachineApplyService extends ServiceImpl<KxsWarehouseMachineApplyMapper, KxsWarehouseMachineApply> {

    private final KxsUserMapper kxsUserMapper;

    private final KxsBrandMapper kxsBrandMapper;

    private final KxsWarehouseMachineApplyDetailMapper kxsWarehouseMachineApplyDetailMapper;

    private final KxsMachineMapper kxsMachineMapper;

    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());

        KxsWarehouseMachineApply warehouseMachineApply = new KxsWarehouseMachineApply();

        ArrayList<KxsWarehouseMachineApplyDetail> machineApplyDetails = new ArrayList<>();


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

            switch (field) {
                case "UserId":
                    int userId = Integer.parseInt(validFieldDataMap.get(field).toString());
                    KxsUser user = kxsUserMapper.selectById(userId);
                    Optional.ofNullable(user).ifPresent(t -> {
                            warehouseMachineApply.setUserId(userId);
                            warehouseMachineApply.setUsername(user.getUsername());
                            warehouseMachineApply.setUserCode(user.getUserCode());
                        }
                    );
                    break;
                case "ApplyNum":
                    warehouseMachineApply.setApplyNum(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "SendSn":
                    List<JSONObject> applyData = new ArrayList<>();
                    String applyJson = validFieldDataMap.get(field).toString();
                    JSONArray parse = JSON.parseArray(applyJson);
                    for (Object data : parse) {
                        JSONObject jsonObject = (JSONObject) data;
                        JSONObject apply = new JSONObject();
                        Integer brandId = jsonObject.getInteger("BrandId");
                        KxsBrand brand = kxsBrandMapper.selectById(brandId);
                        apply.put("number", jsonObject.getInteger("ApplyNum"));
                        apply.put("brandId", jsonObject.getInteger("BrandId"));
                        apply.put("brandName", brand.getName());
                        applyData.add(apply);
                    }
                    warehouseMachineApply.setApplyData(JSON.toJSONString(applyData));
                    break;
                case "SeoDescription":
                    Optional.ofNullable(fieldDataMap.get("SeoDescription").getValue()).ifPresent(t -> {
                        Map<Integer, String> applyDatas = new HashMap<>();
                        String applyJsonStr =  fieldDataMap.get("SendSn").getValue().toString();
                        JSONArray applyJsons = JSON.parseArray(applyJsonStr);
                        for (Object data : applyJsons) {
                            JSONObject jsonObject = (JSONObject) data;
                            Integer brandId = jsonObject.getInteger("BrandId");
                            KxsBrand brand = kxsBrandMapper.selectById(brandId);
                            applyDatas.put(brandId, brand.getName());
                        }

                        String sns = fieldDataMap.get("SeoDescription").getValue().toString();
                        String[] split = sns.split(StrUtil.COMMA);
                        for (String sn : split) {
                            KxsWarehouseMachineApplyDetail machineApplyDetail = new KxsWarehouseMachineApplyDetail();
                            KxsMachine kxsMachine = kxsMachineMapper.selectOne(Wrappers.<KxsMachine>lambdaQuery().eq(KxsMachine::getPosSn, sn));
                            Optional.ofNullable(kxsMachine).ifPresent(item -> {
                                machineApplyDetail.setPosSn(item.getPosSn());
                                machineApplyDetail.setBrandId(item.getBrandId());
                                machineApplyDetail.setOrderId(id);
                                machineApplyDetail.setBrandName(applyDatas.get(item.getBrandId()));
                                machineApplyDetails.add(machineApplyDetail);
                            });
                        }
                    });
                    break;
                case "ApplyNo":
                    warehouseMachineApply.setOrderSn(validFieldDataMap.get(field).toString());
                    break;
                case "SendNum":
                    warehouseMachineApply.setSendNum(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "UseAmount":
                    warehouseMachineApply.setUseAmount(new BigDecimal(validFieldDataMap.get(field).toString()));
                    break;
                case "ErpCode":
                    warehouseMachineApply.setErpNo(validFieldDataMap.get(field).toString());
                    break;
                case "SendMode":
                    warehouseMachineApply.setErpName(validFieldDataMap.get(field).toString());
                    break;
                case "SeoKeyword":
                    warehouseMachineApply.setRemark(validFieldDataMap.get(field).toString());
                    break;
                case "Status":
                    warehouseMachineApply.setStatus(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "SeoTitle":
                    warehouseMachineApply.setUpdateBy(validFieldDataMap.get(field).toString());
                    break;
                case "CreateDate":
                    warehouseMachineApply.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    warehouseMachineApply.setUpdateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
            }
        }
        if (operation.equals(OperationType.UPDATE)) {
            warehouseMachineApply.setId(id);
            baseMapper.updateById(warehouseMachineApply);
            if (!machineApplyDetails.isEmpty()) {
                kxsWarehouseMachineApplyDetailMapper.delete(Wrappers.<KxsWarehouseMachineApplyDetail>lambdaQuery().eq(KxsWarehouseMachineApplyDetail::getOrderId, id));
                for (KxsWarehouseMachineApplyDetail machineApplyDetail : machineApplyDetails) {
                    kxsWarehouseMachineApplyDetailMapper.insert(machineApplyDetail);
                }
            }
        }
        if (operation.equals(OperationType.INSERT)) {
            KxsWarehouseMachineApply kxsWarehouseMachineApply = baseMapper.selectById(id);
            if (kxsWarehouseMachineApply == null) {
                warehouseMachineApply.setId(id);
                baseMapper.insert(warehouseMachineApply);
            }
        }
    }
}

