package com.ruoyi.sim.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.sim.domain.Clazz;
import com.ruoyi.sim.domain.Major;
import com.ruoyi.sim.service.impl.AddOnDeptService;
import com.ruoyi.sim.constant.Consts;
import com.ruoyi.sim.service.impl.TeacherService;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

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

@Api("教师Controller")
@RestController
@RequestMapping("/sim/teacher")
public class TeacherController extends BaseController {


    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysDeptMapper deptMapper;
    @Autowired
    private AddOnDeptService addOnDeptService;
    @Autowired
    private TeacherService teacherService;

    @GetMapping("/list")
    @ApiOperation("[分页]查询教师列表")
    public TableDataInfo list(SysUser suQ) {
        return getDataTable(teacherService.list2(suQ));
    }

    /**
     * copy
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = "/{userId}")
    @ApiOperation("根据userId获取教师详细信息")
    public AjaxResult getInfo(@PathVariable(value = "userId") Long userId) {
        // -------------------------------- tom add  --------------------------------
        // 覆盖data
        // ajax.put(AjaxResult.DATA_TAG, student);
        // -------------------------------- tom add  --------------------------------
        return success(teacherService.selectTeacherByUserId(userId));
    }

    @PostMapping
    @ApiOperation("新增教师")
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        AjaxResult tempAjax = toAjax(userService.insertUser(user));
        // --------------------------------  --------------------------------

        // 自动添加权限
        SysUser suF = userService.selectUserByUserName(user.getUserName());
        logger.info(String.valueOf(suF));
        if (suF != null) {
            // roleService.insertAuthUsers(Consts.ROLE_ID_STUDENT, new Long[]{userId});
            userService.insertUserAuth(suF.getUserId(), new Long[]{Consts.ROLE_ID_TEACHER});
        }
        return tempAjax;
    }

    @PutMapping
    @ApiOperation("修改教师")
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        AjaxResult tempAjax = toAjax(userService.updateUser(user));
        // --------------------------------  --------------------------------
        // todo:不允许修改权限。
        return tempAjax;
    }

    /**
     * 删除教师
     */
    @DeleteMapping("/{userIds}")
    @ApiOperation("删除教师")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 获取班级/部门列表
     *
     * @return
     */
    @GetMapping("/class-major/list")
    @ApiOperation("获取班级/部门列表")
    /**
     * 获取班级/部门列表
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    public List<Clazz> listClassWithMajor() {
        // 构建查询对象。

        //
        List<SysDept> listD = deptMapper.selectDeptList(new SysDept());
        List<Clazz> listC = new ArrayList<>();
        for (SysDept d : listD) {
            Clazz c = new Clazz();
            Major m = addOnDeptService.selectMajorByDeptId(d.getDeptId());
            c.setSysDept(d);
            c.setMajor(m);
            listC.add(c);
        }
        return listC;
    }
}
