package com.srs.web.controller.comprehensive;


import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.srs.common.annotation.NotNull;
import com.srs.common.core.domain.model.LoginUser;
import com.srs.common.utils.bean.BeanTrimmer;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Vo.CphSearch;
import com.srs.comprehensive.service.ICphStuExtraInfoService;
import com.srs.comprehensive.service.ISrsKnrdApplyService;
import com.srs.comprehensive.service.ISrsStuYearService;
import com.srs.comprehensive.service.ISrsStudentService;
import com.srs.framework.web.service.TokenService;
import com.srs.routine.service.IRtStuDisciplinaryApplicationService;
import com.srs.system.service.ISysPostService;
import com.srs.system.service.ISysRoleService;
import com.srs.web.controller.common.RoleBool;

import io.swagger.annotations.ApiOperation;
import liquibase.pro.packaged.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.web.bind.annotation.*;


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;

/**
 * 困难认定Controller
 *
 * @author srs
 * @date 2024-03-19
 */
@RestController
@RequestMapping("/knrdApply/apply")
public class SrsKnrdApplyController extends BaseController {
    @Autowired
    private ISrsKnrdApplyService srsKnrdApplyService;

    @Autowired
    ISysPostService _postService;
    @Autowired
    private ISrsStuYearService srsStuYearService;
    @Autowired
    private ISysRoleService _roleService;

    @GetMapping("/listJwc")
    @ApiOperation("查询学工下的学生申请的列表")
    public TableDataInfo listJwc(CphSearch param) {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            startPage();
            if (param.getStep() == null) {
                param.setStep("4");
            }
            List<SrsKnrdApply> list = srsKnrdApplyService.listView(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }

    @GetMapping("/listXw")
    @ApiOperation("查询学务下的学生申请的列表")
    public TableDataInfo listXw(CphSearch param) {
//        boolean hasRole = RoleBool.isXw(getUserId(),_postService);
        boolean ejxysj = RoleBool.isEjxysj(getUserId(), _postService);
        if (ejxysj) {
            param.setDeptId(getDeptId());
            startPage();
            if (param.getStep() == null) {
                param.setStep("3");
            }
            param.setUserName(getUsername());
            List<SrsKnrdApply> list = srsKnrdApplyService.listView(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }


    @PostMapping("/countXw")
    @ApiOperation("查询学务下的学生申请的列表")
    public AjaxResult countXw(CphSearch param) {
        boolean ejxysj = RoleBool.isEjxysj(getUserId(), _postService);
        if (ejxysj) {
            param.setDeptId(getDeptId());
            param.setUserName(getUsername());
            List<SrsKnrdApply> list = srsKnrdApplyService.countXw(param);
            return AjaxResult.success(list);
        } else {
            List<String> list = new ArrayList<>();
            return AjaxResult.success(list);
        }
    }

    @GetMapping("/listFdy")
    @ApiOperation("查询辅导员下的学生申请的列表")
    public TableDataInfo listFdy(CphSearch param) {
        boolean hasRole = RoleBool.isFdy(getUserId(), _postService);
        if (hasRole) {
            param.setTNo(getUsername());
            startPage();
            if (param.getStep() == null) {
                param.setStep("2");
            }
            List<SrsKnrdApply> list = srsKnrdApplyService.listView(param);
            return getDataTable(list);
        } else {
            List<String> list = new ArrayList<>();
            return getDataTable(list);
        }
    }


    @GetMapping("/listOwn")
    @ApiOperation("查询学生自己申请的列表")
    public TableDataInfo listOwn(SrsKnrdApply srsKnrdApply) {
        String stuNo = getUsername();
        startPage();
        srsKnrdApply.setXh(stuNo);
        List<SrsKnrdApply> list = srsKnrdApplyService.selectSrsKnrdApplyList(srsKnrdApply);
        return getDataTable(list);
    }


    /**
     * 查询困难认定列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SrsKnrdApply srsKnrdApply) {
        BeanTrimmer.trimFields(srsKnrdApply);
        startPage();
        List<SrsKnrdApply> list = srsKnrdApplyService.selectSrsKnrdApplyList(srsKnrdApply);
        return getDataTable(list);
    }

    /**
     * 导出困难认定列表
     */
    @Log(title = "困难认定", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SrsKnrdApply srsKnrdApply) {
        List<SrsKnrdApply> list = srsKnrdApplyService.selectSrsKnrdApplyList(srsKnrdApply);
        ExcelUtil<SrsKnrdApply> util = new ExcelUtil<SrsKnrdApply>(SrsKnrdApply.class);
        util.exportExcel(response, list, "困难认定数据");
    }

    /**
     * 获取困难认定详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        SrsKnrdApply srsKnrdApply = srsKnrdApplyService.selectSrsKnrdApplyById(id);
        boolean isStu = RoleBool.isStu(getUserId(), _roleService);
        if (isStu) {
            String stuNo = getUsername();
            if (srsKnrdApply.getXh().equals(stuNo)) {
                return success(srsKnrdApply);
            } else {
                return error("无权访问");
            }
        } else {
            return success(srsKnrdApply);
        }


    }

    //获取当前学年
    @PostMapping(value = "/findByXhAndApplyYear")
    public AjaxResult findByXhAndApplyYear(@RequestBody SrsKnrdApply srsKnrdApply) {

        return success(srsKnrdApplyService.selectByXhAndYear(srsKnrdApply));
    }


    @Autowired
    private TokenService tokenService;

    @GetMapping("/xh")
    public AjaxResult getInfoxh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        return success(srsKnrdApplyService.getInfoxh(loginUser.getUser().getUserName()));
    }

    @GetMapping("/getStuByXh")
    public AjaxResult getStuByXh(String xh) {
        SrsStudent infoxh = srsKnrdApplyService.getInfoxh(xh);
        if (infoxh == null) {
            return error("学号错误，没有这个学生");
        }

        return success();
    }

    /**
     * 新增困难认定
     */
    @Log(title = "学生新增困难认定", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SrsKnrdApply srsKnrdApply) {
        BeanTrimmer.trimFields(srsKnrdApply);
        return srsKnrdApplyService.insertSrsKnrdApply(srsKnrdApply);
    }

    /**
     * 修改困难认定
     */
    @Log(title = "困难认定", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@RequestBody SrsKnrdApply srsKnrdApply) {
        SrsKnrdApply result = srsKnrdApplyService.selectSrsKnrdApplyById(srsKnrdApply.getId());
        Long step = result.getStep();
        if (step != 1 && step != 0) { //学生只能看不能操作
            boolean isStudent = RoleBool.isStu(getUserId(), _roleService);
            if (isStudent) {
                return AjaxResult.error("操作失败,权限不足!");
            }
            if (step == 2) {
                boolean isFdy = RoleBool.isFdy(getUserId(), _postService);
                if (!isFdy) {
                    return AjaxResult.error("操作失败,权限不足!");
                }
            }
            if (step == 3) {
                boolean ejxysj = RoleBool.isEjxysj(getUserId(), _postService);
                if (!ejxysj) {
                    return AjaxResult.error("操作失败,权限不足!");
                }
            }
            if (step == 4) {
                boolean isJwc = RoleBool.isJwc(getUserId(), _postService);
                if (!isJwc) {
                    return AjaxResult.error("操作失败,权限不足!");
                }
            }
        }

        BeanTrimmer.trimFields(srsKnrdApply);
        return toAjax(srsKnrdApplyService.updateSrsKnrdApply(srsKnrdApply));
    }

    /**
     * 批量困难认定
     */
    @Log(title = "困难认定", businessType = BusinessType.UPDATE)
    @PostMapping("/updateAllSrsKnrdApply")
    public AjaxResult updateAllSrsKnrdApply(@RequestBody SrsHandAllKnrd srsKnrdApply) {
        return toAjax(srsKnrdApplyService.updateAllSrsKnrdApply(srsKnrdApply));
    }

    /**
     * 删除困难认定
     */
    @Log(title = "困难认定", businessType = BusinessType.DELETE)
    @GetMapping("/delete/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(srsKnrdApplyService.deleteSrsKnrdApplyByIds(ids));
    }

    @Autowired
    private ISrsStudentService srsStudentService;

    @Autowired
    private ICphStuExtraInfoService cphStuExtraInfoService;
    @Autowired
    private IRtStuDisciplinaryApplicationService rtStuDisciplinaryApplicationService;

    //学生基础信息校验
    @PostMapping("/infoCheck")
    public AjaxResult infoCheck() {
        AjaxResult ajaxResult = new AjaxResult();

        String stuNo = getUsername();
        SrsStudent res1 = srsStudentService.getStuInfo(stuNo);
        CphStuExtraInfo res2 = cphStuExtraInfoService.getStuInfo(getUsername());
        try {

            check(res1);
            check(res2);
            if (rtStuDisciplinaryApplicationService.selectRtStuDisciplinaryApplicationByStuNo(stuNo)) {
                Map map = new HashMap<String, String>();
                map.put("code", 1);
                ajaxResult.put("code", 0);
                ajaxResult.put("data", map);
                ajaxResult.put("msg", "你当前处于学校处分状态，不允许申请贫困生条件");
                return ajaxResult;
            }

            ajaxResult.put("code", 200);
            return ajaxResult;
        } catch (Exception e) {
            Map map = new HashMap<String, String>();
            map.put("code", 0);
            map.put("info", e.getMessage());
            ajaxResult.put("code", 0);
            ajaxResult.put("data", map);
            ajaxResult.put("msg", "请先填写完成个人信息中的重要信息和其他信息");
            return ajaxResult;
        }

    }

    public static void check(Object obj) throws Exception {
        //获取所有字段
        final Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            NotNull notNull = field.getAnnotation(NotNull.class);

            String name = field.getName();//字段名
            Type type = field.getGenericType();//字段类型
            if (notNull != null) {

                Class<?> fieldClazz = field.getType();
                Object fieldObj = field.get(obj);
                if (field.get(obj) == null || "".equals(field.get(obj))) {
                    throw new Exception(notNull.value());
                }
//                //是数组
//                if(List.class.isAssignableFrom(fieldClazz)){
//                    List list = (List)fieldObj;
//                    if(list.size()<1){
//                        throw new Exception(name +"不能为空");
//                    }
//                }
            }

        }
    }

    @PostMapping("/valid")
    public AjaxResult valid(@RequestBody SrsKnrdApply apply) {
        AjaxResult ajaxResult = new AjaxResult();
//        SrsKnrdApply srsKnrdApply = new SrsKnrdApply();
        String stuNo = getUsername();
        apply.setXh(stuNo);
//        SrsStuYear srsStuYear = srsStuYearService.listEnableYear().get(0);
//        apply.setStuYearId(srsStuYear.getId());
        SrsKnrdApply vaildResult = srsKnrdApplyService.selectByXhAndYear(apply);
        if (vaildResult == null) {
            ajaxResult.put("valid", 1);
        } else {
            ajaxResult.put("valid", 0);
        }
        return ajaxResult;
    }


    @PostMapping("/fdySave")
    public AjaxResult fdySave(@RequestBody SrsKnrdApply srsKnrdApply) {
        int i = srsKnrdApplyService.fdySave(srsKnrdApply);
        return toAjax(i);
    }


    @PostMapping("/getCurrentYear")
    public AjaxResult getCurrentYear() {
        List<SrsStuYear> srsStuYears = srsStuYearService.listEnableYear();
        return success(srsStuYears.get(0));
    }

    @PostMapping("/reject")
    public AjaxResult reject(@RequestBody SrsKnrdApprovalRecord record) {
        return success(srsKnrdApplyService.reject(record));
    }

    @PostMapping("/jwcNext")
    @ApiOperation("查询学工下的学生申请的列表")
    public AjaxResult jwcNext(CphSearch param) {

        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            startPage();
            if (param.getStep() == null) {
                param.setStep("4");
            }
            List<SrsKnrdApply> list = srsKnrdApplyService.listView(param);
            if (list.size() != 0) {
                SrsKnrdApply srsKnrdApply = list.get(0);
                //锁定
                srsKnrdApplyService.lock(srsKnrdApply);
                return AjaxResult.success(srsKnrdApply);
            } else {
                return AjaxResult.success(null);
            }

        } else {
            return AjaxResult.success(null);
        }
    }

    @PostMapping("/fdyNext")
    @ApiOperation("查询学工下的学生申请的列表")
    public AjaxResult fdyNext(CphSearch param) {
        boolean hasRole = RoleBool.isFdy(getUserId(), _postService);
        if (hasRole) {
            param.setTNo(getUsername());
            startPage();
            if (param.getStep() == null) {
                param.setStep("2");
            }
            List<SrsKnrdApply> list = srsKnrdApplyService.listView(param);
            if (list.size() != 0) {
                return AjaxResult.success(list.get(0));
            } else {
                return AjaxResult.success(null);
            }

        } else {

            return AjaxResult.success(null);
        }
    }

    @PostMapping("/xwNext")
    @ApiOperation("查询学务下的学生申请的列表")
    public AjaxResult xwNext(CphSearch param) {
//        boolean hasRole = RoleBool.isXw(getUserId(),_postService);
        boolean ejxysj = RoleBool.isEjxysj(getUserId(), _postService);
        if (ejxysj) {
            param.setDeptId(getDeptId());
            startPage();
            if (param.getStep() == null) {
                param.setStep("3");
            }
            param.setUserName(getUsername());
            List<SrsKnrdApply> list = srsKnrdApplyService.listView(param);
            if (list.size() != 0) {
                return AjaxResult.success(list.get(0));
            } else {
                return AjaxResult.success(null);
            }
        } else {
            List<String> list = new ArrayList<>();
            return AjaxResult.success(null);
        }
    }

    @PostMapping("/revoke")
    @ApiOperation("困难认定撤回")
    public AjaxResult revoke(@RequestBody SrsKnrdApply srsKnrdApply) {
        int revoke = srsKnrdApplyService.revoke(srsKnrdApply);
        if (revoke > 0) {
            return AjaxResult.success("操作成功！");
        } else {
            return AjaxResult.error("操作失败！");
        }

    }


    @PostMapping("/fdyRevoke")
    @ApiOperation("困难认定超级撤回")
    public AjaxResult fdyRevoke(@RequestBody SrsKnrdApply srsKnrdApply) {
        int revoke = srsKnrdApplyService.fdyRevoke(srsKnrdApply);
        if (revoke > 0) {
            return AjaxResult.success("操作成功！");
        } else {
            return AjaxResult.error("操作失败！");
        }

    }

    @PostMapping("/lock")
    public AjaxResult lock(@RequestBody SrsKnrdApply srsKnrdApply) {
        int lock = srsKnrdApplyService.lock(srsKnrdApply);
        if (lock > 0) {
            return AjaxResult.success("操作成功！");
        } else {
            return AjaxResult.error("操作失败！");
        }

    }

    @PostMapping("/unlock")
    public AjaxResult unlock(@RequestBody SrsKnrdApply srsKnrdApply) {
        int unLock = srsKnrdApplyService.unlock(srsKnrdApply);
        if (unLock > 0) {
            return AjaxResult.success("操作成功！");
        } else {
            return AjaxResult.error("操作失败！");
        }
    }


    //教务处一键审核
    @PostMapping("/jwcUpdateAll")
    @ApiOperation("查询学工下的学生申请的列表")
    public AjaxResult jwcUpdateAll(@RequestBody SrsHandAllKnrd srsKnrdApply) {
        boolean hasRole = RoleBool.isJwc(getUserId(), _postService);
        if (hasRole) {
            CphSearch param = new CphSearch();
            if (param.getStep() == null) {
                param.setStep("4");
            }
            List<SrsKnrdApply> list = srsKnrdApplyService.listView(param);
            int[] ids = new int[list.size()];
            for (int i = 0; i < list.size(); i++) {
                ids[i] = list.get(i).getId().intValue();
            }
            srsKnrdApply.setIds(ids);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String formatDate = format.format(new Date());
            srsKnrdApply.setXsqmrq(formatDate);
            return toAjax(srsKnrdApplyService.updateAllSrsKnrdApply(srsKnrdApply));
        } else {

            return toAjax(0);
        }
    }

    // 更新签名
    @PostMapping("/updateSignature")
    public AjaxResult updateSignature(@RequestBody CphSearch cphSearch) {


        return AjaxResult.success(srsKnrdApplyService.updateSignature(cphSearch));
    }
}

