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

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.aliyun.dts.subscribe.clients.record.OperationType;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kxs.transfer.api.mapper.user.KxsUserPresetBeforeMapper;
import com.kxs.transfer.api.model.table.DMLData;
import com.kxs.transfer.api.model.table.FieldData;
import com.kxs.user.api.model.KxsUserPresetBefore;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 用户存量预设职级表(KxsUserPresetBefore)表服务实现类
 *
 * @author 系统
 * @since 2024-06-07 16:24:47
 */
@Service("kxsUserPresetBeforeService")
public class KxsUserPresetBeforeService extends ServiceImpl<KxsUserPresetBeforeMapper, KxsUserPresetBefore>  {

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

        KxsUserPresetBefore presetLog = new KxsUserPresetBefore();
        presetLog.setId(id);
        //操作类型
        OperationType operation = dmlData.getOperation();
        if (operation.equals(OperationType.DELETE)) {
            // 更新数据
            baseMapper.deleteById(id);
            return;
        }

        for (String field : changeFieldList) {

            switch (field) {
                case "UserId":
                    presetLog.setUserId(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "Rank":
                    presetLog.setPresetLevel(Integer.valueOf(validFieldDataMap.get(field).toString()));
                    break;
                case "CreateDate":
                    presetLog.setStartTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    presetLog.setCreateTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
                case "UpdateDate":
                    presetLog.setEndTime(LocalDateTimeUtil.parse(validFieldDataMap.get(field).toString(), DatePattern.NORM_DATETIME_PATTERN));
                    break;
            }
        }

        if (operation.equals(OperationType.UPDATE)) {
            // 更新数据
            baseMapper.updateById(presetLog);
        }
        if (operation.equals(OperationType.INSERT)) {

            KxsUserPresetBefore userPresetLog = baseMapper.selectById(presetLog.getId());
            if (userPresetLog != null) {
                baseMapper.updateById(presetLog);
            } else {
                // 插入数据
                baseMapper.insert(presetLog);
            }
        }
    }
}

