package com.srs.comprehensive.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.utils.PageUtils;
import com.srs.comprehensive.domain.*;
import com.srs.comprehensive.domain.Dto.CphCancel;
import com.srs.comprehensive.domain.Dto.CphResub;
import com.srs.comprehensive.domain.Vo.CphApply;
import com.srs.comprehensive.domain.Vo.CphSearch;
import com.srs.comprehensive.mapper.CphIamMapper;
import com.srs.comprehensive.mapper.SrsAddRecordMapper;
import com.srs.comprehensive.service.*;
import com.srs.system.domain.SysPost;
import com.srs.system.service.ISysPostService;
import com.srs.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.mapper.CphAuditDetailsMapper;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.DefaultTransactionDefinition;

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

/**
 * 审核明细Service业务层处理
 *
 * @author 邓
 * @date 2023-07-04
 */
@Service
public class CphAuditDetailsServiceImpl implements ICphAuditDetailsService {
    @Autowired
    private CphAuditDetailsMapper cphAuditDetailsMapper;
    @Autowired
    private ISysUserService sysUserService; //系统用户

    @Autowired
    private ISysPostService sysPostService; //岗位

    @Autowired
    private ISrsCqScoreService cqScoreService;  //综合素质

    @Autowired
    private ISrsCourseScoreService srsCourseScoreService; //课程成绩

    @Autowired
    private ISrsSportTestService srsSportTestService; //体能测试

    @Autowired
    private ICphClasstwoService iCphClasstwoService; //第二课堂

    @Autowired
    private ICphIamService cphIamService; //思想品德

    @Autowired
    private ISrsAddRecordService srsAddRecordService; //加分记录

    @Autowired
    private ICphAuditDetailsService _auditService;


    @Autowired
    private ICphRulesService _rulesService;

    @Autowired
    private ICphTeacherService _teacherService;

    @Autowired
    private ISrsStudentService _stuService;

    @Autowired
    private ICphMsgService _msgService; //消息

    @Autowired
    private CphIamMapper cphIamMapper;

    @Autowired
    public SrsAddRecordMapper _addRecordMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;

    @Override
    public List<CphApply> listOwnProcessed(CphSearch param) {
        return cphIamMapper.listOwnProcessed(param);
    }

    @Override
    public List<CphApply> listOwnApply(String stuNo) {
        return cphIamMapper.listOwnApply(stuNo);
    }


    @Async
    public void sendMsg(long uid, CphAuditDetails cad) {
        SrsStudent stu = _stuService.selectSrsStudentByStuId(cad.getSubmitterId());
        SysUser user = sysUserService.selectUserByUserName(stu.getStuNo());
        CphMsg msg = new CphMsg();
        msg.setSender(uid);
        msg.setReceiver(user.getUserId());
        if (cad.getStatusCode() == 2L) {
            String content = "您提交申请的《" + cad.getProjectName() + "》已通过辅导员审核";
            msg.setContent(content);
            _msgService.insertCphMsg(msg);

        } else if (cad.getStatusCode() == 6L) {
            String content = "您提交申请的《" + cad.getProjectName() + "》已通过审核";
            msg.setContent(content);
            _msgService.insertCphMsg(msg);
        } else if (cad.getStatusCode() == 10L) {
            String content = "您提交申请的《" + cad.getProjectName() + "》已被驳回，请重新提交";
            msg.setContent(content);
            _msgService.insertCphMsg(msg);
        }
    }

    @Override
    public AjaxResult getDetail(long id) {
        CphAuditDetails cad = cphAuditDetailsMapper.selectCphAuditDetailsById(id);
        CphIam iam = cphIamService.selectCphIamById(cad.getProjectId());
        iam.setStudent(_stuService.selectSrsStudentByStuId(iam.getToAdd()));
        return AjaxResult.success(iam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int reSub(CphResub param) {
        try {
            Long iamId = param.iamId;
            CphIam ciUpdate = cphIamService.selectCphIamById(iamId);
            ciUpdate.setAuditStatus("14");
            ciUpdate.setUpdateTime(getNowDate());
            ciUpdate.setUpdateBy(getUsername());
            cphIamService.updateCphIam(ciUpdate);

            CphAuditDetails cadUpdate = cphAuditDetailsMapper.selectCphAuditDetailsByProjectId(iamId);
            cadUpdate.setStatusCode(14L);
            cadUpdate.setUpdateTime(getNowDate());
            cadUpdate.setUpdateBy(getUsername());
            cadUpdate.setRemarks("已重新提交");
            cphAuditDetailsMapper.updateCphAuditDetails(cadUpdate);

            CphRules rule = _rulesService.selectCphRulesByRuleId(param.ruleId);

            CphIam ciInsert = new CphIam();
            ciInsert.setIamScore(rule.getMaxScore());
            ciInsert.setToAdd(ciUpdate.getToAdd());
            ciInsert.setSubmitter(ciUpdate.getSubmitter());
            ciInsert.setRuleId(param.ruleId);
            ciInsert.setAuditStatus("1");
            ciInsert.setDescription(param.description);
            ciInsert.setMaterial(param.getMaterial());
            ciInsert.setDelFlag("0");
            ciInsert.setCreateTime(getNowDate());
            ciInsert.setCreateBy(getUsername());
            ciInsert.setStuYearId(param.getStuYearId());
            SrsStudent stu = _stuService.selectSrsStudentByStuId(ciInsert.getToAdd());
            ciInsert.setStuNo(stu.getStuNo());
            int res1 = cphIamMapper.insertCphIam(ciInsert);

            if (res1 != 0) {
                Long id = ciInsert.getId();

                CphAuditDetails cadInsert = new CphAuditDetails();
                cadInsert.setProjectId(id);
                cadInsert.setSubmitterId(ciInsert.getToAdd());
                cadInsert.setSubmitterName(stu.getName());
                cadInsert.setProjectName(rule.getRuleName());
                cadInsert.setProjectTypeId(1L);
                cadInsert.setStatusCode(1L);
                cadInsert.setCreateTime(getNowDate());
                cadInsert.setCreateBy(getUsername());
                int res2 = _auditService.insertCphAuditDetails(cadInsert);

                int all = res1 + res2;
                if (all == 2) {
                    return 1;
                } else {
                    return 0;
                }

            } else {
                return 0;
            }
        } catch (Exception ex) {
            return 0;
        }

    }

    @Override
    public AjaxResult cancelProcess(CphCancel param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            Long iamId = param.id;
            String reason = param.reason;
            BigDecimal zero = BigDecimal.valueOf(0.00);
            CphIam iam = cphIamService.selectCphIamById(iamId);

            if (iam.getAuditStatus().equals("12")) {
                return AjaxResult.success("该记录已作废");
            }

            BigDecimal score = zero.subtract(iam.getIamScore());
            iam.setAuditStatus("12");
            iam.setUpdateTime(getNowDate());
            iam.setUpdateBy(getUsername());
            int ret1 = cphIamService.updateCphIam(iam);
            if (ret1 != 1) {
                throw new Exception("更新思想品德状态失败,与服务器连接不稳定");
            }


            CphAuditDetails cadUpdate = cphAuditDetailsMapper.selectCphAuditDetailsByProjectId(iamId);
            if (cadUpdate == null) {
                throw new Exception("未能查询到思想品德记录，作废失败，请联系系统管理员");
            }
            cadUpdate.setStatusCode(12L);
            cadUpdate.setUpdateTime(getNowDate());
            cadUpdate.setUpdateBy(getUsername());
            cadUpdate.setRemarks("作废");
            int ret2 = cphAuditDetailsMapper.updateCphAuditDetails(cadUpdate);
            if (ret2 != 1) {
                throw new Exception("更新审核状态失败,与服务器连接不稳定");
            }

            CphIam temp = new CphIam();
            temp.setIamScore(score);
            temp.setToAdd(iam.getToAdd());
            temp.setSubmitter(iam.getSubmitter());
            temp.setRuleId(iam.getRuleId());
            temp.setAuditStatus("13");
            temp.setDescription(reason);
            temp.setMaterial(iam.getMaterial());
            temp.setDelFlag("0");
            temp.setCreateTime(getNowDate());
            temp.setCreateBy(getUsername());
            temp.setStuYearId(iam.getStuYearId());
            SrsStudent stu = _stuService.selectSrsStudentByStuId(temp.getToAdd());
            temp.setStuNo(stu.getStuNo());
            int res1 = cphIamMapper.insertCphIam(temp);

            if (res1 != 0) {
                CphRules rule = _rulesService.selectCphRulesByRuleId(temp.getRuleId());
                Long id = temp.getId();

                CphAuditDetails cad = new CphAuditDetails();
                cad.setProjectId(id);
                cad.setSubmitterId(temp.getToAdd());
                cad.setSubmitterName(stu.getName());
                cad.setProjectName(rule.getRuleName());
                cad.setProjectTypeId(rule.getRuleId());
                cad.setStatusCode(13L);
                cad.setCreateTime(getNowDate());
                cad.setCreateBy(getUsername());
                cad.setRemarks("平衡分数");
                int res2 = _auditService.insertCphAuditDetails(cad);

                if (res2 != 1) {
                    throw new Exception("插入审核平衡分数失败");
                }

                SrsAddRecord sar = new SrsAddRecord();
                sar.setRecordScore(score);
                sar.setStuNo(stu.getStuNo());
                sar.setApplicant(getUserId());
                sar.setRuleId(temp.getRuleId());
                sar.setDescription(reason);
                sar.setMaterial(temp.getMaterial());
                sar.setRecordScore(score);
                sar.setStuYearId(Integer.parseInt(temp.getStuYearId().toString()));
                sar.setStatusCode("6");
                sar.setDelFlag("0");
                sar.setCreateTime(getNowDate());
                temp.setCreateBy(getUsername());

                int res3 = srsAddRecordService.insertSrsAddRecord(sar);
                if (res3 != 1) {
                    throw new Exception("插入加分记录表平衡分数失败");
                }

                int all = res1 + res2 + res3;
                if (all == 3) {
                    int stuYearId = Integer.parseInt(temp.getStuYearId().toString());
                    String stuNo = stu.getStuNo();
                    cphIamMapper.executeTestIam(stuYearId, stuNo);

                    transactionManager.commit(status);
                    return AjaxResult.success("作废成功");
                } else {
                    throw new Exception("因为未知原因,作废失败");
                }

            } else {
                throw new Exception("插入思想品德平衡分数失败");
            }

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

    }

    /**
     * 查询审核明细
     *
     * @param id 审核明细主键
     * @return 审核明细
     */
    @Override
    public CphAuditDetails selectCphAuditDetailsById(Long id) {
        return cphAuditDetailsMapper.selectCphAuditDetailsById(id);
    }

    /**
     * 查询已审核
     *
     * @param cad
     * @return
     * @author zhy
     * @date 2023-07-06 14:28:45
     **/
    @Override
    public List<CphAuditDetails> listMyProcessed(CphAuditDetails cad, long uid) {
        List<Long> postIds = sysPostService.selectPostListByUserId(uid);
        if (!postIds.isEmpty()) {
            for (Long postId : postIds) {
                SysPost sysPost = sysPostService.selectPostById(postId); //获取到岗位
                if (sysPost.getPostCode().equals("fdy")) {  //辅导员
                    SysUser user = sysUserService.selectUserById(uid);
                    CphTeacher ct = _teacherService.searchTeacherByEmployeeId(user.getUserName());
                    Map map = new HashMap();
                    map.put("fdy", ct.getTeacherId());
                    cad.setParams(map);
                } else if (sysPost.getPostCode().equals("jwcgl")) {  //教务人员
                    Map map = new HashMap();
                    map.put("jwc", uid);
                    cad.setParams(map);
                }
            }
        }
        PageUtils.startPage();
        return cphAuditDetailsMapper.listMyProcessed(cad);
    }

    /**
     * 查询审核明细列表
     *
     * @param cphAuditDetails 审核明细
     * @return 审核明细
     */
    @Override
    public List<CphAuditDetails> selectCphAuditDetailsList(CphAuditDetails cphAuditDetails) {

        return cphAuditDetailsMapper.selectCphAuditDetailsList(cphAuditDetails);
    }

    /**
     * 查询审核明细列表
     *
     * @param cphAuditDetails 审核明细
     * @return 审核明细
     */
    @Override
    public List<CphAuditDetails> searchCphAuditDetailsList(CphAuditDetails cphAuditDetails, Long userId) {
        //cphAuditDetailsMapper   cphAuditDetailsMapper.selectCphAuditDetailsList(cphAuditDetails);
        List<Long> postIds = sysPostService.selectPostListByUserId(userId);
        if (!postIds.isEmpty()) {
            for (Long postId : postIds) {
                SysPost sysPost = sysPostService.selectPostById(postId); //获取到岗位
                if (sysPost.getPostCode().equals("fdy")) {  //辅导员
                    cphAuditDetails.setStatusCode(1L);
                    SysUser user = sysUserService.selectUserById(userId);
                    CphTeacher ct = _teacherService.searchTeacherByEmployeeId(user.getUserName());
                    Map map = new HashMap();
                    map.put("fdy", ct.getTeacherId());
                    cphAuditDetails.setParams(map);
                } else if (sysPost.getPostCode().equals("jwcgl")) {  //教务人员
                    SysUser temp = sysUserService.selectUserById(userId);
                    Long deptId = temp.getDeptId();
                    cphAuditDetails.setStatusCode(2L);
                    Map map = new HashMap();
                    map.put("jwc", deptId);
                    cphAuditDetails.setParams(map);
                }
            }
        }
        PageUtils.startPage();
        return cphAuditDetailsMapper.searchCphAuditDetailsList(cphAuditDetails);
    }

    /**
     * 新增审核明细
     *
     * @param cphAuditDetails 审核明细
     * @return 结果
     */
    @Override
    public int insertCphAuditDetails(CphAuditDetails cphAuditDetails) {
        cphAuditDetails.setCreateTime(getNowDate());
        return cphAuditDetailsMapper.insertCphAuditDetails(cphAuditDetails);
    }

    /**
     * 修改审核明细
     *
     * @param cphAuditDetails 审核明细
     * @return 结果
     */
    @Override
    public int updateCphAuditDetails(CphAuditDetails cphAuditDetails) {
        return cphAuditDetailsMapper.updateCphAuditDetails(cphAuditDetails);
    }

    //审核操作
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditOpera(CphAuditDetails cphAuditDetails) {
        CphIam temp = new CphIam();
        temp.setId(cphAuditDetails.getProjectId());
        temp.setAuditStatus(cphAuditDetails.getStatusCode().toString());
        cphIamService.updateCphIam(temp);

        if (cphAuditDetails.getStatusCode() == 6L)//判断审核状态是否完成
        {
            SrsStudent stu = _stuService.selectSrsStudentByStuId(cphAuditDetails.getSubmitterId());
            SrsAddRecord srsAddRecord = new SrsAddRecord();//加分记录表
            CphIam cphIam = cphIamService.selectCphIamById(cphAuditDetails.getProjectId());//根据加分id查询思想品德

            QueryWrapper<SrsAddRecord> recordQueryWrapper = new QueryWrapper<>();
            recordQueryWrapper.eq("iam_id", cphIam.getId());
            List<SrsAddRecord> addRecordList = _addRecordMapper.selectList(recordQueryWrapper);
            if (addRecordList.size() != 0) {
                return 0;
            }

            srsAddRecord.setStuNo(stu.getStuNo());//加分人学号
            srsAddRecord.setApplicant(cphIam.getSubmitter());//申请人
            srsAddRecord.setRuleId(cphIam.getRuleId());//规则类别标示
            srsAddRecord.setDescription(cphIam.getDescription());//加分描述
            srsAddRecord.setMaterial(cphIam.getMaterial());//佐证材料
            srsAddRecord.setRecordScore(cphIam.getIamScore());//加分
            srsAddRecord.setStatusCode("6");//审核状态
            srsAddRecord.setStuYearId(Math.toIntExact(cphIam.getStuYearId()));//学年id
            srsAddRecord.setIamId(cphIam.getId());
            //srsAddRecord.setAddPointsPerson(cphIam.getSubmitter().toString());
            //srsAddRecord.setPlusPoints(Integer.parseInt(cphIam.getIamScore().toString())); //写入加分记录
            int i = srsAddRecordService.insertSrsAddRecord(srsAddRecord);
            if (i > 0) {
                cphIamMapper.executeTestIam(Math.toIntExact(srsAddRecord.getStuYearId()), stu.getStuNo());
            }
        }
        int i = cphAuditDetailsMapper.updateCphAuditDetails(cphAuditDetails);
        return i;
    }

    /**
     * 批量同意
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int auditOperaBatch(Long[] ids, Long userId) {
        List<Long> postIds = sysPostService.selectPostListByUserId(userId);//根据用户id获取岗位
        Long status = null;//审核状态
        if (postIds != null) {
            for (Long postId : postIds) {
                SysPost sysPost = sysPostService.selectPostById(postId); //获取到岗位
                if (sysPost.getPostCode().equals("fdy")) {
                    status = 6L;
                } else if (sysPost.getPostCode().equals("jwcgl")) {
                    status = 6L;
                } else if (sysPost.getPostCode().equals("xz")) {
                    status = 6L;
                } else if (sysPost.getPostCode().equals("sj")) {
                    status = 6L;
                }
            }
        }
        int i = 0;
        for (Long id : ids) {
            CphAuditDetails cphAuditDetails = selectCphAuditDetailsById(id);
            cphAuditDetails.setStatusCode(status);
            boolean res = auditOpera(cphAuditDetails) > 0;
            if (res) {
                i++;
                sendMsg(getUserId(), cphAuditDetails);
            }
        }
        return i;

    }


    /**
     * 批量删除审核明细
     *
     * @param ids 需要删除的审核明细主键
     * @return 结果
     */
    @Override
    public int deleteCphAuditDetailsByIds(Long[] ids) {
        return cphAuditDetailsMapper.deleteCphAuditDetailsByIds(ids);
    }

    /**
     * 删除审核明细信息
     *
     * @param id 审核明细主键
     * @return 结果
     */
    @Override
    public int deleteCphAuditDetailsById(Long id) {
        return cphAuditDetailsMapper.deleteCphAuditDetailsById(id);
    }

    /**
     * 到辅导员审核完成
     */
    @Override
    public int completedFinish(CphAuditDetails cphAuditDetails) {
        CphAuditDetails cphAuditDetailsS = cphAuditDetailsMapper.selectCphAuditDetailsById(cphAuditDetails.getId());
        cphAuditDetailsS.setStatusCode(cphAuditDetails.getStatusCode());
        int i = cphAuditDetailsMapper.updateCphAuditDetails(cphAuditDetailsS);
        return -1;

    }
}
