package com.srs.comprehensive.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.DateUtils;
import com.srs.comprehensive.domain.KnzzTufaApply;
import com.srs.comprehensive.domain.SrsStuYear;
import com.srs.comprehensive.mapper.SrsStuYearMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.mapper.KnzzGlApplyMapper;
import com.srs.comprehensive.domain.KnzzGlApply;
import com.srs.comprehensive.service.IKnzzGlApplyService;

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

/**
 * 国家励志奖学金Service业务层处理
 *
 * @author srs
 * @date 2025-04-26
 */
@Service
public class KnzzGlApplyServiceImpl extends ServiceImpl<KnzzGlApplyMapper,KnzzGlApply> implements IKnzzGlApplyService {
    @Autowired
    private KnzzGlApplyMapper knzzGlApplyMapper;

    @Autowired
    private SrsStuYearMapper _yearMapper;



    @Override
    public AjaxResult doReApply(KnzzGlApply param){
        try{
            KnzzGlApply apply = knzzGlApplyMapper.selectById(param.getId());
            if(apply == null){
                throw new Exception("申请不存在");
            }
            if(!Objects.equals(apply.getStuNo(), getUsername())){
                throw new Exception("只能重新申请自己的申请");
            }
//            if(!Objects.equals(apply.getApplyStatus(), "10")){
//                throw new Exception("申请已处理");
//            }
            UpdateWrapper<KnzzGlApply> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", apply.getId())
                    // 需要重置的审批流程相关字段
                    .set("fdy_cmt", null)
                    .set("fdy_no", null)
                    .set("fdy_date", null)
                    .set("fdy_sign", null)
                    .set("xw_cmt", null)
                    .set("xw_no", null)
                    .set("xw_date", null)
                    .set("xw_sign", null)
                    .set("xg_cmt", null)
                    .set("xg_no", null)
                    .set("xg_date", null)
                    .set("xg_sign", null)
                    // 其它需要更新的字段
                    .set("apply_status", "1")
                    .set("apply_date", getNowDate())
                    .set("update_time", getNowDate())
                    .set("update_by", getUsername())
                    .set("in_time", param.getInTime())
                    .set("family_num", param.familyNum)
                    .set("family_num", param.familyNum)
                    .set("per_money", param.perMoney)
                    .set("money_src", param.moneySrc)
                    .set("major_rank", param.majorRank)
                    .set("major_num", param.majorNum)
                    .set("is_cph", param.isCph)
                    .set("class_rank", param.classRank)
                    .set("class_num", param.classNum)
                    .set("bxk", param.bxk)
                    .set("jg", param.jg)
                    .set("help_his", param.getHelpHis())
                    .set("month_money", param.getMonthMoney())
                    .set("apply_reason", param.getApplyReason())
                    .set("apply_sign", param.getApplySign())
                    .set("hard_file", param.getHardFile());

            int res = knzzGlApplyMapper.update(null, updateWrapper);

            if(res == 0){
                throw new Exception("重新申请失败");
            }

            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult doEdit(KnzzGlApply param) {
        try{
            KnzzGlApply apply = knzzGlApplyMapper.selectById(param.getId());
            if(apply == null){
                throw new Exception("申请不存在");
            }

//            if(!Objects.equals(apply.getStuNo(), getUsername())){
//                throw new Exception("只能修改自己的申请");
//            }

//            if(!Objects.equals(apply.getApplyStatus(), "1")){
//                throw new Exception("申请已处理");
//            }

            apply.inTime = param.inTime;
            apply.helpHis = param.helpHis;
            apply.familyNum = param.familyNum;
            apply.monthMoney = param.monthMoney;
            apply.perMoney = param.perMoney;
            apply.moneySrc = param.moneySrc;
            apply.majorRank = param.majorRank;
            apply.majorNum = param.majorNum;
            apply.isCph = param.isCph;
            apply.classRank = param.classRank;
            apply.classNum = param.classNum;
            apply.bxk = param.bxk;
            apply.jg = param.jg;
            apply.applyReason = param.applyReason;
            apply.hardFile = param.hardFile;
            apply.applySign = param.applySign;
            apply.applyStatus = param.applyStatus ;
            // 困难类型
            apply.hardType = param.hardType;
            // 家庭住址
            apply.homeAddr = param.homeAddr;

            apply.setUpdateTime(getNowDate());
            apply.setUpdateBy(getUsername());

            int res = knzzGlApplyMapper.updateById(apply);
            if(res == 0){
                throw new Exception("修改失败");
            }


            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public List<KnzzGlApply> listView(KnzzGlApply param){
        return knzzGlApplyMapper.listView(param);
    }

    @Override
    public AjaxResult doMany(List<KnzzGlApply> param) {
        try{
            List<KnzzGlApply> updateList = new ArrayList<>();
            param.forEach(x->{
                KnzzGlApply apply = knzzGlApplyMapper.selectById(x.getId());
                if (apply != null){
                    if(Objects.equals(x.applyStatus, "2")){
                        x.fdyNo = getUsername();
                        x.fdyDate = getNowDate();
                    }
                    if(Objects.equals(x.applyStatus, "3")){
                        x.xwNo = getUsername();
                        x.xwDate = getNowDate();
                    }
                    if(Objects.equals(x.applyStatus, "4")){
                        x.xgNo = getUsername();
                        x.xgDate = getNowDate();
                    }
                    if(Objects.equals(x.applyStatus, "10")){
                        if(Objects.equals(apply.applyStatus, "1")){
                            x.fdyNo = getUsername();
                            x.fdyDate = getNowDate();
                        }
                        if(Objects.equals(apply.applyStatus, "2")){
                            x.xwNo = getUsername();
                            x.xwDate = getNowDate();
                        }
                        if(Objects.equals(apply.applyStatus, "3")){
                            x.xgNo = getUsername();
                            x.xgDate = getNowDate();
                        }
                    }
                    x.setUpdateTime(getNowDate());
                    x.setUpdateBy(getUsername());
                    updateList.add(x);
                }
            });
            boolean res = this.updateBatchById(updateList);

            if(!res){
                throw new Exception("批量更新失败");
            }

            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public AjaxResult doAudit(KnzzGlApply param){
        try{
            KnzzGlApply apply = knzzGlApplyMapper.selectById(param.getId());
            if(apply == null){
                throw new Exception("申请不存在");
            }
            if(Objects.equals(param.applyStatus, "2")){
                param.fdyNo = getUsername();
                param.fdyDate = getNowDate();
            }
            if(Objects.equals(param.applyStatus, "3")){
                param.xwNo = getUsername();
                param.xwDate = getNowDate();
            }
            if(Objects.equals(param.applyStatus, "4")){
                param.xgNo = getUsername();
                param.xgDate = getNowDate();
            }

            if(Objects.equals(param.applyStatus, "10")){
                if(Objects.equals(apply.applyStatus, "1")){
                    param.fdyNo = getUsername();
                    param.fdyDate = getNowDate();
                }
                if(Objects.equals(apply.applyStatus, "2")){
                    param.xwNo = getUsername();
                    param.xwDate = getNowDate();
                }
                if(Objects.equals(apply.applyStatus, "3")){
                    param.xgNo = getUsername();
                    param.xgDate = getNowDate();
                }
            }


            param.setUpdateTime(getNowDate());
            param.setUpdateBy(getUsername());
            int res = knzzGlApplyMapper.updateById(param);
            if(res == 0){
                throw new Exception("审核失败");
            }

            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }

    @Override
    public AjaxResult doCancel(Long id){
        try{

            KnzzGlApply apply = knzzGlApplyMapper.selectById(id);
            if(apply == null){
                throw new Exception("申请不存在");
            }
            if(!Objects.equals(apply.getStuNo(), getUsername())){
                throw new Exception("只能取消自己的申请");
            }
            if(!Objects.equals(apply.getApplyStatus(), "1")){
                throw new Exception("申请已处理");
            }
            int res = knzzGlApplyMapper.deleteById(id);
            if(res == 0){
                throw new Exception("取消失败");
            }

            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult doApply(KnzzGlApply param){
        try{
            String stuNo = getUsername();
            param.stuNo = getUsername();
            param.setCreateTime(getNowDate());
            param.setCreateBy(getUsername());
            /*QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
            yearQuery.eq("status","1");
            yearQuery.last("limit 1");
            SrsStuYear year = _yearMapper.selectOne(yearQuery);*/

            /* 此处使用硬编码，请根据实际情况修改。
        当前页面的功能是获取'国家励志奖学金---NLZJ'标签对应的学年信息。
        涉及到学年标签字典module_tag，需要在字典管理中查询对应的信息。
        如果在字典管理更改了 学年标签 的信息，此处也要进行相应修改。
        尽量避免学年标签字典的更改!!!! */
            List<SrsStuYear> yearList = _yearMapper.selectYearsByTag("NLZJ");

            SrsStuYear year = yearList.get(0);
            if(!year.getModuleTags().contains("NLZJ")){
                throw new Exception("当前学年未关联到国家励志奖学金标签!");
            }
            Long yearId = year.getId();

            QueryWrapper<KnzzGlApply> applyQuery = new QueryWrapper<>();
            applyQuery.eq("stu_no",stuNo);
            applyQuery.eq("stu_year_id",yearId);
            List<KnzzGlApply> applyList = knzzGlApplyMapper.selectList(applyQuery);
            if(applyList!= null && !applyList.isEmpty()){
                throw new Exception("当前学年已提交申请");
            }

            param.stuYearId = year.getId();
            param.setApplyDate(getNowDate());
            param.setApplyStatus("1");

            int res = knzzGlApplyMapper.insert(param);
            if(res == 0){
                throw new Exception("提交申请失败");
            }



            return AjaxResult.success();
        }catch (Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    /**
     * 查询国家励志奖学金
     *
     * @param id 国家励志奖学金主键
     * @return 国家励志奖学金
     */
    @Override
    public KnzzGlApply selectKnzzGlApplyById(Long id) {
        return knzzGlApplyMapper.selectKnzzGlApplyById(id);
    }

    /**
     * 查询国家励志奖学金列表
     *
     * @param knzzGlApply 国家励志奖学金
     * @return 国家励志奖学金
     */
    @Override
    public List<KnzzGlApply> selectKnzzGlApplyList(KnzzGlApply knzzGlApply) {
        return knzzGlApplyMapper.selectKnzzGlApplyList(knzzGlApply);
    }

    /**
     * 新增国家励志奖学金
     *
     * @param knzzGlApply 国家励志奖学金
     * @return 结果
     */
    @Override
    public int insertKnzzGlApply(KnzzGlApply knzzGlApply) {
                knzzGlApply.setCreateTime(getNowDate());
            return knzzGlApplyMapper.insertKnzzGlApply(knzzGlApply);
    }

    /**
     * 修改国家励志奖学金
     *
     * @param knzzGlApply 国家励志奖学金
     * @return 结果
     */
    @Override
    public int updateKnzzGlApply(KnzzGlApply knzzGlApply) {
                knzzGlApply.setUpdateTime(getNowDate());
        return knzzGlApplyMapper.updateKnzzGlApply(knzzGlApply);
    }

    /**
     * 批量删除国家励志奖学金
     *
     * @param ids 需要删除的国家励志奖学金主键
     * @return 结果
     */
    @Override
    public int deleteKnzzGlApplyByIds(Long[] ids) {
        return knzzGlApplyMapper.deleteKnzzGlApplyByIds(ids);
    }

    /**
     * 删除国家励志奖学金信息
     *
     * @param id 国家励志奖学金主键
     * @return 结果
     */
    @Override
    public int deleteKnzzGlApplyById(Long id) {
        return knzzGlApplyMapper.deleteKnzzGlApplyById(id);
    }
}
