package com.xjrsoft.module.concat.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.xjrsoft.common.enums.DeleteMark;
import com.xjrsoft.common.model.result.RT;
import com.xjrsoft.common.utils.TreeUtil;
import com.xjrsoft.module.concat.dto.ConcatTreeDto;
import com.xjrsoft.module.concat.service.IXjrUserService;
import com.xjrsoft.module.concat.vo.ConcatTreeVo;
import com.xjrsoft.module.organization.entity.Department;
import com.xjrsoft.module.organization.service.IDepartmentService;
import com.xjrsoft.module.teacher.entity.XjrUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
* @title: 通讯录
* @Author dzx
* @Date: 2024年3月25日
* @Version 1.0
*/
@RestController
@RequestMapping("/concat" + "/concat")
@Api(value = "/concat"  + "/concat",tags = "通讯录")
@AllArgsConstructor
public class ConcatController {
    private final IXjrUserService xjrUserService;
    private final IDepartmentService departmentService;


    @GetMapping(value = "/list")
    @ApiOperation(value="教师通讯录")
    @SaCheckPermission("room:detail")
    public RT<List<ConcatTreeVo>> list(ConcatTreeDto dto) throws Exception {
        Long parentId = 0L;
        if(dto.getDeptId() != null){
            parentId = dto.getDeptId();
        }
        List<Department> list = departmentService.list(
            new QueryWrapper<Department>().lambda()
            .eq(Department::getParentId, parentId)
        );
        List<ConcatTreeVo> concatList = new ArrayList<>();
        for (Department department : list) {
            concatList.add(
                new ConcatTreeVo(){{
                    setName(department.getName());
                    setId(department.getId());
                    setType(1);
                }}
            );
        }
        MPJLambdaWrapper<XjrUser> wrapper = new MPJLambdaWrapper<>();
        wrapper.leftJoin("xjr_user_dept_relation t2 on t.id = t2.user_id")
                .eq("t2.dept_id", parentId)
                .eq(XjrUser::getDeleteMark, DeleteMark.NODELETE.getCode());
        List<XjrUser> userList = xjrUserService.selectJoinList(XjrUser.class, wrapper);
        for (XjrUser user : userList) {
            concatList.add(
                    new ConcatTreeVo(){{
                        setName(user.getName());
                        setMobile(user.getMobile());
                        setType(2);
                    }}
            );
        }

        return RT.ok(concatList);
    }
}