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.comprehensive.domain.*;
import com.srs.comprehensive.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.service.IKnzzTufaApplyService;

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

/**
 * 学生突发困难资助申请Service业务层处理
 *
 * @author zhy
 * @date 2025-04-09
 */
@Service
public class KnzzTufaApplyServiceImpl extends ServiceImpl<KnzzTufaApplyMapper,KnzzTufaApply> implements IKnzzTufaApplyService {
    @Autowired
    private KnzzTufaApplyMapper knzzTufaApplyMapper;

    @Autowired
    private SrsKnrdApplyMapper _knrdApplyMapper;

    @Autowired
    private CphFamilyMemberMapper _cphFamilyMember;

    @Autowired
    private SrsStuYearMapper _yearMapper;
    @Autowired
    private SrsStuYearMapper srsStuYearMapper;

    @Override
    public AjaxResult doReApply(KnzzTufaApply param){
        try{
            KnzzTufaApply apply = knzzTufaApplyMapper.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<KnzzTufaApply> 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("dept_cmt", null)
                    .set("dept_no", null)
                    .set("dept_date", null)
                    .set("dept_sign", null)
                    .set("xg_cmt", null)
                    .set("xg_no", null)
                    .set("xg_date", null)
                    .set("xg_sign", null)
                    .set("leader_cmt", null)
                    .set("leader_no", null)
                    .set("leader_date", null)
                    .set("leader_sign", null)
                    // 其它需要更新的字段
                    .set("apply_status", "1")
                    .set("apply_date", getNowDate())
                    .set("update_time", getNowDate())
                    .set("update_by", getUsername())
                    .set("help_his", param.getHelpHis())
                    .set("year_money", param.getYearMoney())
                    .set("month_money", param.getMonthMoney())
                    .set("money_source", param.getMoneySource())
                    .set("apply_reason", param.getApplyReason())
                    .set("apply_sign", param.getApplySign())
                    .set("hard_file", param.getHardFile());

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

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

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


    @Override
    public AjaxResult doMany(List<KnzzTufaApply> param) {
        try{
            List<KnzzTufaApply> updateList = new ArrayList<>();
            param.forEach(x->{
                KnzzTufaApply apply = knzzTufaApplyMapper.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.deptCmt = apply.fdyCmt;
                        x.deptNo = getUsername();
                        x.deptDate = getNowDate();
                    }
                    if(Objects.equals(x.applyStatus, "4")){
                        x.xgCmt = apply.fdyCmt;
                        x.xgNo = getUsername();
                        x.xgDate = getNowDate();
                    }
                    if(Objects.equals(x.applyStatus, "5")){
                        x.leaderCmt = apply.fdyCmt;
                        x.leaderNo = getUsername();
                        x.leaderDate = 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.deptNo = getUsername();
                            x.deptDate = getNowDate();
                        }
                        if(Objects.equals(apply.applyStatus, "3")){
                            x.xgNo = getUsername();
                            x.xgDate = getNowDate();
                        }
                        if(Objects.equals(apply.applyStatus, "4")){
                            x.leaderNo = getUsername();
                            x.leaderDate = 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(KnzzTufaApply param){
        try{
            KnzzTufaApply apply = knzzTufaApplyMapper.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.deptNo = getUsername();
                param.deptDate = getNowDate();
            }
            if(Objects.equals(param.applyStatus, "4")){
                param.xgNo = getUsername();
                param.xgDate = getNowDate();
            }
            if(Objects.equals(param.applyStatus, "5")){
                param.leaderNo = getUsername();
                param.leaderDate = 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.deptNo = getUsername();
                    param.deptDate = getNowDate();
                }
                if(Objects.equals(apply.applyStatus, "3")){
                    param.deptNo = getUsername();
                    param.deptDate = getNowDate();
                }
                if(Objects.equals(apply.applyStatus, "4")){
                    param.xgNo = getUsername();
                    param.xgDate = getNowDate();
                }
            }

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

            int res = knzzTufaApplyMapper.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{

            KnzzTufaApply apply = knzzTufaApplyMapper.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 = knzzTufaApplyMapper.deleteById(id);
            if(res == 0){
                throw new Exception("取消失败");
            }

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


    @Override
    public AjaxResult doEdit(KnzzTufaApply param){
        try{
            KnzzTufaApply apply = knzzTufaApplyMapper.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.helpHis = param.helpHis;
            apply.yearMoney = param.yearMoney;
            apply.monthMoney = param.monthMoney;
            apply.moneySource = param.moneySource;
            apply.applyReason = param.applyReason;
            apply.applySign = param.applySign;
            apply.hardFile = param.hardFile;
            apply.bankCard = param.bankCard;
            apply.jthk = param.jthk;
            apply.hardCondition = param.hardCondition;
            apply.familyAddr = param.familyAddr;
            apply.postCode = param.postCode;
            // 家庭成员列表不在辅导员修改范围，保留原值
            if (param.applyStatus != null && !param.applyStatus.isEmpty()) {
                apply.applyStatus = param.applyStatus;
            }

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

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

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


    @Override
    public List<KnzzTufaApply> listView(KnzzTufaApply param){
        return knzzTufaApplyMapper.listView(param);
    }



    @Override
    public AjaxResult doApply(KnzzTufaApply param){
        try{
            String stuNo = getUsername();

            /*QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
            yearQuery.eq("status","1");
            yearQuery.last("limit 1");
            SrsStuYear year = _yearMapper.selectOne(yearQuery);*/

            /* 此处使用硬编码，请根据实际情况修改。
        当前页面的功能是获取'学生特殊困难资助---TSKN'标签对应的学年信息。
        涉及到学年标签字典module_tag，需要在字典管理中查询对应的信息。
        如果在字典管理更改了 学年标签 的信息，此处也要进行相应修改。
        尽量避免学年标签字典的更改!!!!*/
            List<SrsStuYear> yearList = srsStuYearMapper.selectYearsByTag("TSKN");// 此处使用硬编码，请根据实际情况修改。
            SrsStuYear year = yearList.get(0);

            if(!year.getModuleTags().contains("TSKN")){
                throw new Exception("当前学年未关联到学生特殊困难资助标签!");
            }

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

            param.setStuYearId(year.getId());
            param.setStuNo(stuNo);
            param.setApplyDate(getNowDate());
            param.setApplyStatus("1");

            param.setCreateBy(getUsername());
            param.setCreateTime(getNowDate());

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

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


    @Override
    public AjaxResult getOwnFamily(){
        try{
            QueryWrapper<CphFamilyMember> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("stu_no",getUsername());
            List<CphFamilyMember> cphFamilyMemberList = _cphFamilyMember.selectList(queryWrapper);
            return AjaxResult.success(cphFamilyMemberList);
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }



    @Override
    public AjaxResult getOwnKnrd(){
        try{

            /* 此处使用硬编码，请根据实际情况修改。
        当前页面的功能是获取'困难认定---KNRD'标签对应的学年信息。
        涉及到学年标签字典module_tag，需要在字典管理中查询对应的信息。
        如果在字典管理更改了 学年标签 的信息，此处也要进行相应修改。
         尽量避免学年标签字典的更改!!!!*/
            //获取 困难认定 标签对应的学年
            List<SrsStuYear> year = srsStuYearMapper.selectYearsByTag("KNRD");
            //获取对应的学年id
            Long yearId = year.get(0).getId();
            QueryWrapper<SrsKnrdApply> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("xh",getUsername());
            queryWrapper.in("step", "3", "4", "5");
            queryWrapper.eq("stu_year_id", yearId);
            queryWrapper.last("limit 1");
            SrsKnrdApply srsKnrdApply = _knrdApplyMapper.selectOne(queryWrapper);
            if(srsKnrdApply == null){
                throw new Exception("困难认证未通过");
            }

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

    /**
     * 查询学生突发困难资助申请
     *
     * @param id 学生突发困难资助申请主键
     * @return 学生突发困难资助申请
     */
    @Override
    public KnzzTufaApply selectKnzzTufaApplyById(Long id) {
        return knzzTufaApplyMapper.selectKnzzTufaApplyById(id);
    }

    /**
     * 查询学生突发困难资助申请列表
     *
     * @param knzzTufaApply 学生突发困难资助申请
     * @return 学生突发困难资助申请
     */
    @Override
    public List<KnzzTufaApply> selectKnzzTufaApplyList(KnzzTufaApply knzzTufaApply) {
        return knzzTufaApplyMapper.selectKnzzTufaApplyList(knzzTufaApply);
    }

    /**
     * 新增学生突发困难资助申请
     *
     * @param knzzTufaApply 学生突发困难资助申请
     * @return 结果
     */
    @Override
    public int insertKnzzTufaApply(KnzzTufaApply knzzTufaApply) {
                knzzTufaApply.setCreateTime(getNowDate());
            return knzzTufaApplyMapper.insertKnzzTufaApply(knzzTufaApply);
    }

    /**
     * 修改学生突发困难资助申请
     *
     * @param knzzTufaApply 学生突发困难资助申请
     * @return 结果
     */
    @Override
    public int updateKnzzTufaApply(KnzzTufaApply knzzTufaApply) {
                knzzTufaApply.setUpdateTime(getNowDate());
        return knzzTufaApplyMapper.updateKnzzTufaApply(knzzTufaApply);
    }

    /**
     * 批量删除学生突发困难资助申请
     *
     * @param ids 需要删除的学生突发困难资助申请主键
     * @return 结果
     */
    @Override
    public int deleteKnzzTufaApplyByIds(Long[] ids) {
        return knzzTufaApplyMapper.deleteKnzzTufaApplyByIds(ids);
    }

    /**
     * 删除学生突发困难资助申请信息
     *
     * @param id 学生突发困难资助申请主键
     * @return 结果
     */
    @Override
    public int deleteKnzzTufaApplyById(Long id) {
        return knzzTufaApplyMapper.deleteKnzzTufaApplyById(id);
    }
}
