package com.ruoyi.business.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.domain.HwDevice;
import com.ruoyi.business.domain.HwSceneMode;
import com.ruoyi.business.domain.VO.HwSceneVo;
import com.ruoyi.business.mapper.HwDeviceMapper;
import com.ruoyi.common.core.constant.Constants;
import com.ruoyi.common.core.constant.HwDictConstants;
import com.ruoyi.common.core.constant.TdEngineConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.datascope.annotation.DataScope;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.tdengine.api.RemoteTdEngineService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.business.mapper.HwSceneMapper;
import com.ruoyi.business.domain.HwScene;
import com.ruoyi.business.service.IHwSceneService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 场景信息Service业务层处理
 *
 * @author xins
 * @date 2023-08-23
 */
@Service
public class HwSceneServiceImpl implements IHwSceneService {
    @Autowired
    private HwSceneMapper hwSceneMapper;
    @Autowired
    private HwDeviceMapper hwDeviceMapper;
    @Resource
    private RemoteTdEngineService remoteTdEngineService;
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 查询场景信息
     *
     * @param sceneId 场景信息主键
     * @return 场景信息
     */
    @Override
    public HwScene selectHwSceneBySceneId(Long sceneId) {
        return hwSceneMapper.selectHwSceneBySceneId(sceneId);
    }

    @Override
    public List<HwScene> selectHwSceneBySceneModeId(Long sceneModeId) {
        List<HwScene> hwScenes = hwSceneMapper.selectHwSceneBySceneModeId(sceneModeId);

        return hwScenes;
    }

    /**
     * 查询场景信息列表
     *
     * @param hwScene 场景信息
     * @return 场景信息
     */
    @Override
    @DataScope(tenantAlias = "hs")
    public List<HwScene> selectHwSceneList(HwScene hwScene) {
        List<HwScene> scenes = hwSceneMapper.selectHwSceneList(hwScene);
        boolean defaultFlag = false;
        for (HwScene scene : scenes) {
            if (defaultFlag) {
                scene.setDefaultFlag(HwDictConstants.SCENE_DEFAULT_FLAG_NO);
            } else {
                if (scene.getDefaultFlag().equalsIgnoreCase(HwDictConstants.SCENE_DEFAULT_FLAG_YES)) {
                    defaultFlag = true;
                }
            }
            scene.setRouter(HwDictConstants.SCENE_MODE_ROUTER_MAP.get(scene.getSceneModeId()));
        }
        return scenes;
    }

    @Override
    public List<HwSceneVo> selectHwSceneJoinList(HwSceneVo hwScene) {
        return hwSceneMapper.selectHwSceneVoList(hwScene);
    }

    /**
     * 新增场景信息
     *
     * @param hwScene 场景信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertHwScene(HwScene hwScene) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getSysUser();
        hwScene.setCreateBy(sysUser.getUserName());
        hwScene.setTenantId(sysUser.getTenantId());

        if (hwScene.getPreserveTime() == null) {
            hwScene.setPreserveTime(new BigDecimal(90));
        }
        if (hwScene.getTestPreserveTime() == null) {
            hwScene.setTestPreserveTime(new BigDecimal(30));
        }
//        String randomKey = RandomStringUtils.random(12, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789");
//        String randomSecret = RandomStringUtils.random(16, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789");
//        hwScene.setModeKey(randomKey);
//        hwScene.setModeSecret(randomSecret);
        hwScene.setCreateTime(DateUtils.getNowDate());

        int rows = hwSceneMapper.insertHwScene(hwScene);
        this.createTdDatabase(hwScene);
        return rows;
    }

    private void createTdDatabase(HwScene hwScene) {
        String databaseName = TdEngineConstants.getDatabaseName(hwScene.getSceneId());
        R<?> tdReturnMsg = this.remoteTdEngineService.createDataBase(databaseName);
        if (tdReturnMsg.getCode() != Constants.SUCCESS) {//抛出异常，回滚事务
            throw new RuntimeException(tdReturnMsg.getMsg());
        }
    }

    /**
     * 修改场景信息
     *
     * @param hwScene 场景信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateHwScene(HwScene hwScene) {
        if (hwScene.getDefaultFlag().equals(HwDictConstants.SCENE_DEFAULT_FLAG_YES)) {
            HwScene queryScene = new HwScene();
            queryScene.setTenantId(hwScene.getTenantId());
            List<HwScene> dbScenes = hwSceneMapper.selectHwSceneList(queryScene);
            if (dbScenes != null && dbScenes.isEmpty()) {
                dbScenes.forEach(dbScene -> {
                    dbScene.setDefaultFlag(HwDictConstants.SCENE_DEFAULT_FLAG_NO);
                    hwSceneMapper.updateHwScene(dbScene);
                });
            }
        }

        hwScene.setUpdateTime(DateUtils.getNowDate());
        int rows =  hwSceneMapper.updateHwScene(hwScene);
        this.updateRedisAuth(hwScene);
        return rows;
    }

    /**
     * 更新redis的auth认证信息
     */
    private void updateRedisAuth(HwScene hwScene) {
        try {
            HwScene dbScene = hwSceneMapper.selectHwSceneBySceneId(hwScene.getSceneId());
            if (dbScene.getModeAccount().equals(hwScene.getModeAccount()) ||
                    dbScene.getModeKey().equals(hwScene.getModeKey())) {
                String modeAccount = hwScene.getModeAccount();
                String modeKey = hwScene.getModeKey();
                HwDevice queryDevice = new HwDevice();
                queryDevice.setSceneId(hwScene.getSceneId());
                List<HwDevice> devices = hwDeviceMapper.selectHwDeviceList(queryDevice);
                if (devices != null && !devices.isEmpty()) {
                    String deviceInfoStr = redisTemplate.opsForValue().get(HwDictConstants.REDIS_KEY_DEVICE_INFO);
                    JSONArray deviceInfoJsonArr = new JSONArray();
                    if (StringUtils.isNotEmpty(deviceInfoStr)) {
                        deviceInfoJsonArr = JSON.parseArray(deviceInfoStr);
                    }
                    for (HwDevice device : devices) {
                        boolean redisUpdated = false;//是否更新已有的值
                        for (Object deviceInfoObj : deviceInfoJsonArr) {
                            JSONObject deviceInfoJson = (JSONObject) deviceInfoObj;
                            if (deviceInfoJson.getString("deviceCode").equals(device.getDeviceCode())) {
                                deviceInfoJson.put("userName", modeAccount);
                                deviceInfoJson.put("password", modeKey);
                                redisUpdated = true;
                            }
                        }

                        if (!redisUpdated) {
                            JSONObject deviceInfoJson = new JSONObject();
                            deviceInfoJson.put("deviceCode", device.getDeviceCode());
                            deviceInfoJson.put("userName", modeAccount);
                            deviceInfoJson.put("password", modeKey);
                            deviceInfoJsonArr.add(deviceInfoJson);
                        }

                    }
                    redisTemplate.opsForValue().set(HwDictConstants.REDIS_KEY_DEVICE_INFO, deviceInfoJsonArr.toString());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }


    /**
     * 批量删除场景信息
     *
     * @param sceneIds 需要删除的场景信息主键
     * @return 结果
     */
    @Override
    public int deleteHwSceneBySceneIds(Long[] sceneIds) {
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < sceneIds.length; i++) {
            list.add(sceneIds[i]);
        }
        return hwSceneMapper.deleteHwSceneBySceneIds(sceneIds);
    }

    /**
     * 删除场景信息信息
     *
     * @param sceneId 场景信息主键
     * @return 结果
     */
    @Override
    public int deleteHwSceneBySceneId(Long sceneId) {
        return hwSceneMapper.deleteHwSceneBySceneId(sceneId);
    }

    /**
     * 查询场景信息列表供其他页面选择使用
     *
     * @param hwScene 场景信息
     * @return 场景信息
     */
    @Override
    public List<HwScene> selectHwSceneList4Select(HwScene hwScene) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getSysUser();
        hwScene.setTenantId(user.getTenantId());

        List<HwScene> scenes =  hwSceneMapper.selectHwSceneList(hwScene);
        scenes.forEach(s ->{
            if(!s.getTenantId().equals( user.getTenantId())){
                s.setSelectedDisable("1");
            }
        });

        return scenes;
    }

}
