package yangtz.cs.liu.campus.controller.schoolAtt;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.core.utils.HolidayDateUtil;
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.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import yangtz.cs.liu.campus.domain.area.SchoolArea;
import yangtz.cs.liu.campus.domain.schoolAtt.SchoolAtt;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGradeMentor;
import yangtz.cs.liu.campus.service.schoolAtt.ISchoolAttService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeMentorService;
import yangtz.cs.liu.campus.service.schoolgrade.ISchoolGradeService;
import yangtz.cs.liu.campus.vo.schoolAtt.SchoolAttVO;
import yangtz.cs.liu.campus.vo.student.SchoolStudentVO;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

import static yangtz.cs.liu.campus.constant.EmployeeType.EMPLOYEE;
import static yangtz.cs.liu.campus.constant.EmployeeType.TEACH;

/**
 * 打卡记录Controller
 *
 * @author ruoyi
 * @date 2022-12-25
 */
@RestController
@RequestMapping("/schoolAtt")
public class SchoolAttController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISchoolAttService schoolAttService;

    @Autowired
    private ISchoolGradeMentorService gradeMentorService;

    @Autowired
    private ISchoolGradeService gradeService;

    /**
     * 校园管理>打卡记录，查询打卡记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SchoolAtt schoolAtt) {
        List<SchoolAttVO> list = schoolAttService.queryList(schoolAtt);
        return getDataTable(list);
    }

    /**
     * 个人工作>打卡记录，查询打卡记录列表(个人记录)
     */
    @GetMapping("/personalList")
    public TableDataInfo personalList(SchoolAtt schoolAtt) {
        schoolAtt.setUserId(getUserId());
        List<SchoolAttVO> list = schoolAttService.queryList(schoolAtt);
        return getDataTable(list);
    }

    /**
     * 个人工作>打卡记录，导出
     */
    @PostMapping("/personalList/export")
    public void personalListExport(SchoolAtt schoolAtt, HttpServletResponse response) {
        schoolAtt.setUserId(getUserId());
        List<SchoolAttVO> list = schoolAttService.export(schoolAtt);
        ExcelUtil<SchoolAttVO> util = new ExcelUtil<SchoolAttVO>(SchoolAttVO.class);
        util.exportExcel(response, list, "个人打卡记录列表");
    }


    /**
     * 级部工作>考勤管理>打卡记录，查询打卡记录列表（当前登录人所在级部）
     */
    @GetMapping("/gradeList")
    public TableDataInfo gradeList(SchoolAtt schoolAtt) {
        //获取当前登录人所在级部
        //获取当前学年
        int schoolYear = HolidayDateUtil.getSchoolYear();
        //List<SchoolGrade> gradeIds = gradeMentorService.selectGrades(getUserId(),schoolYear);
        List<SchoolGrade> gradeIds = gradeMentorService.selectGradeList(getUserId());
        if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
            //若管理员此时不是级部成员，则查出所有级部
            if(1L == getUserId()){
                LambdaQueryWrapper<SchoolGrade> lqw = new LambdaQueryWrapper<>();
                lqw.orderByAsc(SchoolGrade::getGradeValue);
                gradeIds = gradeService.list(lqw);
                if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
                    throw new ServiceException("暂无级部信息，查询不出级部下的任何信息");
                }
            }else{
                throw new ServiceException("您不在任何级部工作，无法查看级部下的任何信息");
            }
        }
        //获取级部id并排重
        List<Long> idList = gradeIds.stream().map(SchoolGrade::getId).distinct().collect(Collectors.toList());

        //设置查询条件，级部id，类型为教工
        //schoolAtt.setOrgid(mentor.get(0).getGradeId());
        schoolAtt.setUserType(TEACH);
        List<SchoolAttVO> list = schoolAttService.queryGradeList(idList,schoolAtt);
        return getDataTable(list);
    }

    /**
     * 级部工作>打卡记录，导出
     */
    @PostMapping("/gradeList/export")
    public void gradeListExport(SchoolAtt schoolAtt, HttpServletResponse response) {
        //获取当前学年
        int schoolYear = HolidayDateUtil.getSchoolYear();
        /*List<SchoolGrade> gradeIds = gradeMentorService.selectGrades(getUserId(),schoolYear);
        if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
            throw new ServiceException("非级部成员，无法查看");
        }*/
        List<SchoolGrade> gradeIds = gradeMentorService.selectGradeList(getUserId());
        if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
            //若管理员此时不是级部成员，则查出所有级部
            if(1L == getUserId()){
                LambdaQueryWrapper<SchoolGrade> lqw = new LambdaQueryWrapper<>();
                lqw.orderByAsc(SchoolGrade::getGradeValue);
                gradeIds = gradeService.list(lqw);
                if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
                    throw new ServiceException("暂无级部信息，查询不出级部下的任何信息");
                }
            }else{
                throw new ServiceException("您不在任何级部工作，无法查看级部下的任何信息");
            }
        }
        //获取级部id并排重
        List<Long> idList = gradeIds.stream().map(SchoolGrade::getId).distinct().collect(Collectors.toList());

        //设置查询条件，级部id，类型为教工
        //schoolAtt.setOrgid(mentor.get(0).getGradeId());
        schoolAtt.setUserType(TEACH);
        List<SchoolAttVO> list = schoolAttService.exportGrade(idList,schoolAtt);
        ExcelUtil<SchoolAttVO> util = new ExcelUtil<SchoolAttVO>(SchoolAttVO.class);
        util.exportExcel(response, list, "打卡记录列表");
    }

    /**
     * 科室工作>预算填报>考勤管理>打卡记录，查询打卡记录列表（当前登录人所在科室）
     */
    @GetMapping("/deptList")
    public TableDataInfo deptList(SchoolAtt schoolAtt) {
        //获取当前登录人所在科室
        //SysUser user = userService.selectUserById(getUserId());
        //设置查询条件，部门id，类型为职工
        schoolAtt.setOrgid(getDeptId());
        schoolAtt.setUserType(EMPLOYEE);
        List<SchoolAttVO> list = schoolAttService.queryList(schoolAtt);
        return getDataTable(list);
    }

    /**
     * 科室工作>打卡记录，导出
     */
    @PostMapping("/deptList/export")
    public void deptListExport(SchoolAtt schoolAtt, HttpServletResponse response) {
        schoolAtt.setOrgid(getDeptId());
        schoolAtt.setUserType(EMPLOYEE);
        List<SchoolAttVO> list = schoolAttService.export(schoolAtt);
        ExcelUtil<SchoolAttVO> util = new ExcelUtil<SchoolAttVO>(SchoolAttVO.class);
        util.exportExcel(response, list, "个人打卡记录列表");
    }

    /**
     * 校园管理>打卡记录，删除
     * 传行数据，因为合并数据后没有id
     */
    @DeleteMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult delete(@RequestBody SchoolAttVO attVO) {
        LambdaQueryWrapper<SchoolAtt> lqw = new LambdaQueryWrapper<>();
        lqw
                .eq(SchoolAtt::getDeviceNum, attVO.getDeviceNum())
                .eq(SchoolAtt::getTeacherCode, attVO.getTeacherCode())
                .eq(SchoolAtt::getClockDate, attVO.getClockDate())
        ;
        return toAjax(schoolAttService.remove(lqw));
    }

    /**
     * 导出
     */
    @PostMapping("/export")
    public void export(SchoolAtt schoolAtt, HttpServletResponse response) throws IOException {
        List<SchoolAttVO> list = schoolAttService.export(schoolAtt);
        ExcelUtil<SchoolAttVO> util = new ExcelUtil<SchoolAttVO>(SchoolAttVO.class);
        util.exportExcel(response, list, "打卡记录列表");
    }

    /**
     * 模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SchoolAttVO> util = new ExcelUtil<SchoolAttVO>(SchoolAttVO.class);
        util.importTemplateExcel(response, "打卡记录模板");
    }

    /**
     * 校园管理>打卡记录，导入
     */
    @PostMapping("/importData")
    public AjaxResult importStudent(MultipartFile file) throws Exception {
        ExcelUtil<SchoolAttVO> util = new ExcelUtil<SchoolAttVO>(SchoolAttVO.class);
        List<SchoolAttVO> list = util.importExcel(file.getInputStream());
        //先校验
        schoolAttService.checkImport(list);
        //处理数据
        List<SchoolAtt> attList = schoolAttService.dealData(list);
        //数据导入
        String message = schoolAttService.importData(attList);
        return AjaxResult.success(message);

    }

  /**
   * 个人工作-编辑备注
   * */
    @PutMapping("/editRemark")
    public AjaxResult editRemark(@RequestBody SchoolAttVO vo) {
        return toAjax(schoolAttService.editRemark(vo));
    }

}
