package com.fjhx.iot.service.tda.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.iot.constants.RedisConstant;
import com.fjhx.iot.entity.tda.dto.TdaDeviceDto;
import com.fjhx.iot.entity.tda.dto.TdaDeviceSelectDto;
import com.fjhx.iot.entity.tda.po.TdaDevice;
import com.fjhx.iot.entity.tda.vo.TdaDeviceVo;
import com.fjhx.iot.mapper.tda.TdaDeviceMapper;
import com.fjhx.iot.service.tda.TdaDeviceService;
import com.fjhx.item.entity.product.po.ProductInfo;
import com.fjhx.item.service.product.ProductInfoService;
import com.fjhx.tenant.utils.DeptUstil;
import com.ruoyi.common.core.domain.BasePo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.wrapper.IWrapper;
import com.ruoyi.common.utils.wrapper.SqlField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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


/**
 * <p>
 * 设备管理 服务实现类
 * </p>
 *
 * @author zlj
 * @since 2023-03-21
 */
@Service
public class TdaDeviceServiceImpl extends ServiceImpl<TdaDeviceMapper, TdaDevice> implements TdaDeviceService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ProductInfoService productInfoService;

    @Override
    public Page<TdaDeviceVo> getPage(TdaDeviceSelectDto dto) {
        IWrapper<TdaDevice> wrapper = getWrapper();
        wrapper.orderByDesc("td", TdaDevice::getId);
        wrapper.keyword(dto, new SqlField("td.device_name"));

        //权限过滤：设备管理-子公司看自己的,总公司看全部
        wrapper.in("td.company_id", SecurityUtils.getCompanyIds());
        wrapper.eq("td.company_id", dto.getCompanyId());


        Page<TdaDeviceVo> page = this.baseMapper.getPage(dto.getPage(), wrapper);

        List<TdaDeviceVo> records = page.getRecords();

        if (records.size() == 0) {
            return page;
        }

        //获取生产公司信息
        List<Long> companyIds = records.stream().map(TdaDevice::getCompanyId).collect(Collectors.toList());
        Map<Long, String> companyNameMap = DeptUstil.getDeptNameMap(companyIds);

        for (TdaDeviceVo record : records) {
            //赋值生产公司名称
            record.setCompanyName(companyNameMap.get(record.getCompanyId()));
        }

//        for (TdaDeviceVo record : records) {
//
//            HashMap<String, Object> other = new HashMap<>();
//            record.setOther(other);
//
//            // 设备id
//            String deviceId = record.getDeviceId();
//
//            // 产品设备类型
//            String deviceType = record.getDeviceType();
//
//            if (StrUtil.isBlank(deviceId)) {
//                continue;
//            }
//
//            Object obj = redisCache.getCacheObject(RedisConstant.DEVICE_PREFIX + deviceId);
//            if (obj == null) {
//                continue;
//            }
//
//            switch (deviceType) {
//                case "ebc":
//                    EbcDto ebcDto = (EbcDto) obj;
//                    EbcDto.Status status = ebcDto.getStatus();
//                    String sysSta = status.getSys_sta();
//                    record.setStatus(sysSta);
//                    record.setEventTime(ebcDto.getEventTime());
//
//                    other.put("ebc", "1");
//                    other.put("jiaka", status.getJiaka());
//                    other.put("hengyi", status.getHengyi());
//                    break;
//            }
//
//        }


        return page;
    }

    @Override
    public TdaDeviceVo detail(TdaDeviceSelectDto dto) {
        if (ObjectUtil.isEmpty(dto.getId()) && ObjectUtil.isEmpty(dto.getUserUuid())) {
            throw new ServiceException("设备id/用户唯一标识，其中之一不能为空！");
        }

        //赋值任务信息
        IWrapper<TdaDevice> wrapper = getWrapper();
        wrapper.eq("td", TdaDevice::getId, dto.getId());
        wrapper.eq("td", TdaDevice::getUserUuid, dto.getUserUuid());
        TdaDeviceVo result = baseMapper.detail(wrapper);

        if (ObjectUtil.isEmpty(result)) {
            return result;
        }

        //赋值产品信息
        ProductInfo productInfo = productInfoService.getById(result.getProductId());
        if (ObjectUtil.isNotEmpty(productInfo)) {
            result.setProductName(productInfo.getName());
            result.setProductCode(productInfo.getCustomCode());
            result.setProductLength(productInfo.getLength());
            result.setProductWidth(productInfo.getWidth());
            result.setProductHeight(productInfo.getHeight());
            result.setProductColor(productInfo.getColor());
        }

        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TdaDeviceDto tdaDeviceDto) {
//        String nodeId = tdaDeviceDto.getNodeId();
//        String deviceName = tdaDeviceDto.getDeviceName();
//        Long tdaProductId = tdaDeviceDto.getTdaProductId();
//
//        // 查询资源所在空间和产品id
//        TdaProduct tdaProduct = tdaProductService.getById(tdaProductId);
//        String productId = tdaProduct.getProductId();
//
//        TdaApplication tdaApplication = tdaApplicationService.getById(tdaProduct.getTdaApplicationId());
//
//        // 华为ioDta添加设备
//        IoTDAUtil.DeviceKey deviceKey = IoTDAUtil.addDevice(tdaApplication.getTdaConfigId(),
//                nodeId, deviceName, tdaProduct.getAppId(), productId, tdaDeviceDto.getSecret());
//
//        tdaDeviceDto.setProductId(productId);
//        tdaDeviceDto.setDeviceId(tdaDeviceDto.getNodeId());

        // tdaDeviceDto.setSecret(deviceKey.getSecret());

        //赋值归属公司Id
        tdaDeviceDto.setCompanyId(SecurityUtils.getCompanyId());

        this.save(tdaDeviceDto);
    }

    @Override
    @DSTransactional
    public void edit(TdaDeviceDto tdaDeviceDto) {
        String userUuid = tdaDeviceDto.getUserUuid();

        //机台设置 更新用户设备唯一id
        if (ObjectUtil.isNotEmpty(userUuid)) {
            this.update(q -> q
                    .eq(TdaDevice::getUserUuid, userUuid)
                    .set(TdaDevice::getUserUuid, null)
                    .set(BasePo::getUpdateTime, new Date())
                    .set(BasePo::getUpdateUser, SecurityUtils.getUserId())
            );
        }

        this.updateById(tdaDeviceDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(Long id) {

//        TdaDevice tdaDevice = getById(id);
//        TdaProduct tdaProduct = tdaProductService.getById(tdaDevice.getTdaProductId());
//        TdaApplication tdaApplication = tdaApplicationService.getById(tdaProduct.getTdaApplicationId());
//
//        IoTDAUtil.deleteDevice(tdaApplication.getTdaConfigId(), tdaDevice.getDeviceId());

        this.removeById(id);
    }

    @Override
    public List<JSONObject> getComputerList(TdaDeviceSelectDto dto) {
        Set<String> computerKeys = redisCache.scan(RedisConstant.DEVICE_COMPUTER_PREFIX + "*");

        List<JSONObject> computerList = computerKeys.stream().map(item -> (JSONObject) redisCache.getCacheObject(item))
                .filter(Objects::nonNull).collect(Collectors.toList());

        return computerList;
    }

}
