package com.yeejoin.amos.boot.module.jg.biz.refresh;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.yeejoin.amos.boot.module.common.api.dto.ITechParamDefine;
import com.yeejoin.amos.boot.module.common.api.dto.TechParamItem;
import com.yeejoin.amos.boot.module.common.api.entity.ESEquipmentInfo;
import com.yeejoin.amos.boot.module.common.biz.utils.TechParamUtil;
import com.yeejoin.amos.boot.module.jg.biz.edit.backup.TechParamsBackupService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

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

@Service
@RequiredArgsConstructor
public class StatisticsDataUpdateService {

    private final TechParamsBackupService techParamsBackupService;


    public List<ESEquipmentInfo.TechParam> getTechParams(String equList, String record) {
        List<ESEquipmentInfo.TechParam> techParams = new ArrayList<>();
        try {
            Object params = techParamsBackupService.getTechParams(equList, record);
            // 类型转换，否则类型处理错误
            Class<? extends ITechParamDefine> clazz = TechParamUtil.getParamClazz(equList);
            ITechParamDefine paramInstance = clazz.newInstance();
            BeanUtil.copyProperties(params, paramInstance);

            Map<String, Object> paramsMap = BeanUtil.beanToMap(paramInstance);
            List<TechParamItem> techParamItems = TechParamUtil.getParamMetaList(equList);
            techParamItems.forEach(techParamItem -> {
                ESEquipmentInfo.TechParam techParam = new ESEquipmentInfo.TechParam(techParamItem, paramsMap.get(techParamItem.getParamKey()));
                techParams.add(techParam);
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return techParams;
    }


    /**
     *  判断字符串是否为合法的 JSON 格式
     */
    public static boolean isJSONValid(String test) {
        try {
            JSON.parseArray(test);
            return true;
        } catch (Exception ex) {
            return false;
        }
    }

    public static String castList2String(List<String> posts){
        return String.join(",", posts);
    }

    public static String castStrList2String(String jsonTypesStr){
        if(!isNullOrEmpty(jsonTypesStr)){
            if(isJSONValid(jsonTypesStr)){
                List<String> posts = JSON.parseArray(jsonTypesStr, String.class);
                return String.join(",", posts);
            }
            return jsonTypesStr;
        }
        return null;
    }

    public static boolean isNullOrEmpty(String str) {
        return str == null || str.trim().isEmpty() || "null".equals(str);
    }

}
