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.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 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 yangtz.cs.liu.campus.domain.schoolAtt.SchoolAtt;
import yangtz.cs.liu.campus.domain.schoolAtt.SchoolAttEa;
import yangtz.cs.liu.campus.domain.schoolAtt.SchoolAttMon;
import yangtz.cs.liu.campus.domain.schoolAtt.SchoolAttOt;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGrade;
import yangtz.cs.liu.campus.domain.schoolgrade.SchoolGradeMentor;
import yangtz.cs.liu.campus.service.schoolAtt.ISchoolAttEaService;
import yangtz.cs.liu.campus.service.schoolAtt.ISchoolAttMonService;
import yangtz.cs.liu.campus.service.schoolAtt.ISchoolAttOtService;
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 javax.servlet.http.HttpServletResponse;
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;

/**
 * @author xuten
 */
@RestController
@RequestMapping("/schoolAttMon")
public class SchoolAttMonController extends BaseController {

    @Autowired
    private ISchoolAttMonService monService;

    @Autowired
    private ISchoolAttEaService eaService;

    @Autowired
    private ISchoolAttOtService otService;

    @Autowired
    private ISchoolGradeMentorService gradeMentorService;

    @Autowired
    private ISchoolGradeService gradeService;

    public static final String SUBMIT = "1";

    /**
     * 个人工作>月度考勤
     * */
    @GetMapping("/personalList")
    public TableDataInfo personalList(SchoolAttMon schoolAttMon)
    {
        schoolAttMon.setUserId(getUserId());
        startPage();
        List<SchoolAttMon> list = monService.queryList(schoolAttMon);
        return getDataTable(list);
    }

    /**
     * 月度考勤 查看
     * */
    @GetMapping("/getInfo/{attMonId}")
    public AjaxResult getInfo(@PathVariable Long attMonId)
    {
        AjaxResult ajax = AjaxResult.success();
        //获取考勤明细-请假
        List<SchoolAttEa> eaList = eaService.getListByAttMonId(attMonId);
        //获取考勤明细-加班
        List<SchoolAttOt> otList = otService.getListByAttMonId(attMonId);
        ajax.put("eaList",eaList);
        ajax.put("otList",otList);
        return ajax;
    }

    /**
     * 级部工作>月度考勤
     * */
    @GetMapping("/gradeList")
    public TableDataInfo gradeList(SchoolAttMon schoolAttMon)
    {
        //获取当前学年
//        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());
        //本级部下的教工
        schoolAttMon.setUserType(TEACH);
        startPage();
        List<SchoolAttMon> list = monService.queryGradeList(idList,schoolAttMon);
        return getDataTable(list);
    }

    /**
     * 级部工作>月度考勤 导出
     * */
    @PostMapping("/gradeList/export")
    public void exportGrade(HttpServletResponse response, SchoolAttMon schoolAttMon)
    {
        //获取当前学年
//        int schoolYear = HolidayDateUtil.getSchoolYear();
        //获取当前登录人所在级部
        //获取当前登录人所在级部(多个级部)
        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());
        schoolAttMon.setUserType(TEACH);
        List<SchoolAttMon> list = monService.queryGradeList(idList,schoolAttMon);
        ExcelUtil<SchoolAttMon> util = new ExcelUtil<SchoolAttMon>(SchoolAttMon.class);
        util.exportExcel(response, list, "月度考勤数据");
    }

    /**
     * 科室工作>月度考勤
     * */
    @GetMapping("/deptList")
    public TableDataInfo deptList(SchoolAttMon schoolAttMon)
    {
        //获取当前登录人所在科室
        //本级部下的职工
        schoolAttMon.setOrgid(getDeptId());
        schoolAttMon.setUserType(EMPLOYEE);
        startPage();
        List<SchoolAttMon> list = monService.queryList(schoolAttMon);
        return getDataTable(list);
    }

    /**
     * 科室工作>月度考勤 导出
     * */
    @PostMapping("/deptList/export")
    public void exportDept(HttpServletResponse response, SchoolAttMon schoolAttMon)
    {
        schoolAttMon.setOrgid(getDeptId());
        schoolAttMon.setUserType(EMPLOYEE);
        List<SchoolAttMon> list = monService.queryList(schoolAttMon);
        ExcelUtil<SchoolAttMon> util = new ExcelUtil<SchoolAttMon>(SchoolAttMon.class);
        util.exportExcel(response, list, "月度考勤数据");
    }

    /**
     * 导出月度考勤列表
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, SchoolAttMon schoolAttMon)
    {
        List<SchoolAttMon> list = monService.queryList(schoolAttMon);
        ExcelUtil<SchoolAttMon> util = new ExcelUtil<SchoolAttMon>(SchoolAttMon.class);
        util.exportExcel(response, list, "月度考勤数据");
    }

    /**
     * 修改月度考勤
     * 点击修改按钮，对请假和加班进行修改，当修改页面关闭时，发送修改请求，对请假加班时长统计修改
     */
    @PutMapping("/edit/{id}")
    public AjaxResult edit(@PathVariable Long id)
    {
        return toAjax(monService.editById(id));
    }

    /**
     * 单个提交
     * */
    @PutMapping("/submitOne/{id}")
    public AjaxResult submitOne(@PathVariable Long id)
    {
        SchoolAttMon mon = monService.getById(id);
        mon.setState(SUBMIT);
        return toAjax(monService.updateById(mon));
    }

    /**
     * 级部按月批量提交，只提交，当前学年级部的考勤信息
     * */
    @PutMapping("/submitGrade")
    public AjaxResult submitGrade(SchoolAttMon schoolAttMon)
    {
        //判断是否传入要批量提交的年月
        if(StringUtils.isEmpty(schoolAttMon.getAttMon())){
            throw new ServiceException("请选择需要批量提交的月份");
        }
        //获取当前学年
//        int schoolYear = HolidayDateUtil.getSchoolYear();
        // TODO 修改获取最新学年
        int schoolYear = gradeService.isNewSchoolYear();
        List<SchoolGrade> gradeIds = gradeMentorService.selectGrades(getUserId(),schoolYear);
        if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
            //若管理员此时不是级部成员，则查出所有级部
            if(1L == getUserId()){
                LambdaQueryWrapper<SchoolGrade> lqw = new LambdaQueryWrapper<>();
                lqw.eq(SchoolGrade::getSchoolYear,schoolYear)
                .orderByAsc(SchoolGrade::getGradeValue);
                gradeIds = gradeService.list(lqw);
                if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
                    throw new ServiceException(schoolYear+"学年暂无级部信息，查询不出级部下的任何信息");
                }
            }else{
                throw new ServiceException("当前为"+schoolYear+"学年，您不在任何级部工作，无法提交");
            }
        }
        //获取级部id并排重
        List<Long> idList = gradeIds.stream().map(SchoolGrade::getId).distinct().collect(Collectors.toList());
        //本级部下的教工
        schoolAttMon.setUserType(TEACH);
        return toAjax(monService.monthGradeSubmit(idList,schoolAttMon));
    }

    /**
     * 科室按月批量提交
     * */
    @PutMapping("/submitDept")
    public AjaxResult submitDept(SchoolAttMon schoolAttMon)
    {
        //判断是否传入要批量提交的年月
        if(StringUtils.isEmpty(schoolAttMon.getAttMon())){
            throw new ServiceException("请选择需要批量提交的月份");
        }
        //本级部下的教工
        schoolAttMon.setOrgid(getDeptId());
        schoolAttMon.setUserType(EMPLOYEE);
        return toAjax(monService.monthSubmit(schoolAttMon));
    }

    /**
     * 级部按月初始化数据
     * */
    @PutMapping("/initGrade")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult initGrade(SchoolAttMon schoolAttMon) throws Exception {
        //判断是否传入要批量提交的年月
        if(StringUtils.isEmpty(schoolAttMon.getAttMon())){
            throw new ServiceException("请选择需要批量初始化的月份");
        }
        //获取当前学年
//        int schoolYear = HolidayDateUtil.getSchoolYear();
        // TODO 修改最新学年
        int schoolYear = gradeService.isNewSchoolYear();
        List<SchoolGrade> gradeIds = gradeMentorService.selectGrades(getUserId(),schoolYear);
        if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
            //若管理员此时不是级部成员，则查出所有级部
            if(1L == getUserId()){
                LambdaQueryWrapper<SchoolGrade> lqw = new LambdaQueryWrapper<>();
                lqw.eq(SchoolGrade::getSchoolYear,schoolYear)
                        .orderByAsc(SchoolGrade::getGradeValue);
                gradeIds = gradeService.list(lqw);
                if(StringUtils.isNull(gradeIds) || gradeIds.size() == 0){
                    throw new ServiceException(schoolYear+"学年暂无级部信息，查询不出级部下的任何信息");
                }
            }else{
                throw new ServiceException("当前为"+schoolYear+"学年，您不在任何级部工作，无法初始化");
            }
        }
        //获取级部id并排重
        List<Long> idList = gradeIds.stream().map(SchoolGrade::getId).distinct().collect(Collectors.toList());
        //本级部下的教工
        schoolAttMon.setUserType(TEACH);
        return toAjax(monService.monthGradeInit(idList,schoolAttMon));
    }

    /**
     * 科室按月初始化数据
     * */
    @PutMapping("/initDept")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult initDept(SchoolAttMon schoolAttMon) throws Exception {
        //判断是否传入要批量提交的年月
        if(StringUtils.isEmpty(schoolAttMon.getAttMon())){
            throw new ServiceException("请选择需要批量初始化的月份");
        }

        Long deptId = getDeptId();
        //本级部下的教工
        schoolAttMon.setOrgid(deptId);
        schoolAttMon.setUserType(EMPLOYEE);
        return toAjax(monService.monthInit(schoolAttMon));
    }
}
