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.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.Student;
import com.ruoyi.sim.constant.Consts;
import com.ruoyi.sim.service.impl.StudentService;
import com.ruoyi.system.service.ISysDeptService;
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.List;

@Api("学生Controller")
@RestController
@RequestMapping("/sim/student")
public class StudentController extends BaseController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysRoleService roleService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private StudentService studentService;

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

    // @GetMapping(value = "/letTry/{code}")
    // @ApiOperation("letTry")
    public void letTry(@PathVariable(value = "code") int code) {
        studentService.letTry(code);
    }

    /**
     * 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(studentService.selectStudentByUserId(userId));
    }


    /**
     * 新增学生
     */
    // @PreAuthorize("@ss.hasPermi('sim:student:add')")
    // @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @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_STUDENT});
        }
        return tempAjax;
    }

    /**
     * 修改学生
     */
    // @PreAuthorize("@ss.hasPermi('sim:student:edit')")
    // @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @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;
    }

    /**
     * 删除学生
     */
    // @PreAuthorize("@ss.hasPermi('sim:student:remove')")
    // @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    @ApiOperation("删除学生")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }
}

