package com.yeejoin.equipmanage.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.component.rule.MethodParam;
import com.yeejoin.amos.component.rule.RuleActionBean;
import com.yeejoin.amos.component.rule.RuleMethod;
import com.yeejoin.amos.component.rule.RuleTrigger;
import com.yeejoin.equipmanage.common.dto.EquipIndexDto;
import com.yeejoin.equipmanage.common.entity.EquipmentSpecificIndex;
import com.yeejoin.equipmanage.common.entity.FireFightingSystemEntity;
import com.yeejoin.equipmanage.common.enums.TopicEnum;
import com.yeejoin.equipmanage.common.enums.TrueOrFalseEnum;
import com.yeejoin.equipmanage.service.IEquipmentSpecificIndexSerivce;
import com.yeejoin.equipmanage.service.IFireFightingSystemService;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.typroject.tyboot.component.emq.EmqKeeper;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author keyong
 * @title: FireSystemAction
 * <pre>
 * @description: 消防系统运行状态
 * </pre>
 * @date 2023/10/11 16:50
 */
@Component
@RuleActionBean(beanLabel = "消防系统运行状态")
public class FireSystemAction {

    public static final Logger log = LoggerFactory.getLogger(FireSystemAction.class);

    @Autowired
    protected EmqKeeper emqKeeper;

    @Autowired
    private IFireFightingSystemService systemService;

    @Autowired
    private IEquipmentSpecificIndexSerivce specificIndexSerivce;

    @Value("classpath:/json/systemStateIndex.json")
    private Resource systemStateIndex;

    /**
     *
     * @param code
     * @param systemTypeCode
     * @param runStateCode
     * @description  methodLabel是配置的方法名label，project是规则调用的文件夹名称，方法配置在预案文件夹中
     */
    @RuleMethod(methodLabel = "更新消防系统运行状态", project = "换流站消防专项预案")
    public void changeFireSystemRunState(@MethodParam(paramLabel = "系统编码") String code,
                                         @MethodParam(paramLabel = "系统类型编码") String systemTypeCode,
                                         @MethodParam(paramLabel = "系统运行状态") String runStateCode,
                                         @MethodParam(paramLabel = "多指标复合判断") String boolValue,
                                         @MethodParam(paramLabel = "测点指标数据") Object paramObj) throws Exception {
        log.info("规则调用装备改变系统运行状态>>>>>>>>>>>>>>>>>" + JSON.toJSONString(paramObj));
        boolean bool = Boolean.FALSE;
        LambdaQueryWrapper<FireFightingSystemEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FireFightingSystemEntity::getCode, code).eq(FireFightingSystemEntity::getSystemTypeCode, systemTypeCode);
        FireFightingSystemEntity entity = systemService.getOne(queryWrapper);
        if (TrueOrFalseEnum.real.value.equalsIgnoreCase(boolValue)) {
            // 此方法只针对多条件 与 的逻辑
            EquipIndexDto dto = JSONObject.parseObject(paramObj.toString(), EquipIndexDto.class);
            String json = null;
            try {
                json = IOUtils.toString(systemStateIndex.getInputStream(), java.lang.String.valueOf(StandardCharsets.UTF_8));
            } catch (IOException e) {
                e.printStackTrace();
            }
            List<Map> mapList = JSONObject.parseArray(json, Map.class);
            List<Map> resultList = mapList.stream().filter(x -> systemTypeCode.equalsIgnoreCase(String.valueOf(x.get("typeCode")))).collect(Collectors.toList());
            List<EquipIndexDto> indexDtos = new ArrayList<>();
            resultList.forEach(x -> {
                List<EquipIndexDto> list = JSONArray.parseArray(String.valueOf(x.get("indexVo")), EquipIndexDto.class);
                indexDtos.addAll(list);
            });
            List<EquipIndexDto> list = indexDtos.stream().filter(x -> !dto.getIndexKey().equalsIgnoreCase(String.valueOf(x.getIndexKey()))).collect(Collectors.toList());
            boolean flag = Boolean.TRUE;
            for (EquipIndexDto o : list) {
                // 此处由于测点装备可能不跟系统绑定，所以此处默认取第一个
                EquipmentSpecificIndex index = specificIndexSerivce.getOne(new QueryWrapper<EquipmentSpecificIndex>().eq("equipment_index_key", o.getIndexKey()).orderByDesc("update_date").last("limit 1"));

                if (o.getIndexValue().equalsIgnoreCase(index.getValue())){
                    break;
                } else {
                    flag = Boolean.FALSE;
                    break;
                }

            }
            if (flag) {
                entity.setSystemRunState(runStateCode);
                bool = systemService.saveOrUpdate(entity);
            }
        } else {
            entity.setSystemRunState(runStateCode);
            log.info("装备更新系统表信息>>>> >>>>>>>>>>>>>>" + JSON.toJSONString(entity));
            bool = systemService.saveOrUpdate(entity);
        }
        if (bool) {
            entity.setIsAlarm(1);
            entity.setUUID(UUID.randomUUID().toString());
            emqKeeper.getMqttClient().publish(TopicEnum.XFXTYXZT.getTopic(), JSON.toJSONString(entity).getBytes(), 1, false);
        }
    }
}
