package com.yeejoin.amos.boot.module.jg.biz.statistics.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
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.apache.commons.lang3.StringUtils;
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) {
        Object params = techParamsBackupService.getTechParams(equList, record);
        Map<String, Object> paramsMap = BeanUtil.beanToMap(params);
        List<TechParamItem> techParamItems = TechParamUtil.getParamMetaList(equList);
        List<ESEquipmentInfo.TechParam> techParams = new ArrayList<>();
        techParamItems.forEach(techParamItem -> {
            ESEquipmentInfo.TechParam techParam = new ESEquipmentInfo.TechParam(techParamItem, paramsMap.get(techParamItem.getParamKey()));
            techParams.add(techParam);
        });
        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 postJsonStr){
        if(!isNullOrEmpty(postJsonStr)){
            List<String> posts = JSON.parseArray(postJsonStr, String.class);
            return String.join(",", posts);
        }
        return null;
    }

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

}
