package com.zt.plat.module.qms.common.data.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zt.plat.framework.common.exception.ServiceException;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.module.qms.common.data.controller.vo.*;
import com.zt.plat.module.qms.common.data.dal.dataobject.DataTemplateDO;
import com.zt.plat.module.qms.common.data.dal.dataobject.DataTemplateDO;
import com.zt.plat.module.qms.core.constant.DataTypeConstant;
import com.zt.plat.module.qms.enums.ErrorCodeConstants;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;

import java.util.*;

import com.zt.plat.module.qms.common.data.dal.dataobject.DataTemplateDO;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.qms.common.data.dal.mapper.DataTemplateMapper;

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

/**
 * 表单设计器模板 Service 实现类
 *
 * @author 后台管理
 */
@Service
@Validated
public class DataTemplateServiceImpl implements DataTemplateService {

    private int id_path_update_level_limit = 7;
    @Resource private DataTemplateMapper dataTemplateMapper;

    @Override
    public DataTemplateDO getLatestDataByKey(String key) {
        LambdaQueryWrapper<DataTemplateDO> query = new LambdaQueryWrapper<>();
        query.eq(DataTemplateDO::getDataKey, key);
        query.eq(DataTemplateDO::getCurrentFlag, "1");
        query.orderByDesc(DataTemplateDO::getUpdateTime);
        query.last("limit 1");
        return dataTemplateMapper.selectOne(query);
    }
    
    @Override
    public CommonResult<String> saveData(DataTemplateSaveReqVO reqV) {
        String newVersionFlag = reqV.getNewVersionFlag();
        if("1".equals(newVersionFlag))
            return saveDataWithNewVersion(reqV);
        Long id = reqV.getId();
        if(id == null){
            reqV.setCancelFlag("0");
            reqV.setCurrentFlag("1");
            reqV.setVersion(1);
            DataTemplateDO dataTemplate = BeanUtils.toBean(reqV, DataTemplateDO.class);
            dataTemplateMapper.insert(dataTemplate);
            id = dataTemplate.getId();
            reqV.setMainId(id);
            reqV.setId( id);
        }
//        DataTemplateDO backData = this.getDataTemplate(id);
//        if(backData.getCancelFlag() == null || backData.getCancelFlag().equals("-1")){
//            reqV.setCancelFlag("0");
//            reqV.setCurrentFlag("1");
//            reqV.setMainId( id);
//        }
        
        this.updateDataTemplate(reqV);
        return CommonResult.success("保存成功");
    }

    @Override
    public CommonResult<String> saveDataWithNewVersion(DataTemplateSaveReqVO createReqVO) {
        DataTemplateDO dataTemplate = BeanUtils.toBean(createReqVO, DataTemplateDO.class);
        dataTemplate.setCurrentFlag("0");
        dataTemplateMapper.updateById(dataTemplate);

        //创建新版本
        Integer version = dataTemplate.getVersion();
        if(version != null)
            version ++;
        else
            version = 1;
        dataTemplate.setId(null);
        dataTemplate.setVersion(version);
        dataTemplate.setCurrentFlag("1");
        dataTemplate.setMainId(createReqVO.getMainId());
        dataTemplateMapper.insert(dataTemplate);
        
        return CommonResult.success("保存成功");
    }

    @Override
    public CommonResult<DataTemplateRespVO> saveClassify(DataTemplateSaveReqVO entity) {
        if(ObjectUtils.isEmpty(entity.getParentId()))
            entity.setParentId(0L);
        Long parentId = entity.getParentId();
        //检查同一层级下是否重名
        List<DataTemplateDO> checkList = listByParId(parentId);
        boolean duplicate = false;
        DataTemplateDO 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 new ServiceException(ErrorCodeConstants.DATA_COLLECTION_CLASSIFY_DUPLICATE);
        entity.setNodeType(DataTypeConstant.DATA_TYPE_CATEGORY);
        Long id = entity.getId();
        DataTemplateDO dataTemplate = BeanUtils.toBean(entity, DataTemplateDO.class);
        if(ObjectUtils.isEmpty(id)){
            dataTemplateMapper.insert(dataTemplate);
            id = dataTemplate.getId();
        }
        DataTemplateDO backData = this.getDataTemplate(id);
        Long parentId_ = backData.getParentId();
        //检查parId，避免父节点设置为本节点的后代节点
        if(parentId_.equals(id))
            throw new ServiceException(ErrorCodeConstants.DATA_COLLECTION_CLASSIFY_PARENT_ERROR);
        String idPath = getIdPath(dataTemplate);
        int curIdIndex = idPath.indexOf("/" + id.toString() + "/");
        int parIdIndex = idPath.indexOf("/" + parentId.toString() + "/");
        if(curIdIndex <= parIdIndex)
            throw new ServiceException(ErrorCodeConstants.DATA_COLLECTION_CLASSIFY_PARENT_ERROR);
        dataTemplate.setIdPath(idPath);

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

    @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<DataTemplateDO> list = listByParId(parentId);
        DataTemplateDO parEntity = this.getDataTemplate(parentId);
        if(list.isEmpty())
            return CommonResult.success("");
        String parIdPath = "/0/";
        if(parEntity != null)
            parIdPath = parEntity.getIdPath();
        for(DataTemplateDO entity : list){
            entity.setIdPath(parIdPath + "/" + entity.getId() + "/");
            dataTemplateMapper.updateById( entity);
            updateAllIdPath(entity.getId(),level+1);
        }
        return CommonResult.success("");
    }

    @Override
    public List<DataTemplateDO> getTreeData() {
        LambdaQueryWrapper<DataTemplateDO> query = new LambdaQueryWrapper<>();
        query.eq(DataTemplateDO::getNodeType, DataTypeConstant.DATA_TYPE_CATEGORY);
        query.orderByAsc(DataTemplateDO::getSortNo);
        return dataTemplateMapper.selectList(query);
    }

    @Override
    public List<DataTemplateDO> listByParId(Long parId) {
        LambdaQueryWrapper<DataTemplateDO> query = new LambdaQueryWrapper<>();
        query.eq(DataTemplateDO::getParentId, parId);
        query.ne(DataTemplateDO::getCancelFlag, -1);
        return dataTemplateMapper.selectList(query);
    }

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

    @Override
    public DataTemplateRespVO createDataTemplate(DataTemplateSaveReqVO createReqVO) {
        // 插入
        DataTemplateDO dataTemplate = BeanUtils.toBean(createReqVO, DataTemplateDO.class);
        dataTemplateMapper.insert(dataTemplate);
        // 返回
        return BeanUtils.toBean(dataTemplate, DataTemplateRespVO.class);
    }

    @Override
    public void updateDataTemplate(DataTemplateSaveReqVO updateReqVO) {
        // 校验存在
        validateDataTemplateExists(updateReqVO.getId());
        // 更新
        DataTemplateDO updateObj = BeanUtils.toBean(updateReqVO, DataTemplateDO.class);
        dataTemplateMapper.updateById(updateObj);
    }

    @Override
    public void deleteDataTemplate(Long id) {
        // 校验存在
        validateDataTemplateExists(id);
        // 删除
        dataTemplateMapper.deleteById(id);
    }

    @Override
        public void deleteDataTemplateListByIds(List<Long> ids) {
        // 校验存在
        validateDataTemplateExists(ids);
        // 删除
        dataTemplateMapper.deleteByIds(ids);
        }

    private void validateDataTemplateExists(List<Long> ids) {
        List<DataTemplateDO> list = dataTemplateMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(DATA_TEMPLATE_NOT_EXISTS);
        }
    }

    private void validateDataTemplateExists(Long id) {
        if (dataTemplateMapper.selectById(id) == null) {
            throw exception(DATA_TEMPLATE_NOT_EXISTS);
        }
    }

    @Override
    public DataTemplateDO getDataTemplate(Long id) {
        return dataTemplateMapper.selectById(id);
    }

    @Override
    public PageResult<DataTemplateDO> getDataTemplatePage(DataTemplatePageReqVO pageReqVO) {
        return dataTemplateMapper.selectPage(pageReqVO);
    }

}