package com.zcxk.sync.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zcxk.core.common.exception.BusinessException;
import com.zcxk.sync.enums.SqlType;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Andy
 * @version V1.0
 * @description: base数据同步
 * @date 2021/7/29
 **/
@Slf4j
public class BaseSync<T> {

    /**
    * @author Andy
    * @description 转换
    * @date 10:13 2021/7/29
    * @param msg, syncTable, tClass
    * @return java.util.Map<java.lang.String,java.util.List<T>>
    **/
    public Map<String, List<T>> stringConvertMap(String msg, String syncTable, Class<T> tClass) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        JSONArray jsonArray   = jsonObject.getJSONArray("data");
        String typeSql   = jsonObject.getString("type");
        String tableName = jsonObject.getString("table");
        // 检查数据是否正常
        checkData(jsonArray, typeSql, tableName, syncTable);
        Map<String, List<T>> result = new HashMap<>();
        List<T> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            list.add(JSON.toJavaObject(jsonArray.getJSONObject(i), tClass));
        }
        log.info("【mq sync数据】同步的表名：{}，操作类型：{}，数据大小：{}，同步的数据：{}", syncTable, typeSql, list.size(), jsonArray.toString());
        result.put(typeSql, list);
        return result;
    }

    /**
     * @author Andy
     * @description 检查数据是否符合
     * @date 9:48 2021/7/29
     * @param jsonArray, typeSql, tableName
     * @return boolean
     **/
    private void checkData(JSONArray jsonArray, String typeSql, String tableName, String syncTable){
        if (!syncTable.equals(tableName)) {
            throw BusinessException.builder("【mq sync数据错误】表名不一致，需要同步的表【"+ syncTable +"】，当前同步过来的表：" + tableName);
        }
        try {
            SqlType.valueOf(typeSql);
        } catch (IllegalArgumentException e) {
            throw BusinessException.builder("【mq sync数据错误】表名："+ tableName + "，操作：【"+ typeSql +"】不属于更新操作。" );
        }
        if (jsonArray.size() == 0) {
            throw BusinessException.builder("【mq sync数据错误】表名："+ syncTable + "，无数据需要更新。");
        }
    }

}
