package com.srs.web.controller.dormitory;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.*;
import org.springframework.security.access.prepost.PreAuthorize;

import com.srs.dormitory.domain.DmsStuDaily;
import com.srs.dormitory.service.IDmsStuDailyService;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.poi.ExcelUtil;
import com.srs.common.enums.BusinessType;
import com.srs.common.annotation.Log;
import com.srs.common.core.page.TableDataInfo;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.system.service.ISysUserService;

/**
 * 学生宿舍打卡Controller
 *
 * @author srs
 * @date 2024-12-21
 */
@RestController
@RequestMapping("/dormitory/daily")
@Api(value = "学生宿舍打卡管理", tags = "学生宿舍打卡管理")
public class DmsStuDailyController extends BaseController {
    @Autowired
    private IDmsStuDailyService dmsStuDailyService;

    @Autowired
    private ISysUserService userService;

    @GetMapping("/countDeptCard")
    public AjaxResult countDeptCard(){
        List<Map<String, Object>> list = dmsStuDailyService.countDeptCard();
        return AjaxResult.success(list);
    }


    @GetMapping("/listLeaveLog")
    public AjaxResult listLeaveLog(){
        List<String> list = dmsStuDailyService.listLeaveLog();
        return AjaxResult.success(list);
    }


    @GetMapping("/countDeptShixi")
    public AjaxResult countDeptShixi(){
        List<Map<String, Object>> list = dmsStuDailyService.countDeptShixi();
        return AjaxResult.success(list);
    }


    @GetMapping("/countDeptLeave")
    public AjaxResult countDeptLeave(){
        List<Map<String, Object>> list = dmsStuDailyService.countDeptLeave();
        return AjaxResult.success(list);
    }

    @PreAuthorize("@ss.hasPermi('dormitory:daily:sendMail')")
    @PostMapping("/sendMail")
    @ApiOperation("向未打卡学生发送信息")
    public AjaxResult sendMail(){
        return dmsStuDailyService.sendMail();
    }


    @PreAuthorize("@ss.hasPermi('dormitory:daily:listView')")
    @GetMapping("/listView")
    @ApiOperation("查询学生宿舍打卡列表")
    public TableDataInfo listView(DmsStuDaily param)
    {

        // 获取当前用户信息
        String username = getUsername();
        SysUser currentUser = userService.selectUserByUserName(username);

        // 根据用户角色设置数据过滤条件
        if (currentUser != null) {
            // 获取用户角色组
            String roleGroup = userService.selectUserRoleGroup(username);

            // 检查用户拥有的角色
            boolean isXuegongRole = roleGroup.contains("学工");
            boolean isDeptRole = roleGroup.contains("学务干事") || roleGroup.contains("学务办初审");
            boolean isTeacherRole = roleGroup.contains("辅导员");

            // 根据角色组合和前端传递的roleType参数进行过滤
            if ((isXuegongRole && isTeacherRole) || (isDeptRole && isTeacherRole)) {
                // 多角色用户，根据roleType参数决定查看哪种数据
                if ("teacher".equals(param.getRoleType())) {
                    // 辅导员权限：查看个人班级数据
                    param.setTeacherNo(username);
                } else if ("dept".equals(param.getRoleType())) {
                    // 学务干事权限：查看学院数据
                    if (currentUser.getDept() != null) {
                        param.setDeptName(currentUser.getDept().getDeptName());
                    }
                } else if ("xuegong".equals(param.getRoleType()) || param.getRoleType() == null) {
                    // 学工权限：查看所有数据，不设置过滤条件
                }
            } else if (isXuegongRole) {
                // 只有学工角色，查看所有数据，不设置过滤条件
            } else if (isDeptRole) {
                // 只有学务干事角色，查看学院数据
                if (currentUser.getDept() != null) {
                    param.setDeptName(currentUser.getDept().getDeptName());
                }
            } else if (isTeacherRole) {
                // 只有辅导员角色，查看个人班级数据
                param.setTeacherNo(username);
            }
            // 超级管理员可以查看所有数据，不设置过滤条件
        }

        startPage();
        List<DmsStuDaily> list = dmsStuDailyService.listView(param);
        return getDataTable(list);
    }

    /**
     * 主要用于前端不同角色的切换返回不同的数据
     */
    @GetMapping("/checkRoles")
    @ApiOperation("检查用户角色信息")
    public AjaxResult checkUserRoles() {
        String username = getUsername();
        String roleGroup = userService.selectUserRoleGroup(username);
        SysUser currentUser = userService.selectUserByUserName(username);

        boolean isXuegongRole = roleGroup.contains("学工");
        boolean isDeptRole = roleGroup.contains("学务干事");
        boolean isTeacherRole = roleGroup.contains("辅导员");

        // 判断多角色情况
        boolean hasMultipleRoles = (isXuegongRole && isTeacherRole) || (isDeptRole && isTeacherRole);

        Map<String, Object> roleInfo = new HashMap<>();
        roleInfo.put("hasMultipleRoles", hasMultipleRoles);
        roleInfo.put("isAdmin", SecurityUtils.isAdmin(SecurityUtils.getUserId()));
        roleInfo.put("isXuegong", isXuegongRole);
        roleInfo.put("isXuewu", isDeptRole);
        roleInfo.put("isFudaoyuan", isTeacherRole);

        // 设置默认角色和可用角色选项
        if (isXuegongRole && isTeacherRole) {
            // 学工+辅导员组合
            roleInfo.put("defaultRole", "xuegong");
            roleInfo.put("availableRoles", new String[]{"xuegong", "teacher"});
        } else if (isDeptRole && isTeacherRole) {
            // 学务干事+辅导员组合
            roleInfo.put("defaultRole", "dept");
            roleInfo.put("availableRoles", new String[]{"dept", "teacher"});
        } else if (isXuegongRole) {
            // 只有学工角色
            roleInfo.put("defaultRole", "xuegong");
        } else if (isDeptRole) {
            // 只有学务干事角色
            roleInfo.put("defaultRole", "dept");
        } else if (isTeacherRole) {
            // 只有辅导员角色
            roleInfo.put("defaultRole", "teacher");
        }

        // 添加用户部门信息
        if (currentUser != null && currentUser.getDept() != null) {
            roleInfo.put("userDeptName", currentUser.getDept().getDeptName());
        }

        return AjaxResult.success(roleInfo);
    }


    @ApiOperation("学生打卡")
    @PostMapping("/doCard")
    public AjaxResult doCard(@RequestBody DmsStuDaily param){
        param.stuNo = getUsername();
        return dmsStuDailyService.doCard(param);
    }


    @GetMapping("/getOwnDorm")
    @ApiOperation("查询学生自己的宿舍")
    public AjaxResult getOwnDorm(){
        Map<String,Object> map = dmsStuDailyService.getStuDorm(getUsername());
        if(map==null){
            return AjaxResult.error("未找到宿舍信息");
        }
        return AjaxResult.success(map);
    }


    /**
     * 查询学生宿舍打卡列表
     */
    @PreAuthorize("@ss.hasPermi('dormitory:daily:list')")
    @GetMapping("/list")
    @ApiOperation("查询学生宿舍打卡列表")
    public TableDataInfo list(DmsStuDaily dmsStuDaily)
    {
        startPage();
        List<DmsStuDaily> list = dmsStuDailyService.selectDmsStuDailyList(dmsStuDaily);
        return getDataTable(list);
    }

    /**
     * 导出学生宿舍打卡列表
     */
    @PreAuthorize("@ss.hasPermi('dormitory:daily:export')")
    @Log(title = "学生宿舍打卡", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出学生宿舍打卡列表")
    public void export(HttpServletResponse response, DmsStuDaily dmsStuDaily)
    {
        List<DmsStuDaily> list = dmsStuDailyService.selectDmsStuDailyList(dmsStuDaily);
        ExcelUtil<DmsStuDaily> util = new ExcelUtil<DmsStuDaily>(DmsStuDaily.class);
        util.exportExcel(response, list, "学生宿舍打卡数据");
    }

    /**
     * 获取学生宿舍打卡详细信息
     */
    @PreAuthorize("@ss.hasPermi('dormitory:daily:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取学生宿舍打卡详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(dmsStuDailyService.selectDmsStuDailyById(id));
    }

    /**
     * 新增学生宿舍打卡
     */
    @PreAuthorize("@ss.hasPermi('dormitory:daily:add')")
    @Log(title = "学生宿舍打卡", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation("新增学生宿舍打卡")
    public AjaxResult add(@RequestBody DmsStuDaily dmsStuDaily)
    {
        return toAjax(dmsStuDailyService.insertDmsStuDaily(dmsStuDaily));
    }

    /**
     * 修改学生宿舍打卡
     */
    @PreAuthorize("@ss.hasPermi('dormitory:daily:edit')")
    @Log(title = "学生宿舍打卡", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ApiOperation("修改学生宿舍打卡")
    public AjaxResult edit(@RequestBody DmsStuDaily dmsStuDaily)
    {
        return toAjax(dmsStuDailyService.updateDmsStuDaily(dmsStuDaily));
    }

    /**
     * 删除学生宿舍打卡
     */
    @PreAuthorize("@ss.hasPermi('dormitory:daily:remove')")
    @Log(title = "学生宿舍打卡", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    @ApiOperation("删除学生宿舍打卡")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dmsStuDailyService.deleteDmsStuDailyByIds(ids));
    }


    // 统计已打卡的数据
    @GetMapping("/checkedIn")
    @ApiOperation("统计已打卡的数据")
    public AjaxResult checkedIn(){
        return AjaxResult.success(dmsStuDailyService.checkedIn());
    }
    //统计已打卡的数据
    @GetMapping("/notCheckedIn")
    @ApiOperation("统计已打卡的数据")
    public AjaxResult notCheckedIn(){
        return AjaxResult.success(dmsStuDailyService.notCheckedIn());
    }
    //统计请假离校的人数
    @GetMapping("/leavScholl")
    @ApiOperation("统计请假离校的人数")
    public AjaxResult leavScholl(){
        return AjaxResult.success(dmsStuDailyService.leavScholl());
    }
    //统计去实习的人数
    @GetMapping("/goLesson")
    @ApiOperation("统计请假离校的人数")
    public AjaxResult goLesson(){
        return AjaxResult.success(dmsStuDailyService.goLesson());
    }
    //获取部门
    @GetMapping("/getDeptNames")
    @ApiOperation("获取部门")
    public AjaxResult getDeptNames(){
        return AjaxResult.success(dmsStuDailyService.getDeptNames());
    }
}
