/*
 * 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.modular.base.department.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
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.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 org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.user.entity.BizUser;
import vip.xiaonuo.biz.modular.user.mapper.BizUserMapper;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.listener.CommonDataChangeEventCenter;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.core.enums.BaseDataTypeEnum;
import vip.xiaonuo.dev.modular.file.enums.DevFileEngineTypeEnum;
import vip.xiaonuo.dev.modular.file.service.DevFileService;
import vip.xiaonuo.modular.base.baseConfig.entity.BaseConfig;
import vip.xiaonuo.modular.base.department.entity.Department;
import vip.xiaonuo.modular.base.department.mapper.DepartmentMapper;
import vip.xiaonuo.modular.base.department.param.*;
import vip.xiaonuo.modular.base.department.service.DepartmentService;
import vip.xiaonuo.modular.bi.utils.UploadImage;
import vip.xiaonuo.sys.core.enums.SysDataTypeEnum;
import vip.xiaonuo.sys.modular.user.entity.SysUser;
import vip.xiaonuo.sys.modular.user.mapper.SysUserMapper;

import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门Service接口实现类
 *
 * @author newspaper
 * @date  2023/12/13 08:44
 **/
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Autowired
    private BizUserMapper bizUserMapper;
    @Autowired
    private DevFileService devFileService;
    @Autowired
    private UploadImage uploadImage;

    @Override
    public List<Tree<String>> tree(DepartmentOrgIdParam departmentOrgIdParam) {
        String orgId = departmentOrgIdParam.getOrgId();
        List<Department> allDepartment= new ArrayList<>();
        List<Department> baseConfigs = this.list(new LambdaQueryWrapper<Department>().eq(Department::getOrgId, orgId).orderByAsc(Department::getSortCode));

        allDepartment.addAll(baseConfigs);
        List<TreeNode<String>> treeNodeList = allDepartment.stream().map(department ->
                new TreeNode<>(department.getId(), department.getParentId(),
                        department.getDepartmentName(), department.getSortCode()).setExtra(JSONUtil.parseObj(department)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }

    @Override
    public Page<Department> page(DepartmentPageParam departmentPageParam) {
        QueryWrapper<Department> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isAllNotEmpty(departmentPageParam.getSortField(), departmentPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(departmentPageParam.getSortOrder());
            queryWrapper.orderBy(true, departmentPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(departmentPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(Department::getSortCode);
        }
        if (ObjectUtil.isNotEmpty(departmentPageParam.getParentId())){
            queryWrapper.lambda().eq(Department::getParentId,departmentPageParam.getParentId());
        }
        if (ObjectUtil.isNotEmpty(departmentPageParam.getSearchKey())){
            queryWrapper.lambda().eq(Department::getDepartmentName,departmentPageParam.getSearchKey());
        }
        queryWrapper.lambda().eq(Department::getOrgId,departmentPageParam.getOrgId());
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(String departmentName, String parentId, String departmentRegion, String detailLocation, String departmentPhone, String departmentManager, String remarks, Integer sortCode, MultipartFile departmentImgUrl,String orgId) throws IOException {
        if (this.count(new QueryWrapper<Department>().lambda().eq(Department::getDepartmentName,departmentName)) > 0) {
            throw new CommonException("存在重复部门名称!");
        }
        Department department = new Department();
        department.setDepartmentName(departmentName);
        department.setParentId(parentId);
        department.setDepartmentRegion(departmentRegion);
        department.setDetailLocation(detailLocation);
        department.setDepartmentPhone(departmentPhone);
        department.setDepartmentManager(departmentManager);
        department.setRemarks(remarks);
        department.setSortCode(sortCode);
        department.setOrgId(orgId);
        if (ObjectUtil.isNotEmpty(departmentImgUrl)){
            String uploadReturnUrl = uploadImage.getImageCom(departmentImgUrl);
            department.setDepartmentImgUrl(uploadReturnUrl);
        }
        this.save(department);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(String id,String departmentName, String parentId, String departmentRegion, String detailLocation, String departmentPhone, String departmentManager, String remarks, Integer sortCode, MultipartFile departmentImgUrl) throws IOException {
        Department department = this.queryEntity(id);
        if (this.count(new QueryWrapper<Department>().lambda().eq(Department::getOrgId,department.getOrgId()).eq(Department::getDepartmentName,departmentName).ne(Department::getId,id)) > 0) {
            throw new CommonException("存在重复部门名称!");
        }
        department.setDepartmentName(departmentName);
        department.setParentId(parentId);
        department.setDepartmentRegion(departmentRegion);
        department.setDetailLocation(detailLocation);
        department.setDepartmentPhone(departmentPhone);
        department.setDepartmentManager(departmentManager);
        department.setRemarks(remarks);
        department.setSortCode(sortCode);
        if (ObjectUtil.isNotEmpty(departmentImgUrl)){
            String uploadReturnUrl = uploadImage.getImageCom(departmentImgUrl);
            if (uploadReturnUrl.equals("上传失败")){
                throw new CommonException("图片上传失败!");
            }
            department.setDepartmentImgUrl(uploadReturnUrl);
        }
        this.updateById(department);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<DepartmentIdParam> departmentIdParamList) {
        List<String> toDeleteDepartmentIdList = CollStreamUtil.toList(departmentIdParamList, DepartmentIdParam::getId);
        for (String s : toDeleteDepartmentIdList) {
            if (this.count(new QueryWrapper<Department>().lambda().eq(Department::getParentId,s)) > 0) {
                throw new CommonException("部门存在下级,请先删除下级部门!");
            }
            if (bizUserMapper.selectCount(new QueryWrapper<BizUser>().lambda().eq(BizUser::getDepartmentId,s)) > 0){
                throw new CommonException("部门存在人员,请先编辑或删除下属人员!");
            }
        }
        // 执行删除
        this.removeByIds(toDeleteDepartmentIdList);

        // 发布删除事件
        CommonDataChangeEventCenter.doDeleteWithDataId(BaseDataTypeEnum.DEPARTMENT.getValue(), toDeleteDepartmentIdList);
    }

    @Override
    public Department detail(DepartmentIdParam departmentIdParam) {
        return this.queryEntity(departmentIdParam.getId());
    }

    @Override
    public Department queryEntity(String id) {
        Department department = this.getById(id);
        if(ObjectUtil.isEmpty(department)) {
            throw new CommonException("部门不存在，id值为：{}", id);
        }
        return department;
    }

    @Override
    public Page<Department> listChild(DepartmentChildParam departmentChildParam) {
        String orgId = departmentChildParam.getOrgId();
        Page<Department> departmentList = this.page(CommonPageRequest.defaultPage(),new QueryWrapper<Department>().lambda().eq(Department::getOrgId, orgId).eq(Department::getParentId,departmentChildParam.getParentId()));
        return departmentList;
    }

    @Override
    public List<BizUser> userSelector(DepartmentOrgIdParam departmentOrgIdParam) {
        String orgId = departmentOrgIdParam.getOrgId();
        List<BizUser> users = bizUserMapper.selectList(new QueryWrapper<BizUser>().eq("ORG_ID", orgId));
        return users;
    }


}
