package com.zt.plat.module.qms.resource.device.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.module.qms.core.constant.DataTypeConstant;
import com.zt.plat.module.qms.enums.ErrorCodeConstants;
import com.zt.plat.module.qms.resource.device.controller.vo.*;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceProductPageReqVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceProductRespVO;
import com.zt.plat.module.qms.resource.device.controller.vo.DeviceProductSaveReqVO;
import com.zt.plat.module.qms.resource.device.dal.dataobject.DeviceProductDO;
import com.zt.plat.module.qms.resource.device.dal.mapper.DeviceProductMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.util.List;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.qms.enums.ErrorCodeConstants.*;

/**
 * 设备-设备大类 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class DeviceProductServiceImpl implements DeviceProductService {

    private int id_path_update_level_limit = 7;
    
    @Resource
    private DeviceProductMapper deviceProductMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<DeviceProductRespVO> saveCategory(DeviceProductSaveReqVO entity) {
        if(entity.getParentId() == null || entity.getParentId() == 0L)
            entity.setParentId(0L);
        Long parentId = entity.getParentId();
        List<DeviceProductDO> checkList = listByParId(parentId, DataTypeConstant.DATA_TYPE_CATEGORY);
        boolean duplicate = false;
        DeviceProductDO duplicateEntity = checkList.stream().filter(e->e.getName().equals(entity.getName())).findFirst().orElse(null);
        if(duplicateEntity != null && !duplicateEntity.getId().equals(entity.getId()))
            duplicate = true;
        if(duplicate)
            throw exception(ErrorCodeConstants.DICTIONARY_BUSINESS_CLASSIFY_DUPLICATE);
        entity.setNodeType(DataTypeConstant.DATA_TYPE_CATEGORY);
        Long id = entity.getId();
        DeviceProductDO dic = BeanUtils.toBean(entity, DeviceProductDO.class);
        if(ObjectUtils.isEmpty(id)){
            deviceProductMapper.insert(dic);
            id = dic.getId();
        }
        DeviceProductDO backData = this.getDeviceProduct(id);
        Long parentId_ = backData.getParentId();
        //检查parId，避免父节点设置为本节点的后代节点
        if(parentId_.equals(id))
            throw new ServiceException(ErrorCodeConstants.DATA_COLLECTION_CLASSIFY_PARENT_ERROR);
        String idPath = getIdPath(dic);
        int curIdIndex = idPath.indexOf("/" + id.toString() + "/");
        int parIdIndex = idPath.indexOf("/" + parentId.toString() + "/");
        if(curIdIndex <= parIdIndex)
            throw new ServiceException(ErrorCodeConstants.DATA_COLLECTION_CLASSIFY_PARENT_ERROR);
        dic.setIdPath(idPath);

        //更新后代节点路径
        updateAllIdPath(id, 1);
        deviceProductMapper.updateById(dic);
        return CommonResult.success(BeanUtils.toBean(dic, DeviceProductRespVO.class));
    }

    @Override
    public CommonResult<DeviceProductRespVO> saveData(DeviceProductSaveReqVO createReqVO) {
        Long id = createReqVO.getId();
        DeviceProductDO entity = BeanUtils.toBean(createReqVO, DeviceProductDO.class);
        entity.setNodeType(DataTypeConstant.DATA_TYPE_DATA);
        Long parentId = createReqVO.getParentId();
        if(id == null){
            deviceProductMapper.insert(entity);
        }else{
            deviceProductMapper.updateById(entity);
        }
        if(parentId != null && parentId != 0L){
            DeviceProductDO parEntity = this.getDeviceProduct(parentId);
            String parPath = parEntity.getIdPath();
            entity.setIdPath(parPath + "/" + entity.getId() + "/");
            deviceProductMapper.updateById(entity);
        }
        DeviceProductRespVO vo = BeanUtils.toBean(entity, DeviceProductRespVO.class);
        return CommonResult.success( vo);
    }

    @Override
    public List<Long> getIdListByIdPath(Long id) {
        List<DeviceProductDO> productDOList = this.listByIdPath(id, DataTypeConstant.DATA_TYPE_DATA);
        List<Long> productIds = productDOList.stream().map(DeviceProductDO::getId).toList();
        return productIds;
    }

    @Override
    public List<DeviceProductDO> listByIdPath(Long id, String nodeType) {
        LambdaQueryWrapper<DeviceProductDO> query = new LambdaQueryWrapper<>();
        query.like(DeviceProductDO::getIdPath, id);
        if(!ObjectUtils.isEmpty(nodeType))
            query.eq(DeviceProductDO::getNodeType, nodeType);
        query.orderByAsc(DeviceProductDO::getSortNo);
        return deviceProductMapper.selectList(query);
    }

    @Override
    public List<DeviceProductDO> listByParId(Long parId, String nodeType) {
        LambdaQueryWrapper<DeviceProductDO> query = new LambdaQueryWrapper<>();
        query.eq(DeviceProductDO::getParentId, parId);
        if(!ObjectUtils.isEmpty(nodeType))
            query.eq(DeviceProductDO::getNodeType, nodeType);
        query.orderByAsc(DeviceProductDO::getSortNo);
        return deviceProductMapper.selectList(query);
    }

    @Override
    public CommonResult<String> updateAllIdPath(Long parentId, Integer level) {
        if(level > id_path_update_level_limit)
            return CommonResult.success("更新完成（超出层数限制："+id_path_update_level_limit+"）");
        List<DeviceProductDO> list = listByParId(parentId, "");
        DeviceProductDO parEntity = this.getDeviceProduct(parentId);
        if(list.isEmpty())
            return CommonResult.success("");
        String parIdPath = "/0/";
        if(parEntity != null)
            parIdPath = parEntity.getIdPath();
        for(DeviceProductDO entity : list){
            entity.setIdPath(parIdPath + "/" + entity.getId() + "/");
            deviceProductMapper.updateById( entity);
            updateAllIdPath(entity.getId(),level+1);
        }
        return CommonResult.success("");
    }

    @Override
    public List<DeviceProductDO> getTreeData(String nodeType) {
        LambdaQueryWrapper<DeviceProductDO> query = new LambdaQueryWrapper<>();
        if(!ObjectUtils.isEmpty(nodeType))
            query.eq(DeviceProductDO::getNodeType, nodeType);
        query.orderByAsc(DeviceProductDO::getSortNo);
        return deviceProductMapper.selectList(query);
    }

    @Override
    public DeviceProductRespVO createDeviceProduct(DeviceProductSaveReqVO createReqVO) {
        // 插入
        DeviceProductDO deviceProduct = BeanUtils.toBean(createReqVO, DeviceProductDO.class);
        deviceProductMapper.insert(deviceProduct);
        // 返回
        return BeanUtils.toBean(deviceProduct, DeviceProductRespVO.class);
    }

    @Override
    public void updateDeviceProduct(DeviceProductSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceProductExists(updateReqVO.getId());
        // 更新
        DeviceProductDO updateObj = BeanUtils.toBean(updateReqVO, DeviceProductDO.class);
        deviceProductMapper.updateById(updateObj);
    }

    @Override
    public void deleteDeviceProduct(Long id) {
        // 校验存在
        validateDeviceProductExists(id);
        // 删除
        deviceProductMapper.deleteById(id);
    }

    @Override
        public void deleteDeviceProductListByIds(List<Long> ids) {
        // 校验存在
        validateDeviceProductExists(ids);
        // 删除
        deviceProductMapper.deleteByIds(ids);
        }

    private void validateDeviceProductExists(List<Long> ids) {
        List<DeviceProductDO> list = deviceProductMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DEVICE_PRODUCT_NOT_EXISTS);
        }
    }

    private void validateDeviceProductExists(Long id) {
        if (deviceProductMapper.selectById(id) == null) {
            throw exception(DEVICE_PRODUCT_NOT_EXISTS);
        }
    }

    @Override
    public DeviceProductDO getDeviceProduct(Long id) {
        return deviceProductMapper.selectById(id);
    }

    @Override
    public PageResult<DeviceProductDO> getDeviceProductPage(DeviceProductPageReqVO pageReqVO) {
        return deviceProductMapper.selectPage(pageReqVO);
    }

    @Override
    public List<DeviceProductDO> getDeviceProductByCategoryName(String deviceCategoryName) {
        List<DeviceProductDO> category = deviceProductMapper.selectList(Wrappers.lambdaQuery(DeviceProductDO.class)
                .eq(DeviceProductDO::getNodeType, DataTypeConstant.DATA_TYPE_CATEGORY)
                .eq(DeviceProductDO::getName, deviceCategoryName)
                .last("limit 1"));
        if (CollUtil.isEmpty(category)) return List.of();

        return deviceProductMapper.selectList(Wrappers.lambdaQuery(DeviceProductDO.class)
                .like(DeviceProductDO::getIdPath, "/" + category.get(0).getId() + "/")
                .eq(DeviceProductDO::getNodeType, DataTypeConstant.DATA_TYPE_DATA));
    }

    private String getIdPath(DeviceProductDO entity){
        String parIdPath = "";
        if(ObjectUtils.isEmpty(entity.getParentId()) || 0L == entity.getParentId())
            parIdPath = "/0/";
        DeviceProductDO parEntity = this.getDeviceProduct(entity.getParentId());
        if(parEntity != null){
            parIdPath = parEntity.getIdPath();
        }
        return parIdPath + entity.getId() + "/";
    }
    
}