package cn.iocoder.yudao.module.pms.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotInfoClassifyListReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotInfoClassifyRespVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotInfoClassifySaveReqVO;
import cn.iocoder.yudao.module.pms.controller.admin.vo.IotInfoRespVO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotDeviceDO;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotInfoClassifyDO;
import cn.iocoder.yudao.module.pms.dal.mysql.IotInfoClassifyMapper;
import cn.iocoder.yudao.module.pms.dal.dataobject.IotTreeDO;
import cn.iocoder.yudao.module.pms.dal.mysql.IotInfoMapper;
import cn.iocoder.yudao.module.pms.dal.mysql.IotTreeMapper;
import cn.iocoder.yudao.module.system.dal.redis.RedisKeyConstants;
import cn.iocoder.yudao.module.system.enums.ErrorCodeConstants;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.module.pms.enums.ErrorCodeConstant.IOT_INFO_EXISTS;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.*;

/**
 * 产品分类 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class IotInfoClassifyServiceImpl implements IotInfoClassifyService {

    @Resource
    private IotInfoClassifyMapper iotInfoClassifyMapper;
    @Resource
    private IotTreeMapper iotTreeMapper;
    @Autowired
    private IotInfoMapper iotInfoMapper;
    @Autowired
    private DeviceServiceImpl deviceServiceImpl;
    @Autowired
    private IotDeviceService iotDeviceService;

    @Override
    @CacheEvict(cacheNames = RedisKeyConstants.IOT_INFO_CHILDREN_ID_LIST,
            allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public Long createIotInfoClassify(IotInfoClassifySaveReqVO createReqVO) {
        if (createReqVO.getParentId() == null) {
            createReqVO.setParentId(IotInfoClassifyDO.PARENT_ID_ROOT);
        }
        // 校验父产品分类的有效性
        validateParentInfoClassify(null, createReqVO.getParentId());
        // 校验产品分类名的唯一性
        validateInfoClassifyNameUnique(null, createReqVO.getParentId(), createReqVO.getName());

        // 插入产品分类
        IotInfoClassifyDO infoClassifyDO = BeanUtils.toBean(createReqVO, IotInfoClassifyDO.class);
        iotInfoClassifyMapper.insert(infoClassifyDO);
        //插入pms树
        IotTreeDO iotTreeDO = new IotTreeDO();
        iotTreeDO.setType("file");
        iotTreeDO.setOriginId(infoClassifyDO.getId());
        iotTreeDO.setName(infoClassifyDO.getName());
        IotDeviceDO iotDevice = iotDeviceService.getIotDevice(infoClassifyDO.getDeviceId());
        iotTreeDO.setDeptId(Objects.isNull(iotDevice) ? null : iotDevice.getDeptId());
        List<IotTreeDO> iotTreeDOS = iotTreeMapper.selectListByOriginId(infoClassifyDO.getDeviceId(),"device");
        List<IotTreeDO> iotTreeDOSs = iotTreeMapper.selectListByOriginId(infoClassifyDO.getParentId(),"file");
        if (CollUtil.isEmpty(iotTreeDOSs)) {
            iotTreeDO.setParentId(Objects.nonNull(iotTreeDOS.get(0)) ? iotTreeDOS.get(0).getId() : 0);
        } else {
            iotTreeDO.setParentId(iotTreeDOSs.get(0).getId());
        }
        iotTreeMapper.insert(iotTreeDO);
        return infoClassifyDO.getId();
    }

    @Override
    @CacheEvict(cacheNames = RedisKeyConstants.IOT_INFO_CHILDREN_ID_LIST,
            allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void updateIotInfoClassify(IotInfoClassifySaveReqVO updateReqVO, String type) {
        if (updateReqVO.getParentId() == null) {
            updateReqVO.setParentId(IotInfoClassifyDO.PARENT_ID_ROOT);
        }
        // 校验自己存在
        validateIotInfoClassifyExists(updateReqVO.getId());
        // 校验父产品分类的有效性
        validateParentInfoClassify(updateReqVO.getId(), updateReqVO.getParentId());
        // 校验产品分类名的唯一性
        validateInfoClassifyNameUnique(updateReqVO.getId(), updateReqVO.getParentId(), updateReqVO.getName());

        // 更新产品分类
        IotInfoClassifyDO updateObj = BeanUtils.toBean(updateReqVO, IotInfoClassifyDO.class);
        iotInfoClassifyMapper.updateById(updateObj);
        //更新pms树
        List<IotTreeDO> iotTreeDOS = iotTreeMapper.selectListByOriginId(updateObj.getId(), "file");
        if (CollUtil.isEmpty(iotTreeDOS)) {
            throw new ServiceException(ErrorCodeConstants.DEPT_NOT_FOUND.getCode(),"无该部门");
        }
        IotTreeDO iotTreeDO = iotTreeDOS.get(0);
        iotTreeDO.setName(updateObj.getName());
        List<IotTreeDO> parentIotTreeDOS = iotTreeMapper.selectListByOriginId(updateObj.getParentId(), "file");
        if ("remove".equals(type)) {
            if (CollUtil.isEmpty(parentIotTreeDOS)) {
                throw new ServiceException(ErrorCodeConstants.DEPT_NOT_FOUND.getCode(),"无该节点");
            } else {
                iotTreeDO.setParentId(parentIotTreeDOS.get(0).getId());
            }
        }
        iotTreeDO.setDeptId(updateObj.getDeptId());
        iotTreeMapper.updateById(iotTreeDO);
    }

    @Override
    @CacheEvict(cacheNames = RedisKeyConstants.IOT_INFO_CHILDREN_ID_LIST,
            allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void deleteIotInfoClassify(Long id) {
        // 校验是否存在
        validateIotInfoClassifyExists(id);
        // 校验是否有子产品分类
        if (iotInfoClassifyMapper.selectCountByParentId(id) > 0) {
            throw exception(IOT_INFO_EXISTS);
        }
        // 删除产品分类
        iotInfoClassifyMapper.deleteById(id);
        //删除pms树
        iotTreeMapper.deleteByMap(ImmutableMap.of("origin_id", id));
        //删除文件
        iotInfoMapper.deleteByMap(ImmutableMap.of("class_id", id));
    }

    @Override
    public List<IotInfoClassifyRespVO> getChildContentFile(Long classId) {
        List<IotInfoClassifyDO> classifyList = getChildIotInfoClassifyList(ImmutableList.of(classId));


        BeanUtils.toBean(classifyList, IotInfoRespVO.class);
        return Collections.emptyList();
    }

    @VisibleForTesting
    void validateIotInfoClassifyExists(Long id) {
        if (id == null) {
            return;
        }
        IotInfoClassifyDO dept = iotInfoClassifyMapper.selectById(id);
        if (dept == null) {
            throw exception(DEPT_NOT_FOUND);
        }
    }

    @VisibleForTesting
    void validateParentInfoClassify(Long id, Long parentId) {
        if (parentId == null || IotInfoClassifyDO.PARENT_ID_ROOT.equals(parentId)) {
            return;
        }
        // 1. 不能设置自己为父产品分类
        if (Objects.equals(id, parentId)) {
            throw exception(DEPT_PARENT_ERROR);
        }
        // 2. 父产品分类不存在
        IotInfoClassifyDO parentDept = iotInfoClassifyMapper.selectById(parentId);
        if (parentDept == null) {
            throw exception(DEPT_PARENT_NOT_EXITS);
        }
        // 3. 递归校验父产品分类，如果父产品分类是自己的子产品分类，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = parentDept.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(DEPT_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父产品分类
            if (parentId == null || IotInfoClassifyDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            parentDept = iotInfoClassifyMapper.selectById(parentId);
            if (parentDept == null) {
                break;
            }
        }
    }

    @VisibleForTesting
    void validateInfoClassifyNameUnique(Long id, Long parentId, String name) {
        IotInfoClassifyDO dept = iotInfoClassifyMapper.selectByParentIdAndName(parentId, name);
        if (dept == null) {
            return;
        }
        // 如果 id 为空，说明不用比较是否为相同 id 的产品分类
        if (id == null) {
            throw exception(DEPT_NAME_DUPLICATE);
        }
        if (ObjectUtil.notEqual(dept.getId(), id)) {
            throw exception(DEPT_NAME_DUPLICATE);
        }
    }

    @Override
    public IotInfoClassifyDO getIotInfoClassify(Long id) {
        return iotInfoClassifyMapper.selectById(id);
    }

    @Override
    public List<IotInfoClassifyDO> getIotInfoClassifyList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        return iotInfoClassifyMapper.selectBatchIds(ids);
    }

    @Override
    public List<IotInfoClassifyDO> getIotInfoClassifyList(IotInfoClassifyListReqVO reqVO) {
        List<IotInfoClassifyDO> list = iotInfoClassifyMapper.selectList(reqVO);
        list.sort(Comparator.comparing(IotInfoClassifyDO::getSort));
        return list;
    }

    @Override
    public List<IotInfoClassifyDO> getChildIotInfoClassifyList(Collection<Long> ids) {
        List<IotInfoClassifyDO> children = new LinkedList<>();
        // 遍历每一层
        Collection<Long> parentIds = ids;
        for (int i = 0; i < Short.MAX_VALUE; i++) { // 使用 Short.MAX_VALUE 避免 bug 场景下，存在死循环
            // 查询当前层，所有的子产品分类
            List<IotInfoClassifyDO> depts = iotInfoClassifyMapper.selectListByParentId(parentIds);
            // 1. 如果没有子产品分类，则结束遍历
            if (CollUtil.isEmpty(depts)) {
                break;
            }
            // 2. 如果有子产品分类，继续遍历
            children.addAll(depts);
            parentIds = convertSet(depts, IotInfoClassifyDO::getId);
        }
        return children;
    }
    @Override
    @DataPermission(enable = false) // 禁用数据权限，避免建立不正确的缓存
    @Cacheable(cacheNames = RedisKeyConstants.IOT_INFO_CHILDREN_ID_LIST, key = "#id")
    public Set<Long> getChildIotInfoClassifyIdListFromCache(Long id) {
        List<IotInfoClassifyDO> children = getChildInfoList(id);
        return convertSet(children, IotInfoClassifyDO::getId);
    }

    @Override
    public List<IotInfoClassifyDO> getChildInfoList(Collection<Long> ids) {
        List<IotInfoClassifyDO> children = new LinkedList<>();
        // 遍历每一层
        Collection<Long> parentIds = ids;
        for (int i = 0; i < Short.MAX_VALUE; i++) { // 使用 Short.MAX_VALUE 避免 bug 场景下，存在死循环
            // 查询当前层，所有的子部门
            List<IotInfoClassifyDO> depts = iotInfoClassifyMapper.selectListByParentId(parentIds);
            // 1. 如果没有子部门，则结束遍历
            if (CollUtil.isEmpty(depts)) {
                break;
            }
            // 2. 如果有子部门，继续遍历
            children.addAll(depts);
            parentIds = convertSet(depts, IotInfoClassifyDO::getId);
        }
        return children;
    }
}
