package com.skr.mdm.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.skr.mdm.bean.qo.GaodeTerminalQO;
import com.skr.mdm.entity.DeviceEquipmentDO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @author nfq
 * @date 2023-03-01 9:41
 */
@Slf4j
public class RegisterEquipmentUtil {

    private static final Integer COUNT_EQUIPMENT = 9;

    /**
     * 生成设备名
     *
     * @param equipmentDOList 用户下的设备集合
     * @param userName        用户名
     * @return 设备名
     */
    public static String createEquipmentName(List<String> equipmentNameList, String userName) {
        if (CollectionUtils.isEmpty(equipmentNameList)) {
            return userName + "01";
        }
        List<Integer> numberList = new ArrayList<>(equipmentNameList.size());
        equipmentNameList.forEach(equipmentName -> {
            if (equipmentName.length() == userName.length() + 2) {
                String number = StringUtils.substringAfter(equipmentName, userName);
                if (StringUtils.isNumeric(number)) {
                    numberList.add(Integer.valueOf(number));
                }
            }
        });
        if (CollectionUtils.isEmpty(numberList)) {
            return userName + "01";
        }
        Integer max = CollectionUtil.max(numberList);
        if (max < COUNT_EQUIPMENT) {
            max++;
            return userName + "0" + max;
        }
        max++;
        return userName + max;
    }

    /**
     * 注册高德终端
     *
     * @param gaodeTerminalQO 高德终端请求对象
     * @param equipmentDO     设备实体
     * @return 设备实体
     */
    public static DeviceEquipmentDO registerGaodeTerminal(GaodeTerminalQO gaodeTerminalQO, DeviceEquipmentDO equipmentDO) {
        if (gaodeTerminalQO.getSid() == null) {
            return equipmentDO;
        }
        Integer tid = GaodeMapAPIUtil.getTerminal(gaodeTerminalQO);
        if (tid == null) {
            tid = GaodeMapAPIUtil.addTerminal(gaodeTerminalQO);
        }
        Integer trid = GaodeMapAPIUtil.addTrack(gaodeTerminalQO.getSid(), tid);
        if (tid == null || trid == null) {
            log.error("注册高德猎鹰终端失败 tid:{} trid:{} 设备信息：{}", tid, trid, JSONUtil.toJsonStr(equipmentDO));
        }
        equipmentDO.setTid(tid);
        equipmentDO.setTrid(trid);
        return equipmentDO;
    }
}
