package com.dcsoft.system.ladder.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dcsoft.common.core.constant.Constants;
import com.dcsoft.common.core.enums.exception.CommonExceptionEnum;
import com.dcsoft.common.core.exception.ServiceException;
import com.dcsoft.system.domain.SysEquipment;
import com.dcsoft.system.ladder.domain.DeviceTreeVo;
import com.dcsoft.system.ladder.domain.StoreyInfoVo;
import com.dcsoft.system.ladder.domain.TLadderConfig;
import com.dcsoft.system.ladder.domain.TLadderRule;
import com.dcsoft.system.ladder.mapper.TLadderConfigMapper;
import com.dcsoft.system.ladder.service.ITLadderConfigService;
import com.dcsoft.system.utils.FloorUtil;
import com.dcsoft.system.utils.TreeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

import static com.dcsoft.common.core.utils.PageUtils.startPage;


/**
 * 梯控基础配置Service业务层处理
 *
 * @author dcsoft
 * @date 2023-12-26
 */
@Slf4j
@Service
public class TLadderConfigServiceImpl implements ITLadderConfigService {

    @Autowired
    private TLadderConfigMapper tLadderConfigMapper;

    @Value("${ladder.url}")
    private String url;

    @Value("${ladder.pass}")
    private String pass;

    /**
     * 设置分层控制接口
     */
    public static final String setDeviceTierOpen = "/setDeviceTierOpen";

    /**
     * 设置设备开关
     */
    public static final String setDeviceOpen = "/setDeviceOpen";


    /**
     * 查询梯控基础配置
     *
     * @param id 梯控基础配置主键
     * @return 梯控基础配置
     */
    @Override
    public TLadderConfig selectTLadderConfigById(String id) {
        TLadderConfig ladderConfig = tLadderConfigMapper.selectTLadderConfigById(id);
        List<StoreyInfoVo> storeyInfoVos = tLadderConfigMapper.queryStoreyInfo(ladderConfig);
        if (!CollectionUtils.isEmpty(storeyInfoVos)) {
            ladderConfig.setList(storeyInfoVos);
        }
        return ladderConfig;
    }

    /**
     * 查询梯控基础配置列表
     *
     * @param tLadderConfig 梯控基础配置
     * @return 梯控基础配置
     */
    @Override
    public List<TLadderConfig> selectTLadderConfigList(TLadderConfig tLadderConfig) {
        List<String> listStr = new ArrayList<>();
        if (StringUtils.isNotEmpty(tLadderConfig.getPointId())) {
            listStr = Arrays.asList(tLadderConfig.getPointId().split(","));
        }
        startPage();
        List<TLadderConfig> list = tLadderConfigMapper.selectTLadderConfigList(tLadderConfig, listStr);
        List<StoreyInfoVo> storeyList = tLadderConfigMapper.queryStoreyInfo(new TLadderConfig());
        Map<String, List<StoreyInfoVo>> collect = storeyList.stream().collect(Collectors.groupingBy(StoreyInfoVo::getLadderId));
        for (TLadderConfig ladderConfig : list) {
            List<StoreyInfoVo> storeyInfoVos = collect.get(ladderConfig.getId());
            if (!CollectionUtils.isEmpty(storeyInfoVos)) {
                ladderConfig.setList(storeyInfoVos);
            }
        }
        return list;
    }

    /**
     * 新增梯控基础配置
     *
     * @param tLadderConfig 梯控基础配置
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTLadderConfig(TLadderConfig tLadderConfig) {
        // 判断是否需要分层控制（调用设备接口/setDeviceTierOpen）
        if (Constants.ONE.equals(tLadderConfig.getLadderSwitch())) {
            SysEquipment sysEquipment = tLadderConfigMapper.queryEquipment(tLadderConfig);
            setDeviceTierOpen(tLadderConfig, sysEquipment);
            // 设置设备开关
            setDeviceOpen(sysEquipment);
        }
        tLadderConfig.setId(UUID.randomUUID().toString().replace("-", ""));
        // 保存楼层数据
        saveStoreyInfo(tLadderConfig);
        return tLadderConfigMapper.insertTLadderConfig(tLadderConfig);
    }

    private void setDeviceOpen(SysEquipment sysEquipment) {
        Map<String, Object> map = new HashMap<>();
        map.put("pass", pass);
        map.put("state", 1);
        String body = HttpUtil.createPost("http://" + sysEquipment.getIp() + ":8090" + setDeviceOpen).body(JSON.toJSONString(map)).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        if (!Constants.CODE.equals(object.get("msg"))) {
            log.error("梯控设置设备开关接口异常:" + object.get("msg").toString());
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "梯控设置设备开关接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage());
        }
    }

    /**
     * 修改梯控基础配置
     *
     * @param tLadderConfig 梯控基础配置
     * @return 结果
     */
    @Override
    @Transactional
    public int updateTLadderConfig(TLadderConfig tLadderConfig) {
        TLadderConfig ladderConfig = tLadderConfigMapper.selectTLadderConfigById(tLadderConfig.getId());
        if (tLadderConfig.getLadderSwitch().equals(ladderConfig.getLadderSwitch())) {
            tLadderConfigMapper.deleteStoreyInfo(tLadderConfig);
            saveStoreyInfo(tLadderConfig);
            return tLadderConfigMapper.updateTLadderConfig(tLadderConfig);
        }

        // 判断是否需要分层控制（调用设备接口/setDeviceTierOpen）
//        setDeviceTierOpen(tLadderConfig);
        tLadderConfigMapper.deleteStoreyInfo(tLadderConfig);
        saveStoreyInfo(tLadderConfig);
        return tLadderConfigMapper.updateTLadderConfig(tLadderConfig);
    }

    /**
     * 设置分层控制接口
     *
     * @param tLadderConfig
     */
    private void setDeviceTierOpen(TLadderConfig tLadderConfig, SysEquipment sysEquipment) {

        Map<String, Object> map = new HashMap<>();
        map.put("pass", pass);
        map.put("enable", tLadderConfig.getLadderType());
        map.put("floor", FloorUtil.floorConvert(tLadderConfig.getStoreyList()));
        String body = HttpUtil.createPost("http://" + sysEquipment.getIp() + ":8090" + setDeviceTierOpen).body(JSON.toJSONString(map)).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        if (!Constants.CODE.equals(object.get("msg"))) {
            log.error("梯控设置分层控制接口异常:" + object.get("msg").toString());
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "梯控设置分层控制接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage());
        }
    }

    /**
     * 保存楼层数据
     */
    private void saveStoreyInfo(TLadderConfig tLadderConfig) {
        // 保存楼层数据
        List<String> storeyList = tLadderConfig.getStoreyList();
        List<TLadderConfig> list = new ArrayList<>();
        for (String s : storeyList) {
            TLadderConfig ladderConfig = new TLadderConfig();
            ladderConfig.setStorey(s);
            ladderConfig.setLadderId(tLadderConfig.getId());
            list.add(ladderConfig);
        }
        tLadderConfigMapper.saveStoreyInfo(list);
    }

    /**
     * 批量删除梯控基础配置
     *
     * @param ids 需要删除的梯控基础配置主键
     * @return 结果
     */
    @Override
    public int deleteTLadderConfigByIds(String[] ids) {
        for (String id : ids) {
            List<TLadderRule> list = tLadderConfigMapper.queryRuleCount(id);
            if (!CollectionUtils.isEmpty(list)) {
                String collect = list.stream().map(TLadderRule::getName).collect(Collectors.joining(","));
                throw new ServiceException("已绑定规则" + collect + "不可删除");
            }
        }
        return tLadderConfigMapper.deleteTLadderConfigByIds(ids);
    }

    /**
     * 删除梯控基础配置信息
     *
     * @param id 梯控基础配置主键
     * @return 结果
     */
    @Override
    public int deleteTLadderConfigById(String id) {
        return tLadderConfigMapper.deleteTLadderConfigById(id);
    }

    /**
     * 查询设备树
     */
    @Override
    public List<DeviceTreeVo> queryDeviceTree() {
        List<DeviceTreeVo> deviceTreeVos = tLadderConfigMapper.queryDeviceTree();
        return TreeUtil.buildTree(deviceTreeVos, Constants.ZERO);
    }

    /**
     * 设备初始化
     */
    @Override
    public void deviceInitialize(TLadderConfig ladderConfig) {
        if (StringUtils.isEmpty(ladderConfig.getSerialNumber())) {
            throw new ServiceException(CommonExceptionEnum.DEVICE_INITIALIZE_ERROR.getCode(), "设备初始化接口" + CommonExceptionEnum.DEVICE_INITIALIZE_ERROR.getMessage());
        }
        SysEquipment sysEquipment = tLadderConfigMapper.queryEquipment(ladderConfig);
        Map<String, String> map = new HashMap<>();
        map.put("pass", sysEquipment.getPassword());
        String body = HttpUtil.createPost("http://" + sysEquipment.getIp() + ":8090/resetDevice").body(JSON.toJSONString(map)).execute().body();
        JSONObject object = JSONObject.parseObject(body);
        if (Constants.ONE.equals(object.get("result"))) {
            throw new ServiceException(CommonExceptionEnum.REQUEST_ERROR.getCode(), "设备初始化接口" + CommonExceptionEnum.REQUEST_ERROR.getMessage());
        }
    }


}
