package com.srs.workstudy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.enums.QgzxApplyStatus;
import com.srs.common.exception.ServiceException;
import com.srs.comprehensive.domain.CphTeacher;
import com.srs.comprehensive.domain.SrsKnrdApply;
import com.srs.comprehensive.domain.SrsStuYear;
import com.srs.comprehensive.mapper.SrsKnrdApplyMapper;
import com.srs.comprehensive.mapper.SrsStuYearMapper;
import com.srs.workstudy.domain.QgzxPost;
import com.srs.workstudy.domain.QgzxStuPost;
import com.srs.workstudy.domain.dto.QgzxStuPostDto;
import com.srs.workstudy.domain.dto.StuPostSelectDto;
import com.srs.workstudy.domain.vo.StuPostListFindVo;
import com.srs.workstudy.mapper.QgzxPostMapper;
import com.srs.workstudy.mapper.QgzxStuPostMapper;
import com.srs.workstudy.service.IQgzxStuPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import java.util.*;
import java.util.stream.Collectors;

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

/**
 * 学生岗位Service业务层处理
 *
 * @author srs
 * @date 2024-06-03
 */
@Service
public class QgzxStuPostServiceImpl extends ServiceImpl<QgzxStuPostMapper, QgzxStuPost> implements IQgzxStuPostService {
    @Autowired
    private QgzxStuPostMapper qgzxStuPostMapper;

    @Autowired
    private QgzxPostMapper _postMapper;

    @Autowired
    private SrsStuYearMapper _yearMapper;

    @Autowired
    private SrsKnrdApplyMapper _knrdMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;


    @Override
    public List<CphTeacher> listTeacher(CphTeacher param){
        return qgzxStuPostMapper.listTeacher(param);
    }


    @Override
    public AjaxResult getStuFdyName(String stuNo){
        try{

            String fdyName = qgzxStuPostMapper.getFdyNameByStuNo(stuNo);
            if(fdyName == null){
                return AjaxResult.error("该学生未指导老师");
            }
            Map<String, Object> data = new HashMap<>();
            data.put("fdyName", fdyName);

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


    @Override
    public AjaxResult doReply(QgzxStuPost param) { // 重新提交
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            QgzxStuPost oldRecord = qgzxStuPostMapper.selectById(param.id);

            if (!Objects.equals(oldRecord.stuNo, getUsername())) {
                throw new Exception("您不是本人");
            }

            if (!Objects.equals(oldRecord.applyStatus, QgzxStuPost.applyStatusDict.Return.getValue())) {
                throw new Exception("该记录状态不是驳回");
            }

            oldRecord.applyStatus = QgzxStuPost.applyStatusDict.Replay.getValue();
            int res1 = qgzxStuPostMapper.updateById(oldRecord);

            if (res1 == 0) {
                throw new Exception("更新旧记录状态失败");
            }

            QgzxStuPost needInsert = new QgzxStuPost();
            needInsert.stuNo = getUsername();
            needInsert.postId = param.postId;
            needInsert.setZdlsNo(param.getZdlsNo());
            needInsert.canTime = param.canTime;
            needInsert.helpHis = param.helpHis;
            needInsert.familyCondition = param.familyCondition;
            needInsert.bankAddr = param.bankAddr;
            needInsert.bankCard = param.bankCard;
            needInsert.idCard = param.idCard;
            needInsert.stuPhone = param.stuPhone;
            needInsert.stuDorm = param.stuDorm;
            needInsert.familyAddr = param.familyAddr;
            needInsert.applyMaterial = param.applyMaterial;
            needInsert.applyReason = param.applyReason;
            needInsert.applySign = param.applySign;
            needInsert.applyStatus = QgzxStuPost.applyStatusDict.Submit.getValue();
            needInsert.applyTime = getNowDate();
            needInsert.workStatus = "否";

            int res2 = qgzxStuPostMapper.insert(needInsert);
            if (res2 == 0) {
                throw new Exception("插入新纪录失败");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public Map<String, Object> countStuPostInByPostId(Long postId) {
        Map<String, Object> data = new HashMap<>();

        QueryWrapper<QgzxStuPost> query = new QueryWrapper<>();
        query.eq("apply_status", "4")
                .eq("work_status", "是")
                .eq("post_id", postId);
        Long res = qgzxStuPostMapper.selectCount(query); //查询在岗人数
        data.put("count", res);

        return data;
    }


    @Override
    public AjaxResult doQuit(QgzxStuPost param) {
        try {
            QgzxStuPost stuPost = qgzxStuPostMapper.selectById(param.id);
            if (stuPost == null) {
                throw new Exception("该学生岗位记录不存在");
            }

            stuPost.workStatus = "否";
            int res = qgzxStuPostMapper.updateById(stuPost);
            if (res == 0) {
                throw new Exception("更新学生在岗状态失败");
            }

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


    @Override
    public AjaxResult doAudit(QgzxStuPost param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            QgzxStuPost stuPost = qgzxStuPostMapper.selectById(param.id);
            if (stuPost == null) {
                throw new Exception("该申请记录已被删除，刷新试试");
            }

            QgzxPost post = _postMapper.selectById(stuPost.postId);
            if (post == null) {
                throw new Exception("该岗位已被删除");
            }

//            if (!Objects.equals(post.zdlsNo, getUsername())) {
//                throw new Exception("您不是该岗位的指导老师");
//            }

            if (param.getAuditType().equals("0")) {
                param.setFdyNo(getUsername());
                param.fdyTime = getNowDate();
                if (Objects.equals(param.getFdyCmt(), "通过")) {
                    QueryWrapper<QgzxStuPost> findFull = new QueryWrapper<>();
                    findFull.eq("post_id", post.id)
                            .eq("work_status", "是");
                    List<QgzxStuPost> fullList = qgzxStuPostMapper.selectList(findFull);
                    if (fullList.size() >= Integer.parseInt(post.postCount)) {
                        throw new Exception("该岗位在岗人数已满，不能申请通过");
                    }
                    param.setFdyNo(getUsername());
                    param.applyStatus = QgzxApplyStatus.COUNSELOR_APPROVED.getCode();
//                    param.workStatus = "是";
                } else if (Objects.equals(param.getFdyCmt(), "驳回")) {
                    param.applyStatus = QgzxStuPost.applyStatusDict.Return.getValue();
                    param.workStatus = "否";
                } else {
                    param.applyStatus = QgzxApplyStatus.REJECTED.getCode();
                    param.workStatus = "否";
                }
            } else if (param.getAuditType().equals("1")) {
                param.setZdlsNo(getUsername());
                param.zdlsTime = getNowDate();
                if (Objects.equals(param.getZdlsCmt(), "通过")) {
                    Long postId = stuPost.getPostId();
                    Long zdlsYes = qgzxStuPostMapper.countZdlsYes(postId);
                    if (zdlsYes >= Integer.parseInt(post.postCount)) {
                        throw new Exception("该岗位已有别的记录被其指导老师审核通过，不能申请通过");
                    }

                    param.applyStatus = QgzxApplyStatus.INSTRUCTOR_APPROVED.getCode();
//                    param.workStatus = "是";
                } else if (Objects.equals(param.getZdlsCmt(), "驳回")) {
                    param.applyStatus = QgzxStuPost.applyStatusDict.Return.getValue();
                    param.workStatus = "否";
                } else {
                    param.applyStatus = QgzxApplyStatus.REJECTED.getCode();
                    param.workStatus = "否";
                }
            } else if (param.getAuditType().equals("2")) {
                param.setZzbNo(getUsername());
                param.zzbTime = getNowDate();
                if (Objects.equals(param.getZzbCmt(), "通过")) {
                    QueryWrapper<QgzxStuPost> findFull = new QueryWrapper<>();
                    findFull.eq("post_id", post.id)
                            .eq("work_status", "是");
                    List<QgzxStuPost> fullList = qgzxStuPostMapper.selectList(findFull);
                    if (fullList.size() >= Integer.parseInt(post.postCount)) {
                        throw new Exception("该岗位在岗人数已满，不能申请通过");
                    }
                    param.applyStatus = QgzxApplyStatus.CENTER_OPINION.getCode();
                    param.workStatus = "是";
                } else if (Objects.equals(param.getZzbCmt(), "驳回")) {
                    param.applyStatus = QgzxStuPost.applyStatusDict.Return.getValue();
                    param.workStatus = "否";
                } else {
                    param.applyStatus = QgzxApplyStatus.REJECTED.getCode();
                    param.workStatus = "否";
                }
            }

            int res = qgzxStuPostMapper.updateById(param);
            if (res == 0) {
                throw new Exception("修改状态失败");
            }

            transactionManager.commit(status);
            return AjaxResult.success();
        } catch (Exception ex) {
            transactionManager.rollback(status);
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public AjaxResult cancelApply(Long id) {
        try {
            QgzxStuPost find = qgzxStuPostMapper.selectById(id);
            if (find == null) {
                throw new Exception("申请记录不存在");
            }

            if (!Objects.equals(find.applyStatus, "0") && !Objects.equals(find.applyStatus, "1")) {
                throw new Exception("该记录已被审核,不能取消申请");
            }

            if (!Objects.equals(find.stuNo, getUsername())) {
                throw new Exception("不是本人");
            }

            int res = qgzxStuPostMapper.deleteQgzxStuPostById(id);
            if (res == 0) {
                throw new Exception("取消失败");
            }

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


    @Override
    public List<QgzxStuPost> listView(QgzxStuPost param) {
        return qgzxStuPostMapper.listView(param);
    }


    @Override
    public AjaxResult doApply(QgzxStuPost param) {
        try {

            QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
            yearQuery.eq("status", 1)
                    .orderByDesc("id")
                    .last("limit 1");
            SrsStuYear year = _yearMapper.selectOne(yearQuery);
            if (year == null) {
                throw new Exception("当前未开启学年");
            }

            Long stuYearId = year.getId();
//            QueryWrapper<SrsKnrdApply> knrdApplyQueryWrapper = new QueryWrapper<>();
//            knrdApplyQueryWrapper.eq("stu_year_id", stuYearId)
//                    .eq("xh", getUsername())
//                    .eq("step", 3);
//            List<SrsKnrdApply> knList = _knrdMapper.selectList(knrdApplyQueryWrapper);
//            if (knList.size() == 0) {
////                throw new Exception("您当前学年没有通过困难认定");
//                throw new Exception("辅导员未通过贫困生认定");
//            }

            QueryWrapper<SrsKnrdApply> knrdApplyQueryWrapper = new QueryWrapper<>();
            knrdApplyQueryWrapper.eq("stu_year_id", stuYearId)
                    .eq("xh", getUsername())
                    .eq("step", 0);
            List<SrsKnrdApply> knList = _knrdMapper.selectList(knrdApplyQueryWrapper);
            if (knList.size() > 0) {
//                throw new Exception("您当前学年没有通过困难认定");
                throw new Exception("贫困生认定待提交审核");
            }

            QueryWrapper<SrsKnrdApply> knrdApplyQueryWrapper2 = new QueryWrapper<>();
            knrdApplyQueryWrapper2.eq("stu_year_id", stuYearId)
                    .eq("xh", getUsername())
                    .eq("step", 2);
            List<SrsKnrdApply> knList2 = _knrdMapper.selectList(knrdApplyQueryWrapper2);
            if (knList2.size() > 0) {
//                throw new Exception("您当前学年没有通过困难认定");
                throw new Exception("贫困生认定辅导员审核中");
            }

            QgzxPost qgzxPost = _postMapper.selectById(param.postId);
            if (qgzxPost == null) {
                throw new Exception("该岗位不存在");
            }

            QueryWrapper<QgzxStuPost> findFull = new QueryWrapper<>();
            findFull.eq("post_id", param.postId)
                    .eq("work_status", "是");
            List<QgzxStuPost> fullList = qgzxStuPostMapper.selectList(findFull);
            if (fullList.size() >= Integer.parseInt(qgzxPost.postCount)) {
                throw new Exception("该岗位在岗人数已满，不能申请");
            }

            List<String> statusList = new ArrayList<>();
            statusList.add("0");
            statusList.add("1");
            QueryWrapper<QgzxStuPost> query = new QueryWrapper<>();
            query.eq("stu_no", param.stuNo)
                    .in("apply_status", statusList);
            if (param.id != null) {
                query.ne("id", param.id);
            }
            List<QgzxStuPost> list = qgzxStuPostMapper.selectList(query);
            if (list.size() != 0) {
                throw new Exception("您已经有一条申请记录了");
            }

            QueryWrapper<QgzxStuPost> findIsWorkQuery = new QueryWrapper<>();
            findIsWorkQuery.eq("stu_no", param.stuNo)
                    .eq("work_status", "是");
            List<QgzxStuPost> findIsWork = qgzxStuPostMapper.selectList(findIsWorkQuery);
            if (findIsWork.size() != 0) {
                throw new Exception("您已经在岗了,每人只能有一个岗位");
            }

            param.workStatus = "否";
            param.applyStatus = QgzxApplyStatus.SUBMITTED.getCode();
            param.applyTime = getNowDate();
            if (param.id != null) {
                QgzxStuPost qgzxStuPost = qgzxStuPostMapper.selectById(param.id);
                if (qgzxStuPost == null) {
                    throw new Exception("该记录不存在");
                }
            }

            boolean res = this.saveOrUpdate(param);
            if (!res) {
                throw new Exception("保存失败");
            }

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


    @Override
    public AjaxResult doSave(QgzxStuPost param) {
        try {

            QueryWrapper<SrsStuYear> yearQuery = new QueryWrapper<>();
            yearQuery.eq("status", 1)
                    .orderByDesc("id")
                    .last("limit 1");
            SrsStuYear year = _yearMapper.selectOne(yearQuery);
            if (year == null) {
                throw new Exception("当前未开启学年");
            }

            Long stuYearId = year.getId();
            QueryWrapper<SrsKnrdApply> knrdApplyQueryWrapper = new QueryWrapper<>();
            knrdApplyQueryWrapper.eq("stu_year_id", stuYearId)
                    .eq("xh", getUsername())
                    .eq("step", 0);
            List<SrsKnrdApply> knList = _knrdMapper.selectList(knrdApplyQueryWrapper);
            if (knList.size() > 0) {
//                throw new Exception("您当前学年没有通过困难认定");
                throw new Exception("贫困生认定待提交审核");
            }

            QueryWrapper<SrsKnrdApply> knrdApplyQueryWrapper2 = new QueryWrapper<>();
            knrdApplyQueryWrapper2.eq("stu_year_id", stuYearId)
                    .eq("xh", getUsername())
                    .eq("step", 2);
            List<SrsKnrdApply> knList2 = _knrdMapper.selectList(knrdApplyQueryWrapper2);
            if (knList2.size() > 0) {
//                throw new Exception("您当前学年没有通过困难认定");
                throw new Exception("贫困生认定辅导员审核中");
            }


            QgzxPost qgzxPost = _postMapper.selectById(param.postId);
            if (qgzxPost == null) {
                throw new Exception("该岗位不存在");
            }

            QueryWrapper<QgzxStuPost> findFull = new QueryWrapper<>();
            findFull.eq("post_id", param.postId)
                    .eq("work_status", "是");
            List<QgzxStuPost> fullList = qgzxStuPostMapper.selectList(findFull);
            if (fullList.size() >= Integer.parseInt(qgzxPost.postCount)) {
                throw new Exception("该岗位在岗人数已满，不能申请");
            }

            List<String> statusList = new ArrayList<>();
            statusList.add("0");
            statusList.add("1");
            QueryWrapper<QgzxStuPost> query = new QueryWrapper<>();
            query.eq("stu_no", param.stuNo)
                    .in("apply_status", statusList);
            if (param.id != null) {
                query.ne("id", param.id);
            }
            List<QgzxStuPost> list = qgzxStuPostMapper.selectList(query);
            if (list.size() != 0) {
                throw new Exception("您已经有一条申请记录了");
            }

            QueryWrapper<QgzxStuPost> findIsWorkQuery = new QueryWrapper<>();
            findIsWorkQuery.eq("stu_no", param.stuNo)
                    .eq("work_status", "是");
            List<QgzxStuPost> findIsWork = qgzxStuPostMapper.selectList(findIsWorkQuery);
            if (findIsWork.size() != 0) {
                throw new Exception("您已经在岗了,每人只能有一个岗位");
            }


            param.workStatus = "否";
            param.applyStatus = "0";
            param.applyTime = getNowDate();

            if (param.id != null) {
                QgzxStuPost qgzxStuPost = qgzxStuPostMapper.selectById(param.id);
                if (qgzxStuPost == null) {
                    throw new Exception("该记录不存在");
                }
            }

            boolean res = this.saveOrUpdate(param);
            if (!res) {
                throw new Exception("保存失败");
            }

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


    /**
     * 查询学生岗位
     *
     * @param id 学生岗位主键
     * @return 学生岗位
     */
    @Override
    public QgzxStuPost selectQgzxStuPostById(Long id) {
        return qgzxStuPostMapper.selectQgzxStuPostById(id);
    }

    /**
     * 查询学生岗位列表
     *
     * @param qgzxStuPost 学生岗位
     * @return 学生岗位
     */
    @Override
    public List<QgzxStuPost> selectQgzxStuPostList(QgzxStuPost qgzxStuPost) {
        return qgzxStuPostMapper.selectQgzxStuPostList(qgzxStuPost);
    }

    /**
     * 新增学生岗位
     *
     * @param qgzxStuPost 学生岗位
     * @return 结果
     */
    @Override
    public int insertQgzxStuPost(QgzxStuPost qgzxStuPost) {
        qgzxStuPost.setCreateTime(getNowDate());
        return qgzxStuPostMapper.insertQgzxStuPost(qgzxStuPost);
    }

    /**
     * 修改学生岗位
     *
     * @param qgzxStuPost 学生岗位
     * @return 结果
     */
    @Override
    public int updateQgzxStuPost(QgzxStuPost qgzxStuPost) {
        qgzxStuPost.setUpdateTime(getNowDate());
        return qgzxStuPostMapper.updateQgzxStuPost(qgzxStuPost);
    }
    @Override
    public  int updateInstructor(QgzxStuPostDto qgzxStuPostDto){
        return  qgzxStuPostMapper.updateInstructor(qgzxStuPostDto);
    }
    /**
     * 批量删除学生岗位
     *
     * @param ids 需要删除的学生岗位主键
     * @return 结果
     */
    @Override
    public int deleteQgzxStuPostByIds(Long[] ids) {
        return qgzxStuPostMapper.deleteQgzxStuPostByIds(ids);
    }

    /**
     * 删除学生岗位信息
     *
     * @param id 学生岗位主键
     * @return 结果
     */
    @Override
    public int deleteQgzxStuPostById(Long id) {
        return qgzxStuPostMapper.deleteQgzxStuPostById(id);
    }

    @Override
    public AjaxResult manyAudit(List<QgzxStuPost> param) {
        List<Long> ids = param.stream().map(x -> x.id).collect(Collectors.toList());
        QueryWrapper<QgzxStuPost> query = new QueryWrapper<>();
        query.in("id", ids);
        List<QgzxStuPost> list = qgzxStuPostMapper.selectList(query);
        if (list.size() == 0) {
            return AjaxResult.error("没有查询到记录");
        }
        // 循环，进行审批操作
        for (QgzxStuPost qgzxStuPost : param) {
            QgzxStuPost qgzxStuPost1 = qgzxStuPostMapper.selectQgzxStuPostById(qgzxStuPost.id);
            QgzxPost qgzxPost = _postMapper.selectById(qgzxStuPost1.postId);
            if (qgzxPost == null) {
                throw new ServiceException("该岗位不存在");
            }
            if (qgzxStuPost.applyStatus.equals(QgzxApplyStatus.CENTER_OPINION.getCode())) {
                if (Objects.equals(qgzxStuPost.getZzbCmt(), "通过")) {
                    QueryWrapper<QgzxStuPost> findFull = new QueryWrapper<>();
                    findFull.eq("post_id", qgzxStuPost.postId)
                            .eq("work_status", "是");
                    List<QgzxStuPost> fullList = qgzxStuPostMapper.selectList(findFull);
                    if (fullList.size() >= Integer.parseInt(qgzxPost.postCount)) {
                        throw new ServiceException("该岗位在岗人数已满，不能申请通过");
                    }
                    qgzxStuPost.zzbTime = getNowDate();
                    qgzxStuPost.setZzbNo(getUsername());
                    qgzxStuPost.setApplyStatus(QgzxApplyStatus.CENTER_OPINION.getCode());
                    qgzxStuPost.setWorkStatus("是");
                    this.updateById(qgzxStuPost);
                } else {
                    qgzxStuPost.zzbTime = getNowDate();
                    qgzxStuPost.setZzbNo(getUsername());
                    qgzxStuPost.setApplyStatus(QgzxApplyStatus.REJECTED.getCode());
                    qgzxStuPost.setWorkStatus("否");
                    this.updateById(qgzxStuPost);
                }
            } else if (qgzxStuPost.applyStatus.equals(QgzxApplyStatus.REJECTED.getCode())) {
                qgzxStuPost.zzbTime = getNowDate();
                qgzxStuPost.setZzbNo(getUsername());
                qgzxStuPost.setApplyStatus(QgzxApplyStatus.REJECTED.getCode());
                qgzxStuPost.setWorkStatus("否");
                this.updateById(qgzxStuPost);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public List<StuPostListFindVo> getQgzxStuPostList(StuPostSelectDto param) {
        return qgzxStuPostMapper.getQgzxStuPostList(param);
    }
}
