/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.disk.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.enums.SysDataTypeEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.disk.domain.College;
import vip.xiaonuo.disk.mapper.CollegeMapper;
import vip.xiaonuo.disk.param.*;
import vip.xiaonuo.disk.service.CollegeService;

import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * collegeService接口实现类
 *
 * @author pans
 * @date  2025/06/26 09:09
 **/
@Service
public class CollegeServiceImpl extends ServiceImpl<CollegeMapper, College> implements CollegeService {
   @Autowired
   private CollegeMapper collegeMapper;
    @Override
    public Page<College> page(CollegePageParam collegePageParam) {
        QueryWrapper<College> queryWrapper = new QueryWrapper<>();
        // 查询部分字段
        queryWrapper.lambda().select(College::getId, College::getParentId, College::getName,
                College::getCategory, College::getSortCode, College::getIsResourceaccount);
        if(ObjectUtil.isNotEmpty(collegePageParam.getParentId())) {
            queryWrapper.lambda().eq(College::getParentId, collegePageParam.getParentId());
        }
        if(ObjectUtil.isNotEmpty(collegePageParam.getSearchKey())) {
            queryWrapper.lambda().like(College::getName, collegePageParam.getSearchKey());
        }
        if(ObjectUtil.isAllNotEmpty(collegePageParam.getSortField(), collegePageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(collegePageParam.getSortOrder());
            queryWrapper.orderBy(true, collegePageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(collegePageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(College::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Override
    public List<Tree<String>> tree() {
        List<College> collegeList = this.getAllOrgList();
        List<TreeNode<String>> treeNodeList = collegeList.stream().map(college ->
                        new TreeNode<>(college.getId(), college.getParentId(),
                                college.getName(), college.getSortCode()).setExtra(JSONUtil.parseObj(college)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(CollegeAddParam collegeAddParam) {

        College college = BeanUtil.toBean(collegeAddParam, College.class);
        // 重复名称
        boolean repeatName = this.count(new LambdaQueryWrapper<College>().eq(College::getParentId, college.getParentId())
                .eq(College::getName, college.getName())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级组织，名称为：{}", college.getName());
        }
        college.setCode(RandomUtil.randomString(10));
        this.save(college);

        // 发布增加事件
     //   CommonDataChangeEventCenter.doAddWithData(SysDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(college));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(CollegeEditParam collegeEditParam) {
        College college = this.queryEntity(collegeEditParam.getId());
        BeanUtil.copyProperties(collegeEditParam, college);
        boolean repeatName = this.count(new LambdaQueryWrapper<College>().eq(College::getParentId, college.getParentId())
                .eq(College::getName, college.getName()).ne(College::getId, college.getId())) > 0;
        if(repeatName) {
            throw new CommonException("存在重复的同级组织，名称为：{}", college.getName());
        }
        List<College> originDataList = this.getAllOrgList();
        boolean errorLevel = this.getChildListById(originDataList, college.getId(), true).stream()
                .map(College::getId).collect(Collectors.toList()).contains(college.getParentId());
        if(errorLevel) {
            throw new CommonException("不可选择上级组织：{}", this.getById(originDataList, college.getParentId()).getName());
        }
        this.updateById(college);

        // 发布更新事件
        CommonDataChangeEventCenter.doUpdateWithData(SysDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(college));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<CollegeIdParam> collegeIdParamList) {
        List<String> orgIdList = CollStreamUtil.toList(collegeIdParamList, CollegeIdParam::getId);
        if(ObjectUtil.isNotEmpty(orgIdList)) {
            List<College> allOrgList = this.getAllOrgList();
            // 获取所有子组织
            List<String> toDeleteOrgIdList = CollectionUtil.newArrayList();
            orgIdList.forEach(orgId -> toDeleteOrgIdList.addAll(this.getChildListById(allOrgList, orgId, true).stream()
                    .map(College::getId).collect(Collectors.toList())));

            // 执行删除
            this.removeByIds(toDeleteOrgIdList);

            // 发布删除事件
            //CommonDataChangeEventCenter.doDeleteWithDataId(SysDataTypeEnum.ORG.getValue(), toDeleteOrgIdList);
        }
    }

    @Override
    public College detail(CollegeIdParam collegeIdParam) {
        return this.queryEntity(collegeIdParam.getId());
    }

    @Override
    public College queryEntity(String id) {
        College college = this.getById(id);
        if(ObjectUtil.isEmpty(college)) {
            throw new CommonException("组织不存在，id值为：{}", id);
        }
        return college;
    }

    @Override
    public List<College> getAllOrgList() {
        return this.list(new LambdaQueryWrapper<College>().orderByAsc(College::getSortCode));
    }

    @Override
    public String getOrgIdByOrgFullNameWithCreate(String orgFullName) {
        List<College> allOrgList = this.getAllOrgList();
        List<Tree<String>> treeList = TreeUtil.build(allOrgList.stream().map(college ->
                        new TreeNode<>(college.getId(), college.getParentId(), college.getName(), college.getSortCode()))
                .collect(Collectors.toList()), "0");
        return findOrgIdByOrgName("0", StrUtil.split(orgFullName, StrUtil.DASHED).iterator(), allOrgList, treeList);
    }

    public String findOrgIdByOrgName(String parentId, Iterator<String> iterator, List<College> allOrgList, List<Tree<String>> treeList) {
        String orgName = iterator.next();
        if(ObjectUtil.isNotEmpty(treeList)) {
            List<Tree<String>> findList = treeList.stream().filter(tree -> tree.getName().equals(orgName)).collect(Collectors.toList());
            if(ObjectUtil.isNotEmpty(findList)) {
                if(iterator.hasNext()) {
                    return findOrgIdByOrgName(findList.get(0).getId(), iterator, allOrgList, findList.get(0).getChildren());
                } else {
                    return findList.get(0).getId();
                }
            }
        }
        String orgId = this.doCreateOrg(parentId, orgName, allOrgList);
        if(iterator.hasNext()) {
            return findOrgIdByOrgName(orgId, iterator, allOrgList, CollectionUtil.newArrayList());
        } else {
            return orgId;
        }
    }

    /**
     * 执行创建组织
     *
     * @author xuyuxiang
     * @date 2023/3/8 9:38
     **/
    public String doCreateOrg(String parentId, String orgName, List<College> allOrgList) {
        //创建该组织
        College college = new College();
        college.setName(orgName);
        college.setCode(RandomUtil.randomString(10));
        college.setParentId(parentId);
        college.setSortCode(99);
        this.save(college);
        // 发布增加事件
      //  CommonDataChangeEventCenter.doAddWithData(SysDataTypeEnum.ORG.getValue(), JSONUtil.createArray().put(college));
        return college.getId();
    }

    /* ====组织部分所需要用到的选择器==== */

    @Override
    public List<Tree<String>> orgTreeSelector() {
        List<College> collegeList = this.getAllOrgList();
        List<TreeNode<String>> treeNodeList = collegeList.stream().map(college ->
                        new TreeNode<>(college.getId(), college.getParentId(), college.getName(), college.getSortCode()))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public Page<College> orgListSelector(CollegeOrgSelectorOrgListParam collegeSelectorOrgListParam) {
        LambdaQueryWrapper<College> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询部分字段
        lambdaQueryWrapper.select(College::getId, College::getParentId, College::getName,
                College::getCategory, College::getSortCode);
        if(ObjectUtil.isNotEmpty(collegeSelectorOrgListParam.getParentId())) {
            lambdaQueryWrapper.eq(College::getParentId, collegeSelectorOrgListParam.getParentId());
        }
        if(ObjectUtil.isNotEmpty(collegeSelectorOrgListParam.getSearchKey())) {
            lambdaQueryWrapper.like(College::getName, collegeSelectorOrgListParam.getSearchKey());
        }
        lambdaQueryWrapper.orderByAsc(College::getSortCode);
        return this.page(CommonPageRequest.defaultPage(), lambdaQueryWrapper);
    }



    /* ====以下为各种递归方法==== */

    @Override
    public List<College> getParentAndChildListById(List<College> originDataList, String id, boolean includeSelf) {
        List<College> parentListById = this.getParentListById(originDataList, id, false);
        List<College> childListById = this.getChildListById(originDataList, id, true);
        parentListById.addAll(childListById);
        return parentListById;
    }

    @Override
    public List<College> getChildListById(List<College> originDataList, String id, boolean includeSelf) {
        List<College> resultList = CollectionUtil.newArrayList();
        execRecursionFindChild(originDataList, id, resultList);
        if(includeSelf) {
            College self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    @Override
    public List<College> getParentListById(List<College> originDataList, String id, boolean includeSelf) {
        List<College> resultList = CollectionUtil.newArrayList();
        execRecursionFindParent(originDataList, id, resultList);
        if(includeSelf) {
            College self = this.getById(originDataList, id);
            if(ObjectUtil.isNotEmpty(self)) {
                resultList.add(self);
            }
        }
        return resultList;
    }

    public void execRecursionFindChild(List<College> originDataList, String id, List<College> resultList) {
        originDataList.forEach(item -> {
            if(item.getParentId().equals(id)) {
                resultList.add(item);
                execRecursionFindChild(originDataList, item.getId(), resultList);
            }
        });
    }

    public void execRecursionFindParent(List<College> originDataList, String id, List<College> resultList) {
        originDataList.forEach(item -> {
            if(item.getId().equals(id)) {
                College parent = this.getById(originDataList, item.getParentId());
                if(ObjectUtil.isNotEmpty(parent)) {
                    resultList.add(parent);
                }
                execRecursionFindParent(originDataList, item.getParentId(), resultList);
            }
        });
    }

    @Override
    public College getById(List<College> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, College::getId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }

    @Override
    public College getParentById(List<College> originDataList, String id) {
        College self = this.getById(originDataList, id);
        return ObjectUtil.isNotEmpty(self)?self:this.getById(originDataList, self.getParentId());
    }

    @Override
    public College getChildById(List<College> originDataList, String id) {
        int index = CollStreamUtil.toList(originDataList, College::getParentId).indexOf(id);
        return index == -1?null:originDataList.get(index);
    }
}
