package nckd.jimin.jyyy.hr.wtc.wtbs.util;

import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.wtc.wtbs.common.util.WTCMaps;

import java.util.HashMap;
import java.util.Map;

import static kd.wtc.wtp.constants.WTPProjConstants.WTC_WTP_BUSINESS;

/**
 * 取数项目中数组类型工具类
 * @author rd_shancheng_chen
 * @since 2024-07-16 11:11
 */
public final class RetrievalItemArrUtils {

    private static final Log LOG = LogFactory.getLog(RetrievalItemArrUtils.class);

    private static Object[] getRealLineArr(Object[] objArr) {
        try {
            // 空则返回空数组
            if (objArr == null || objArr.length == 0) {
                return null;
            }
            // 判断数组的类型
            if (objArr.getClass().getComponentType() == null) {
                throw new IllegalArgumentException("illegal input type");
            } else if (objArr[0] instanceof Map) {
                return objArr;
            } else if (objArr[0].getClass().isAssignableFrom(String.class)) {
                Object[] res = new HashMap[objArr.length];
                for (int i = 0; i < objArr.length; i++) {
                    JSONObject jsonObject = JSONObject.parseObject(objArr[i].toString());
                    Map<String, Object> resultMap = WTCMaps.JsonToMap(jsonObject);
                    res[i] = resultMap;
                }
                return res;
            } else {
                throw new IllegalArgumentException("llegal input type:" + objArr[0].getClass().getName());
            }
        } catch (Exception exp) {
            LOG.warn("RetrievalItemArrUtils getRealLineArr fail:lineArr={}", objArr);
            throw new KDBizException(ResManager.loadKDString("数组参数不符合规范：{0}", "RetrievalItemArrUtils_1", WTC_WTP_BUSINESS, exp.getMessage()));
        }
    }

    /**
     * 给数组对象设值
     *
     * @param lineArr  数组对象,[{key:value,xxx}, {xxx}]结构 
     * @param lineArr 下标，从0开始
     * @param fieldName fieldName字段，支持xxx.xxx.xxx
     * @return Object  可能为NULL， boolean返回 'Y'和'N'
     */
    public static Object getRetrievalItemArrLineDetailValue(Object[] lineArr, Integer rowNum, String fieldName) {
        lineArr = getRealLineArr(lineArr);
        if (rowNum == null) {
            LOG.warn("RetrievalItemArrUtils getRetrievalItemArrLineDetailValue fail:rowNum is null");
            throw new KDBizException(ResManager.loadKDString("所读取的行数不得为空。", "RetrievalItemArrUtils_2", WTC_WTP_BUSINESS, rowNum));
        }
        if (rowNum < 0) {
            LOG.warn("RetrievalItemArrUtils getRetrievalItemArrLineDetailValue fail:rowNum < 0,rowNum={}", rowNum);
            throw new KDBizException(ResManager.loadKDString("所读取的行数（{0}）不得小于0。", "RetrievalItemArrUtils_3", WTC_WTP_BUSINESS, rowNum));
        }
        if (lineArr == null || lineArr.length == 0) {
            LOG.warn("RetrievalItemArrUtils getRetrievalItemArrLineDetailValue fail:lineArr isEmpty");
            throw new KDBizException(ResManager.loadKDString("没有可读取的数据。", "RetrievalItemArrUtils_4", WTC_WTP_BUSINESS));
        }
        if (rowNum >= lineArr.length) {
            LOG.warn("RetrievalItemArrUtils getRetrievalItemArrLineDetailValue fail:rowNum >= lineArr.length,rowNum={},lineArr.length={}", rowNum, lineArr.length);
            throw new KDBizException(ResManager.loadKDString("所读取的行数（{0}）超出可读取的数据范围（{1}）。", "RetrievalItemArrUtils_5", WTC_WTP_BUSINESS, rowNum, lineArr.length));
        }
        if (!(lineArr[0] instanceof Map)) {
            LOG.warn("RetrievalItemArrUtils getRetrievalItemArrLineDetailValue fail:!(lineArr[0] instanceof Map,lineArr={}", lineArr[0].getClass().getName());
            throw new KDBizException(ResManager.loadKDString("不是map数组。", "RetrievalItemArrUtils_6", WTC_WTP_BUSINESS));
        }
        Map<String, Object> line = (Map) lineArr[rowNum];
        if (!line.containsKey(fieldName)) {
            LOG.warn("RetrievalItemArrUtils getRetrievalItemArrLineDetailValue fail:!line.containsKey(fieldName),line={},fieldName={}", line, fieldName);
            throw new KDBizException(ResManager.loadKDString("读取失败，不存在字段：{0}。", "RetrievalItemArrUtils_7", WTC_WTP_BUSINESS, fieldName));
        } else {
            Object fieldValue = line.get(fieldName);
            if (fieldValue instanceof Boolean) {
                if ((Boolean) fieldValue) {
                    fieldValue = "Y";
                } else {
                    fieldValue = "N";
                }
            }
            return fieldValue;
        }
    }


    /**
     * 给数组对象设值
     *
     * @param mapArray  数组对象,[{key:value,xxx}, {xxx}]结构 
     * @param index 下标，从0开始
     * @param key key
     * @param value  value
     * @return mapArray
     */
    public static Object[] setArrayMapValue(Object[] mapArray, Integer index, String key, Object value) {
        if (mapArray == null) {
            mapArray = new Object[index + 1];
        } else {
            Object[] newArr = new Object[index + 1];
            if (mapArray.length < newArr.length) {
                // 拷贝
                System.arraycopy(mapArray, 0, newArr, 0, mapArray.length);
                mapArray = newArr;
            }
        }
        for (int i = 0; i < mapArray.length; i++) {
            if (mapArray[i] == null) {
                mapArray[i] = new HashMap<>();
            }
        }
        ((Map) mapArray[index]).put(key, value);

        return mapArray;
    }

}