package com.srs.web.controller.workstudy;

import com.srs.common.annotation.Log;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysDept;
import com.srs.common.core.page.TableDataInfo;
import com.srs.common.enums.BusinessType;
import com.srs.common.utils.poi.ExcelUtil;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.service.ISrsStudentService;
import com.srs.system.service.ISysDeptService;
import com.srs.system.service.ISysRoleService;
import com.srs.web.controller.common.RoleBool;
import com.srs.workstudy.domain.QgzxMoney;
import com.srs.workstudy.domain.QgzxMoneyExtra;
import com.srs.workstudy.domain.QgzxStuPost;
import com.srs.workstudy.domain.dto.ManyMoney;
import com.srs.workstudy.domain.vo.DeptPostCount;
import com.srs.workstudy.service.IQgzxMoneyExtraService;
import com.srs.workstudy.service.IQgzxMoneyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.srs.common.utils.DateUtils.getNowDate;

/**
 * 勤工助学薪资填报Controller
 *
 * @author srs
 * @date 2024-06-11
 */
@RestController
@RequestMapping("/workstudy/money")
@Api(value = "勤工助学薪资填报管理", tags = "勤工助学薪资填报管理")
public class QgzxMoneyController extends BaseController {
    @Autowired
    private IQgzxMoneyService qgzxMoneyService;

    @Autowired
    private IQgzxMoneyExtraService _moneyExtraService;

    @Autowired
    private ISysRoleService _roleService;

    @Autowired
    public ISysDeptService _deptService;

    @Autowired
    public ISrsStudentService _studentService;

    @PostMapping("/editMonth")
    @ApiOperation("资助办领导添加")
    public AjaxResult editMonth(@RequestBody QgzxMoney param){
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.editMonth(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @GetMapping("/listTeacherCanSelectPostAndMonthTime")
    @ApiOperation("列出指导老师通过审核并且在岗的记录和月工时")
    public TableDataInfo listTeacherCanSelectPostAndMonthTime(QgzxStuPost param) {
        param.setZdlsNo(getUsername());
        param.applyStatus = "4";
        param.workStatus = "是";
        startPage();
        List<QgzxStuPost> list = qgzxMoneyService.listTeacherCanSelectPostAndMonthTime(param);
        return getDataTable(list);
    }

    @GetMapping("/computeMonthTime")
    @ApiOperation("计算月份工作时间")
    public AjaxResult computeMonthTime(QgzxMoney param){
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            Map<String, Object> result = qgzxMoneyService.computeMonthTime(param);
            return AjaxResult.success(result);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @GetMapping("/getStuNameByStuNo/{stuNo}")
    @ApiOperation("通过学号获取学生姓名")
    public AjaxResult getStuNameByStuNo(@PathVariable String stuNo) {
        SrsStudent srsStudent = _studentService.selectSrsStudentByStuNo(stuNo);
        if (srsStudent == null) {
            return AjaxResult.error("未找到该学生");
        }else{
            SrsStudent s = new SrsStudent();
            s.setName(srsStudent.getName());
            return AjaxResult.success(s);
        }
    }


    @PostMapping("/addMoneyExtra")
    @ApiOperation("资助办领导添加")
    public AjaxResult addMoneyExtra(@RequestBody QgzxMoneyExtra param){
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return _moneyExtraService.addMoneyExtra(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @PostMapping("/delMoneyExtra/{id}")
    @ApiOperation("删除资助办领导添加")
    public AjaxResult delMoneyExtra(@PathVariable Long id) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return _moneyExtraService.delMoneyExtra(id);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @PostMapping("/editPostTypeMoney")
    @ApiOperation("修改学生工时(同时需要修改岗位类型)")
    public AjaxResult editPostTypeMoney(@RequestBody QgzxMoney param){
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.editPostTypeMoney(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @PostMapping("/zzbOneClickAudit")
    @ApiOperation("资助办一键全部审核通过")
    public AjaxResult zzbOneClickAudit(){
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.zzbOneClickAudit();
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @PostMapping("/oneClickAudit")
    @ApiOperation("一键全部审核通过")
    public AjaxResult oneClickAudit(){
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.oneClickAudit();
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @PostMapping("/zzbldEdit")
    @ApiOperation("资助办领导修改")
    public AjaxResult zzbldEdit(@RequestBody QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.zzbldEdit(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @PostMapping("/zzbldAdd")
    @ApiOperation("资助办领导添加")
    public AjaxResult zzbldAdd(@RequestBody QgzxMoney param){
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.zzbldAdd(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }



    @GetMapping("/listCount")
    @ApiOperation("查询统计")
    public AjaxResult listCount() {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            List<DeptPostCount> data = qgzxMoneyService.listCount();
            return AjaxResult.success(data);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @PostMapping("/finalDeptAuditUnPass")
    @ApiOperation("学工批量部门审核拒绝")
    public AjaxResult finalDeptAuditUnPass(@RequestBody List<String> deptCodes) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.finalDeptAudit(deptCodes, "10");
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @PostMapping("/finalDeptAuditPass")
    @ApiOperation("学工批量部门审核通过")
    public AjaxResult finalDeptAuditPass(@RequestBody List<String> deptCodes) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.finalDeptAudit(deptCodes, "6");
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @PostMapping("/highDeptAuditUnPass")
    @ApiOperation("资助办批量部门审核拒绝")
    public AjaxResult highDeptAuditUnPass(@RequestBody List<String> deptCodes) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.highDeptAudit(deptCodes, "10");
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @PostMapping("/highDeptAuditPass")
    @ApiOperation("资助办批量部门审核通过")
    public AjaxResult highDeptAuditPass(@RequestBody List<String> deptCodes) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.highDeptAudit(deptCodes, "3");
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @GetMapping("/listFinalAuditByDept")
    @ApiOperation("列出 按照部门进行 学工审核")
    public AjaxResult listFinalAuditByDept() {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            QgzxMoney param = new QgzxMoney();
            param.applyStatus = "3";
            List<DeptPostCount> res = qgzxMoneyService.listAuditByDept(param);
            return AjaxResult.success(res);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/listHighAuditByDept")
    @ApiOperation("列出 按照部门进行 资助办审核")
    public AjaxResult listHighAuditByDept() {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            QgzxMoney param = new QgzxMoney();
            param.applyStatus = "2";
            List<DeptPostCount> res = qgzxMoneyService.listAuditByDept(param);
            return AjaxResult.success(res);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @PostMapping("/doMany")
    @ApiOperation("批量填报")
    public AjaxResult doMany(@RequestBody ManyMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.doMany(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @GetMapping("/countUnMoney")
    @ApiOperation("查看勤工助学薪资未填报数量")
    public AjaxResult countUnMoney() {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            QgzxMoney param = new QgzxMoney();
            param.applyNo = getUsername();
            param.applyTime = getNowDate();
            Map<String, Object> data = qgzxMoneyService.countUnMoney(param);
            return AjaxResult.success(data);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @PostMapping("/deptExport")
    @ApiOperation("部门导出勤工助学薪资填报列表")
    public void deptExport(HttpServletResponse response, QgzxMoney qgzxMoney) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            qgzxMoney.applyStatus = "6";
            qgzxMoney.deptId = getDeptId();
            List<QgzxMoney> list = qgzxMoneyService.listView(qgzxMoney);

            int i = 1;
            BigDecimal allMoney = new BigDecimal(0);
            for (QgzxMoney x : list) {
                x.rankNum = i;
                i++;
                if(Objects.equals(x.postType, "固定岗位A")){
                    x.totalTimeExport = x.totalTime.setScale(1, RoundingMode.HALF_UP).toString()+"天";
                    x.totalMoney = new BigDecimal("1990").divide(new BigDecimal(qgzxMoney.workdayCount),2, BigDecimal.ROUND_HALF_UP).multiply(x.totalTime).setScale(0, RoundingMode.HALF_UP);
                    int result = x.totalMoney.compareTo(new BigDecimal("1990"));
                    if (result < 0) {
                    } else if (result == 0) {
                    } else {
                        x.totalMoney = new BigDecimal("1990");
                    }
                }else{
                    x.totalTimeExport = x.totalTime.setScale(1, RoundingMode.HALF_UP).toString()+"小时";
                    x.totalMoney = x.totalTime.setScale(1, RoundingMode.HALF_UP).multiply(new BigDecimal(15)).setScale(1, RoundingMode.HALF_UP);
                }
                allMoney = allMoney.add(x.totalMoney);
            }

            SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月");
            String dateStr = sf.format(qgzxMoney.applyTime);

            String firstTitle = dateStr + "学生勤工助学考勤、考核表";
            Set<String> depts = list.stream().map(x -> x.deptName).collect(Collectors.toSet());
            String secondTitle = "用人部门:" + String.join("、", depts);

            ExcelUtil<QgzxMoney> util = new ExcelUtil<QgzxMoney>(QgzxMoney.class);
            util.exportExcelHasSecondTitle(response, list, "勤工助学薪资数据", firstTitle, secondTitle,allMoney.toString());
        }
    }

    @PostMapping("/doExport")
    @ApiOperation("导出勤工助学薪资填报列表")
    public void doExport(HttpServletResponse response, QgzxMoney qgzxMoney) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            qgzxMoney.applyStatus = "6";
            List<QgzxMoney> list = qgzxMoneyService.listView(qgzxMoney);

            int i = 1;
            BigDecimal allMoney = new BigDecimal(0);
            for (QgzxMoney x : list) {
                x.rankNum = i;
                i++;
                if(Objects.equals(x.postType, "固定岗位A")){
                    x.totalTimeExport = x.totalTime.setScale(1, RoundingMode.HALF_UP).toString()+"天";
                    x.totalMoney = new BigDecimal("1990").divide(new BigDecimal(qgzxMoney.workdayCount),2, BigDecimal.ROUND_HALF_UP).multiply(x.totalTime).setScale(0, RoundingMode.HALF_UP);
                    int result = x.totalMoney.compareTo(new BigDecimal("1990"));
                    if (result < 0) {
                    } else if (result == 0) {
                    } else {
                        x.totalMoney = new BigDecimal("1990");
                    }
                }else{
                    x.totalTimeExport = x.totalTime.setScale(1, RoundingMode.HALF_UP).toString()+"小时";
                    x.totalMoney = x.totalTime.setScale(1, RoundingMode.HALF_UP).multiply(new BigDecimal(15)).setScale(1, RoundingMode.HALF_UP);
                }
                allMoney = allMoney.add(x.totalMoney);
            }

            SimpleDateFormat sf = new SimpleDateFormat("yyyy年MM月");
            String dateStr = sf.format(qgzxMoney.applyTime);

            String firstTitle = "梧州职业学院"+ dateStr + " 学生勤工助学岗位考勤、考核表";
            Set<String> depts = list.stream().map(x -> x.deptName).collect(Collectors.toSet());
            String secondTitle = "用工部门:" + String.join("、", depts);

            ExcelUtil<QgzxMoney> util = new ExcelUtil<QgzxMoney>(QgzxMoney.class);
            util.exportExcelHasSecondTitle(response, list, "勤工助学薪资数据", firstTitle, secondTitle,allMoney.toString());
        }
    }


    @GetMapping("/listStu")
    @ApiOperation("查询部门的勤工助学岗位申请列表")
    public TableDataInfo listStu(QgzxMoney param) {
        param.stuNo = getUsername();
        startPage();
        List<QgzxMoney> list = qgzxMoneyService.listView(param);
        return getDataTable(list);
    }


    @PostMapping("/manyAudit")
    @ApiOperation("批量审核勤工助学岗位薪资")
    public AjaxResult manyAudit(@RequestBody List<QgzxMoney> param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.manyAudit(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @PostMapping("/doAudit")
    @ApiOperation("审核勤工助学岗位薪资")
    public AjaxResult doAudit(@RequestBody QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.doAudit(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }

    @GetMapping("/listFinal")
    @ApiOperation("查询资助办领导的勤工助学岗位申请列表")
    public TableDataInfo listFinal(QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            param.applyStatus = "3";
            startPage();
            List<QgzxMoney> list = qgzxMoneyService.listView(param);
            return getDataTable(list);
        } else {
            return getDataTable(new ArrayList<>());
        }
    }

    @GetMapping("/listAll")
    @ApiOperation("查询部门的勤工助学岗位申请列表")
    public TableDataInfo listAll(QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            startPage();
            List<QgzxMoney> list = qgzxMoneyService.listView(param);
            return getDataTable(list);
        } else {
            return getDataTable(new ArrayList<>());
        }
    }


    @GetMapping("/listHigh")
    @ApiOperation("查询资助办公室的勤工助学岗位申请列表")
    public TableDataInfo listHigh(QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            param.applyStatus = "2";
            startPage();
            List<QgzxMoney> list = qgzxMoneyService.listView(param);
            return getDataTable(list);
        } else {
            return getDataTable(new ArrayList<>());
        }
    }


    @GetMapping("/checkDeptAll")
    @ApiOperation("检查部门是否全部岗位都上报")
    public AjaxResult checkDeptAll(QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            SysDept dept = _deptService.selectDeptById(getDeptId());
            if (dept == null) {
                return AjaxResult.error("您未绑定部门");
            }
            param.deptName = dept.getDeptName();
            return qgzxMoneyService.checkDeptAll(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @GetMapping("/listDeptAll")
    @ApiOperation("查询部门的勤工助学岗位申请列表")
    public TableDataInfo listDeptAll(QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            SysDept dept = _deptService.selectDeptById(getDeptId());
            if (dept == null) {
                return getDataTable(new ArrayList<>());
            }
            param.deptName = dept.getDeptName();
            startPage();
            List<QgzxMoney> list = qgzxMoneyService.listView(param);
            return getDataTable(list);
        } else {
            return getDataTable(new ArrayList<>());
        }
    }


    @GetMapping("/listDept")
    @ApiOperation("查询部门的勤工助学岗位申请列表")
    public TableDataInfo listDept(QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            SysDept dept = _deptService.selectDeptById(getDeptId());
            if (dept == null) {
                return getDataTable(new ArrayList<>());
            }
            param.deptName = dept.getDeptName();
            param.applyStatus = "1";
            startPage();
            List<QgzxMoney> list = qgzxMoneyService.listView(param);
            return getDataTable(list);
        } else {
            return getDataTable(new ArrayList<>());
        }
    }

    @PostMapping("/cancelApply/{id}")
    @ApiOperation("学生取消申请")
    public AjaxResult cancelApply(@PathVariable Long id) {
        return qgzxMoneyService.cancelApply(id);
    }

    @GetMapping("/listOwnApply")
    @ApiOperation("指导老师查看申请")
    public TableDataInfo listOwnApply(QgzxMoney param) {
        param.applyNo = getUsername();
        startPage();
        List<QgzxMoney> list = qgzxMoneyService.listView(param);
        return getDataTable(list);
    }


    @PostMapping("/doReply")
    @ApiOperation("指导老师重新申请")
    public AjaxResult doReply(@RequestBody QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.doReply(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    @PostMapping("/doApply")
    @ApiOperation("指导老师申请")
    public AjaxResult doApply(@RequestBody QgzxMoney param) {
        boolean hasRole = RoleBool.notStu(getUserId(), _roleService);
        if (hasRole) {
            return qgzxMoneyService.doApply(param);
        } else {
            return AjaxResult.error(401, "你无权做这些");
        }
    }


    /**
     * 查询勤工助学薪资填报列表
     */
    @PreAuthorize("@ss.hasPermi('workstudy:money:list')")
    @GetMapping("/list")
    @ApiOperation("查询勤工助学薪资填报列表")
    public TableDataInfo list(QgzxMoney qgzxMoney) {
        startPage();
        List<QgzxMoney> list = qgzxMoneyService.selectQgzxMoneyList(qgzxMoney);
        return getDataTable(list);
    }

    /**
     * 导出勤工助学薪资填报列表
     */
    @PreAuthorize("@ss.hasPermi('workstudy:money:export')")
    @Log(title = "勤工助学薪资填报", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出勤工助学薪资填报列表")
    public void export(HttpServletResponse response, QgzxMoney qgzxMoney) {
        List<QgzxMoney> list = qgzxMoneyService.selectQgzxMoneyList(qgzxMoney);
        ExcelUtil<QgzxMoney> util = new ExcelUtil<QgzxMoney>(QgzxMoney.class);
        util.exportExcel(response, list, "勤工助学薪资填报数据");
    }

    /**
     * 获取勤工助学薪资填报详细信息
     */
    @PreAuthorize("@ss.hasPermi('workstudy:money:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation("获取勤工助学薪资填报详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(qgzxMoneyService.selectQgzxMoneyById(id));
    }

    /**
     * 新增勤工助学薪资填报
     */
    @PreAuthorize("@ss.hasPermi('workstudy:money:add')")
    @Log(title = "勤工助学薪资填报", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ApiOperation("新增勤工助学薪资填报")
    public AjaxResult add(@RequestBody QgzxMoney qgzxMoney) {
        return toAjax(qgzxMoneyService.insertQgzxMoney(qgzxMoney));
    }

    /**
     * 修改勤工助学薪资填报
     */
    @PreAuthorize("@ss.hasPermi('workstudy:money:edit')")
    @Log(title = "勤工助学薪资填报", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    @ApiOperation("修改勤工助学薪资填报")
    public AjaxResult edit(@RequestBody QgzxMoney qgzxMoney) {
        return toAjax(qgzxMoneyService.updateQgzxMoney(qgzxMoney));
    }

    /**
     * 删除勤工助学薪资填报
     */
    @PreAuthorize("@ss.hasPermi('workstudy:money:remove')")
    @Log(title = "勤工助学薪资填报", businessType = BusinessType.DELETE)
    @PostMapping("/{ids}")
    @ApiOperation("删除勤工助学薪资填报")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(qgzxMoneyService.deleteQgzxMoneyByIds(ids));
    }
}
