package cn.xluobo.business.sys.admin.service;

import cn.xluobo.business.sc.student.repo.model.ScStudentCourse;
import cn.xluobo.business.sc.student.service.IScStudentCourseService;
import cn.xluobo.business.sys.admin.domain.req.ReqSearchSysDept;
import cn.xluobo.business.sys.admin.domain.resp.RespTreeSelect;
import cn.xluobo.business.sys.admin.model.SysUserDept;
import cn.xluobo.core.api.APIResponse;
import cn.xluobo.core.api.ApiResEnums;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ：zhangbaoyu
 * @date ：Created in 2020-01-14 17:24
 */
@Service
@Transactional
public class BusinessSysDeptService {

    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysUserDeptService userDeptService;
    @Autowired
    private IScStudentCourseService studentCourseService;

    /**
     * 查询树
     *
     * @param reqSearchSysDept
     * @return
     */
    public APIResponse searchList(ReqSearchSysDept reqSearchSysDept) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("delete_flag", "0");
        if (StringUtils.isNotEmpty(reqSearchSysDept.getDeptName())) {
            qw.like("dept_name", reqSearchSysDept.getDeptName());
        }
//        if (StringUtils.isNotEmpty(reqSearchSysDept.getInUse())) {
//            qw.eq("in_use", reqSearchSysDept.getInUse());
//        }
//        qw.orderByAsc("sort");
//        List<SysDept> list = sysDeptService.list(qw);
//        SysDept sysDept = new SysDept();
//        sysDept.setDeptId(-1L);
//        sysDept.converterTree(list);
//        List<SysDept> respPage = sysDept.getChildren();
        return APIResponse.toAPIResponse(null);
    }

    /**
     * 前端select
     *
     * @return
     */
    public APIResponse treeSelect() {
        SysDept sysDept = new SysDept();
        QueryWrapper<SysDept> qw = new QueryWrapper(sysDept);
        qw.orderByAsc("sort");
        List<SysDept> list = sysDeptService.list(qw);
        SysDept tree = new SysDept();
        tree.setDeptId(-1L);
        this.converterTree(list,tree);
        List<SysDept> children = tree.getChildren();
        List<RespTreeSelect> respTreeSelects = children.stream().map(RespTreeSelect::new).collect(Collectors.toList());
        return APIResponse.toAPIResponse(respTreeSelects);
    }

    private static Map<Long, List<SysDept>> subTreeMap = new HashMap<>();
    private List<SysDept> children;
    /**
     * 树转换
     * @param sysDeptList
     */
    public void converterTree(List<SysDept> sysDeptList,SysDept tree) {
        subTreeMap.clear();
        for (SysDept menu : sysDeptList) {
            List<SysDept> subTreeList = subTreeMap.get(menu.getParentId());
            if (null == subTreeList) {
                subTreeList = new LinkedList<>();
                subTreeMap.put(menu.getParentId(),subTreeList);
            }
            subTreeList.add(menu);
        }

        this.children = treeDepth(tree).getChildren();
        if(this.children.isEmpty()){
            this.children = sysDeptList;
        }
    }
    private SysDept treeDepth(SysDept sysDept) {
        Long deptId = sysDept.getDeptId();
        List<SysDept> childMenuList = subTreeMap.get(deptId);
        if(null != childMenuList){
            List<SysDept> childList = Lists.newLinkedList();
            for (SysDept childMenu : childMenuList) {
                SysDept child = treeDepth(childMenu);
                childList.add(child);
            }
            sysDept.setChildren(childList);
            return sysDept;
        }else{
            sysDept.setChildren(Lists.newLinkedList());
            return sysDept;
        }
    }


    /**
     * 详情
     *
     * @param deptId
     * @return
     */
    public APIResponse detailById(Long deptId) {
        if (null == deptId) {
            return APIResponse.toAPIResponse(null);
        }
        SysDept detailInfo = sysDeptService.getById(deptId);
        return APIResponse.toAPIResponse(detailInfo);
    }


    /**
     * 删除
     *
     * @param deptIds
     * @return
     */
    public APIResponse deleteById(List<Long> deptIds) {
        if (null == deptIds || deptIds.isEmpty()) {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }

        for (Long deptId : deptIds) {
            if (sysDeptService.hadChild(deptId)) {
                return APIResponse.toExceptionResponse("存在子部门不能删除");
            }
            if (sysDeptService.hadUser(deptId)) {
                return APIResponse.toExceptionResponse("存在用户不能删除");
            }
        }

        // 如果已报读 不允许删除
        QueryWrapper<ScStudentCourse> qwSc = new QueryWrapper<>();
        qwSc.in("dept_id", deptIds);
        int studentCourseCount = studentCourseService.count(qwSc);
        if (studentCourseCount != 0) {
            return APIResponse.toExceptionResponse("该校区已有报读学员,无法删除");
        }

        boolean deleteDept = sysDeptService.removeByIds(deptIds);
        if (deleteDept) {
            return APIResponse.toOkResponse();
        } else {
            return APIResponse.toExceptionResponse(ApiResEnums.FAIL_WAIT_A_MINUTE);
        }
    }

    /**
     * 前端select
     *
     * @return
     */
    public List<RespTreeSelect> campusList() {
        SysDept sysDept = new SysDept();
//        sysDept.setInUse("1");
//        sysDept.setDeleteFlag("0");
//        sysDept.setDeptType("2");
        QueryWrapper<SysDept> qw = new QueryWrapper(sysDept);
        qw.orderByAsc("sort");
        List<SysDept> list = sysDeptService.list(qw);
        List<RespTreeSelect> respTreeSelects = list.stream().map(RespTreeSelect::new).collect(Collectors.toList());
        return respTreeSelects;
    }

    /**
     * 前端select
     *
     * @return
     */
    public List<RespTreeSelect> campusListLimitByUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        List<SysDept> deptList = sysDeptService.selectUserCampusList(loginUser.getUserId());
        List<RespTreeSelect> respTreeSelects = deptList.stream().map(RespTreeSelect::new).collect(Collectors.toList());
        return respTreeSelects;
    }

    /**
     * 校区选择
     * 如果拥有全部校区权限，返回全部校区 部分校区
     * 否二 返回 部分校区
     *
     * @return
     */
    public List<RespTreeSelect> campusSelect() {

        List<RespTreeSelect> list = Lists.newArrayList();

        list.add(new RespTreeSelect(9L,"全部校区",null));
        list.add(new RespTreeSelect(0L,"部分校区",null));

        return list;
    }

    /**
     * 校区选择
     * 如果拥有全部校区权限，返回全部校区 部分校区
     * 否二 返回 部分校区
     *
     * @return
     */
    public List<RespTreeSelect> campusSelectLimitByUser() {
        LoginUser loginUser = SecurityUtils.getLoginUser();

        List<RespTreeSelect> list = Lists.newArrayList();

        QueryWrapper qw = new QueryWrapper();
        qw.eq("user_id",loginUser.getUserId());
        qw.eq("dept_id","-1");
        SysUserDept one = userDeptService.getOne(qw);
        if(null != one){
            list.add(new RespTreeSelect(9L,"全部校区",null));
        }
        list.add(new RespTreeSelect(0L,"部分校区",null));

        return list;
    }
}
