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

import cn.hutool.core.collection.CollUtil;
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.material.controller.vo.*;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialProductPageReqVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialProductRespVO;
import com.zt.plat.module.qms.resource.material.controller.vo.MaterialProductSaveReqVO;
import com.zt.plat.module.qms.resource.material.dal.dataobject.MaterialProductDO;
import com.zt.plat.module.qms.resource.material.dal.mapper.MaterialProductMapper;
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 MaterialProductServiceImpl implements MaterialProductService {
    private int id_path_update_level_limit = 7;

    @Resource
    private MaterialProductMapper materialProductMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<MaterialProductRespVO> saveCategory(MaterialProductSaveReqVO entity) {
        if(entity.getParentId() == null || entity.getParentId() == 0L)
            entity.setParentId(0L);
        Long parentId = entity.getParentId();
        List<MaterialProductDO> checkList = listByParId(parentId, DataTypeConstant.DATA_TYPE_CATEGORY);
        boolean duplicate = false;
        MaterialProductDO 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();
        MaterialProductDO dic = BeanUtils.toBean(entity, MaterialProductDO.class);
        if(ObjectUtils.isEmpty(id)){
            materialProductMapper.insert(dic);
            id = dic.getId();
        }
        MaterialProductDO backData = this.getMaterialProduct(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);
        materialProductMapper.updateById(dic);
        return CommonResult.success(BeanUtils.toBean(dic, MaterialProductRespVO.class));
    }

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

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

    @Override
    public List<MaterialProductDO> listByIdPath(Long id, String nodeType) {
        LambdaQueryWrapper<MaterialProductDO> query = new LambdaQueryWrapper<>();
        query.like(MaterialProductDO::getIdPath, id);
        if(!ObjectUtils.isEmpty(nodeType))
            query.eq(MaterialProductDO::getNodeType, nodeType);
        query.orderByAsc(MaterialProductDO::getSortNo);
        return materialProductMapper.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<MaterialProductDO> list = listByParId(parentId, "");
        MaterialProductDO parEntity = this.getMaterialProduct(parentId);
        if(list.isEmpty())
            return CommonResult.success("");
        String parIdPath = "/0/";
        if(parEntity != null)
            parIdPath = parEntity.getIdPath();
        for(MaterialProductDO entity : list){
            entity.setIdPath(parIdPath + "/" + entity.getId() + "/");
            materialProductMapper.updateById( entity);
            updateAllIdPath(entity.getId(),level+1);
        }
        return CommonResult.success("");
    }

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

    @Override
    public MaterialProductRespVO createMaterialProduct(MaterialProductSaveReqVO createReqVO) {
        // 插入
        MaterialProductDO materialProduct = BeanUtils.toBean(createReqVO, MaterialProductDO.class);
        materialProductMapper.insert(materialProduct);
        // 返回
        return BeanUtils.toBean(materialProduct, MaterialProductRespVO.class);
    }

    @Override
    public void updateMaterialProduct(MaterialProductSaveReqVO updateReqVO) {
        // 校验存在
        validateMaterialProductExists(updateReqVO.getId());
        // 更新
        MaterialProductDO updateObj = BeanUtils.toBean(updateReqVO, MaterialProductDO.class);
        materialProductMapper.updateById(updateObj);
    }

    @Override
    public void deleteMaterialProduct(Long id) {
        // 校验存在
        validateMaterialProductExists(id);
        // 删除
        materialProductMapper.deleteById(id);
    }

    @Override
        public void deleteMaterialProductListByIds(List<Long> ids) {
        // 校验存在
        validateMaterialProductExists(ids);
        // 删除
        materialProductMapper.deleteByIds(ids);
        }

    private void validateMaterialProductExists(List<Long> ids) {
        List<MaterialProductDO> list = materialProductMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(MATERIAL_PRODUCT_NOT_EXISTS);
        }
    }

    private void validateMaterialProductExists(Long id) {
        if (materialProductMapper.selectById(id) == null) {
            throw exception(MATERIAL_PRODUCT_NOT_EXISTS);
        }
    }

    @Override
    public MaterialProductDO getMaterialProduct(Long id) {
        return materialProductMapper.selectById(id);
    }

    @Override
    public PageResult<MaterialProductDO> getMaterialProductPage(MaterialProductPageReqVO pageReqVO) {
        return materialProductMapper.selectPage(pageReqVO);
    }

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