package com.testor.module.notice.service.impl;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.excel.util.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.biz.sys.post.model.domain.TSysPost;
import com.testor.biz.sys.post.service.TSysPostService;
import com.testor.biz.sys.user.model.domain.SysUser;
import com.testor.biz.sys.user.service.SysUserService;
import com.testor.module.notice.dao.TSysOrgDao;
import com.testor.module.notice.model.domain.TSysOrg;
import com.testor.module.notice.model.domain.TreeVO;
import com.testor.module.notice.service.TSysOrgService;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * noticeService业务层处理
 *
 * @author tong-framework
 * @date 2022-04-27 18:10:12
 */
@Service
public class TSysOrgServiceImpl extends SuperServiceImpl<TSysOrgDao, TSysOrg> implements TSysOrgService {
    @Autowired
    private TSysOrgDao tSysOrgDao;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private TSysPostService postService;

    @Override
    public BaseResponse getOrg() {
        BaseResponse<Object> response = new BaseResponse<>();
        try {
            String loginName = ContextUtils.getLoginUser().getLoginName();
            LambdaQueryWrapper<SysUser> querywrapper = new LambdaQueryWrapper<>();
            querywrapper.eq(SysUser::getLoginName, loginName);
            SysUser one = sysUserService.getOne(querywrapper);
            String orgId = one.getOrgId();
            SysOrg sysorg = sysOrgService.getById(orgId);
            List<TreeVO> treeVOS = tSysOrgDao.selectAllTree(orgId);
            response.setData(treeVOS);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addIsRentDept() {
        // 1. 查询租赁库数据
        List<TSysOrg> tSysOrgs = tSysOrgDao.selectIsRent();
        if (CollectionUtils.isEmpty(tSysOrgs)) {
            return 0;
        }

        // 2. 查询已有部门的租赁库数据
        List<TSysOrg> tSysOrgDept = tSysOrgDao.selectIsRentDept();

        // 3. 筛选出没有子部门的租赁库
        Set<String> parentIdsWithDept = tSysOrgDept.stream()
                .map(TSysOrg::getParentId)
                .collect(Collectors.toSet());

        List<TSysOrg> tSysOrgWithoutDept = tSysOrgs.stream()
                .filter(org -> !parentIdsWithDept.contains(org.getOrgId()))
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(tSysOrgWithoutDept)) {
            return 0;
        }

        // 4. 为无部门的租赁库添加默认部门
        List<TSysOrg> addSysOrg = new ArrayList<>();
        for (TSysOrg temp : tSysOrgWithoutDept) {
            if (StringUtils.isEmpty(temp.getOrgId()) || StringUtils.isEmpty(temp.getParentId())) {
                log.warn("orgId 或 parentId 为空，跳过");
                continue;
            }

            TSysOrg tSysOrg = new TSysOrg();
            String orgId = IdWorker.getIdStr(); // 使用雪花算法生成唯一 ID
            tSysOrg.setOrgId(orgId);
            tSysOrg.setParentId(temp.getOrgId());
            tSysOrg.setParentIds(temp.getParentId() + "," + orgId);
            tSysOrg.setTreeSort("1");
            tSysOrg.setTreeLevel("4");
            tSysOrg.setOrgName("安全环保部");
            tSysOrg.setStatus("0");
            tSysOrg.setIsDept("1");
            tSysOrg.setIsRent("1");
            addSysOrg.add(tSysOrg);
        }

        // 5. 为这些部门添加默认岗位
        List<TSysPost> addSysPost = new ArrayList<>();
        for (TSysOrg temp : addSysOrg) {
            TSysPost sysPost = new TSysPost();
            String id = IdWorker.getIdStr(); // 使用雪花算法生成唯一 ID
            sysPost.setId(id);
            sysPost.setDeptId(temp.getOrgId());
            sysPost.setOrgId(temp.getParentId());
            sysPost.setPostName("安全环保部员工");
            sysPost.setStatus("0");
            addSysPost.add(sysPost);
        }

        // 6. 批量插入（如果某条记录失败，整个事务回滚）
        if (!addSysOrg.isEmpty()) {
            this.saveBatch(addSysOrg);
        }
        if (!addSysPost.isEmpty()) {
            postService.saveBatch(addSysPost);
        }

        return 1;
    }
//    @Override
//    public BaseResponse getOrg() {
//        BaseResponse<Object> response = new BaseResponse<>();
//        try {
//            String loginName = ContextUtils.getLoginUser().getLoginName();
//            LambdaQueryWrapper<SysUser> querywrapper = new LambdaQueryWrapper<>();
//            querywrapper.eq(SysUser::getLoginName, loginName);
//            SysUser one = sysUserService.getOne(querywrapper);
//            String orgId = one.getOrgId();
//            List<TreeVO> list = this.recursiveTree(orgId);
//            response.setData(list);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return response;
//    }

    private List<TreeVO> recursiveTree(String orgId) {
        List<TreeVO> list = new ArrayList<>();
        TreeVO treeVO = new TreeVO();
        LambdaQueryWrapper<SysOrg> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrg::getParentId, orgId);
        SysOrg one = sysOrgService.getOne(queryWrapper);
        treeVO.setName(one.getOrgName());
        treeVO.setId(one.getOrgId());
        treeVO.setPid(one.getParentId());
        list.add(treeVO);
        if (one != null) {
            recursiveTree(one.getOrgId());
            treeVO.setChildren(list);
        }
        return list;
    }
}
