package com.srs.comprehensive.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.core.domain.entity.SysRole;
import com.srs.common.core.domain.model.LoginUser;
import com.srs.common.utils.DateUtils;
import com.srs.common.utils.SecurityUtils;
import com.srs.common.utils.StringUtils;
import com.srs.comprehensive.domain.CphGoodApply;
import com.srs.comprehensive.domain.Dto.CphAuditMany;
import com.srs.comprehensive.mapper.CphGoodApplyMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.srs.comprehensive.mapper.CphGoodAuditMapper;
import com.srs.comprehensive.domain.CphGoodAudit;
import com.srs.comprehensive.service.ICphGoodAuditService;
import org.springframework.transaction.annotation.Transactional;

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


/**
 * 评优审核Service业务层处理
 *
 * @author srs
 * @date 2023-09-12
 */
@Service
public class CphGoodAuditServiceImpl extends ServiceImpl<CphGoodAuditMapper,CphGoodAudit> implements ICphGoodAuditService {
    @Autowired
    private CphGoodAuditMapper cphGoodAuditMapper;
    @Autowired
    private CphGoodApplyMapper cphGoodApplyMapper;

    /**
     * 查询评优审核
     *
     * @param id 评优审核主键
     * @return 评优审核
     */
    @Override
    public CphGoodAudit selectCphGoodAuditById(Long id) {
        return cphGoodAuditMapper.selectCphGoodAuditById(id);
    }

    @Override
    public Map<String,Object> fdyCountUnAudit(String tNo){
        return cphGoodAuditMapper.fdyCountUnAudit(tNo);
    }

    @Override
    public Map<String,Object> xwCountUnAudit(Long deptId){
        return cphGoodAuditMapper.xwCountUnAudit(deptId);
    }

    @Override
    public Map<String,Object> jwcCountUnAudit(){
        return cphGoodAuditMapper.jwcCountUnAudit();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult manyAudit(CphAuditMany param){
        try{
            String applyStatus = "2";
            //学工
            if (param.getRoleId()==100){
                applyStatus = "6";
            }
            //学务
            if (param.getRoleId()==105) {
                applyStatus = "3";
            }

            Long[] applyIds = param.applyIds;
            List<Long> applyIdList = new ArrayList<>();

            for (Long id: applyIds ) {
                applyIdList.add(id);
                CphGoodApply temp = new CphGoodApply();
                temp.setApplyStatus(applyStatus);
                temp.setUpdateTime(getNowDate());
                temp.setUpdateBy(getUsername());
                temp.setId(id);
                cphGoodApplyMapper.updateById(temp);
            }

            List<CphGoodAudit> needUpdateAudit = cphGoodAuditMapper.selectList(null)
                    .stream().filter(x -> applyIdList.contains(x.getApplyId())).collect(Collectors.toList());

            for(CphGoodAudit item : needUpdateAudit ){
                //学工
                if (param.getRoleId()==100){
                    item.setFinalComment(param.common);
                    item.setFinalStatus(applyStatus);
                    item.setFinalTime(getNowDate());
                }
                //学务
                if (param.getRoleId()==105){
                    item.setDeptComment(param.common);
                    item.setDeptStatus(applyStatus);
                    item.setDeptTime(getNowDate());
                }
                item.setUpdateTime(getNowDate());
                item.setUpdateBy(getUsername());
                cphGoodAuditMapper.updateById(item);
            }


            return AjaxResult.success("操作成功");
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult changeApply(CphGoodAudit param){
        try{
            String applyStatus = param.getStatus();
            CphGoodAudit query = new CphGoodAudit();
            query.setApplyId(param.getApplyId());
            List<CphGoodAudit> needUpdateAuditList = cphGoodAuditMapper.selectCphGoodAuditList(query);
            if(needUpdateAuditList.size() == 0){
                throw new Exception("审核记录不存在,请联系管理员");
            }
            CphGoodAudit needUpdateAudit = needUpdateAuditList.get(0);
            needUpdateAudit.setFinalComment(param.getFinalComment());
            int res1 = cphGoodAuditMapper.updateCphGoodAudit(needUpdateAudit);
            if(res1!= 1){
                throw new Exception("更新审核记录失败,请联系管理员");
            }
            CphGoodApply needUpdateApply = cphGoodApplyMapper.selectCphGoodApplyById(param.getApplyId());
            if(needUpdateApply == null){
                throw new Exception("申请记录不存在，请联系管理员");
            }
            needUpdateApply.setApplyStatus(applyStatus);
            int res2 = cphGoodApplyMapper.updateCphGoodApply(needUpdateApply);
            if(res2 != 1){
                throw new Exception("更新申请记录失败，请联系管理员");
            }
            return AjaxResult.success("操作成功");
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult voidApply(CphGoodAudit param){
        try{
            CphGoodAudit query = new CphGoodAudit();
            query.setApplyId(param.getApplyId());
            List<CphGoodAudit> needUpdateAuditList = cphGoodAuditMapper.selectCphGoodAuditList(query);
            if(needUpdateAuditList.size() == 0){
                throw new Exception("审核记录不存在,请联系管理员");
            }
            CphGoodAudit needUpdateAudit = needUpdateAuditList.get(0);
            needUpdateAudit.setFinalComment(param.getFinalComment());
            int res1 = cphGoodAuditMapper.updateCphGoodAudit(needUpdateAudit);
            if(res1!= 1){
                throw new Exception("更新审核记录失败,请联系管理员");
            }
            CphGoodApply needUpdateApply = cphGoodApplyMapper.selectCphGoodApplyById(param.getApplyId());
            if(needUpdateApply == null){
                throw new Exception("申请记录不存在，请联系管理员");
            }
            needUpdateApply.setApplyStatus("12");
            int res2 = cphGoodApplyMapper.updateCphGoodApply(needUpdateApply);
            if(res2 != 1){
                throw new Exception("更新申请记录失败，请联系管理员");
            }
            return AjaxResult.success();
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }


    /**
     * 查询评优审核列表
     *
     * @param cphGoodAudit 评优审核
     * @return 评优审核
     */
    @Override
    public List<CphGoodAudit> selectCphGoodAuditList(CphGoodAudit cphGoodAudit) {
        return cphGoodAuditMapper.selectCphGoodAuditList(cphGoodAudit);
    }

    /**
     * 新增评优审核
     *
     * @param cphGoodAudit 评优审核
     * @return 结果
     */
    @Override
    public int insertCphGoodAudit(CphGoodAudit cphGoodAudit) {
                cphGoodAudit.setCreateTime(getNowDate());
            return cphGoodAuditMapper.insertCphGoodAudit(cphGoodAudit);
    }

    /**
     * 修改评优审核
     *
     * @param cphGoodAudit 评优审核
     * @return 结果
     */
    @Override
    public int updateCphGoodAudit(CphGoodAudit cphGoodAudit) {
                cphGoodAudit.setUpdateTime(getNowDate());
        return cphGoodAuditMapper.updateCphGoodAudit(cphGoodAudit);
    }

    /**
     * 批量删除评优审核
     *
     * @param ids 需要删除的评优审核主键
     * @return 结果
     */
    @Override
    public int deleteCphGoodAuditByIds(Long[] ids) {
        return cphGoodAuditMapper.deleteCphGoodAuditByIds(ids);
    }

    /**
     * 删除评优审核信息
     *
     * @param id 评优审核主键
     * @return 结果
     */
    @Override
    public int deleteCphGoodAuditById(Long id) {
        return cphGoodAuditMapper.deleteCphGoodAuditById(id);
    }

    /**
     * 辅导员审核申请
     * @param auditId 审核表ID
     * @param status 审核状态
     * @param common 审核意见
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult fdyAudit(Long auditId, String status, String common) {
            CphGoodAudit cphGoodAudit = getById(auditId);
            cphGoodAudit.setFdyNo(getUsername());
            cphGoodAudit.setFdyStatus(status);
            cphGoodAudit.setFdyComment(common);
            cphGoodAudit.setFdyTime(getNowDate());
        boolean updateApply = new LambdaUpdateChainWrapper<>(cphGoodApplyMapper)
                .eq(CphGoodApply::getId, cphGoodAudit.getApplyId())
                .set(CphGoodApply::getApplyStatus, status.equals("6") ? "2" : status)
                .update();
        boolean updateAudit = updateById(cphGoodAudit);
        if (!updateAudit||!updateApply) {
            throw new RuntimeException("审核失败");
        }
        return AjaxResult.success();
    }

    /**
     * 学院人员审核申请
     * @param auditId 审核表ID
     * @param status 审核状态
     * @param common 审核意见
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult deptAudit(Long auditId, String status, String common) {
        CphGoodAudit cphGoodAudit = getById(auditId);
        if (StringUtils.isEmpty(cphGoodAudit.getFdyStatus())||cphGoodAudit.getFdyStatus().equals("1")) return AjaxResult.error("辅导员尚未审核");
        if (cphGoodAudit.getFdyStatus().equals("10")||cphGoodAudit.getFdyStatus().equals("11")){
            return AjaxResult.error("辅导员已驳回或拒绝申请");
        }
        cphGoodAudit.setDeptNo(getUsername());
        cphGoodAudit.setDeptStatus(status);
        cphGoodAudit.setDeptTime(getNowDate());
        cphGoodAudit.setDeptComment(common);
        boolean updateApply = new LambdaUpdateChainWrapper<>(cphGoodApplyMapper)
                .eq(CphGoodApply::getId, cphGoodAudit.getApplyId())
                .eq(CphGoodApply::getApplyStatus, "2")
                .set(CphGoodApply::getApplyStatus, status.equals("6") ? "3" : status)
                .update();
        boolean updateAudit = updateById(cphGoodAudit);
        if (!updateAudit||!updateApply){
            throw new RuntimeException("审核失败");
        }
        return AjaxResult.success();
    }

    /**
     * 学工处审核申请
     * @param auditId 审核表ID
     * @param status 审核状态
     * @param common 审核意见
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult finalAudit(Long auditId, String status, String common) {
        CphGoodAudit cphGoodAudit = getById(auditId);
        if (StringUtils.isEmpty(cphGoodAudit.getDeptStatus())||cphGoodAudit.getDeptStatus().equals("1")) return AjaxResult.error("学务干事尚未审核");
        if (cphGoodAudit.getDeptStatus().equals("10")||cphGoodAudit.getDeptStatus().equals("11")){
            return AjaxResult.error("学务干事已驳回或拒绝申请");
        }
        cphGoodAudit.setFinalNo(getUsername());
        cphGoodAudit.setFinalStatus(status);
        cphGoodAudit.setFinalTime(getNowDate());
        cphGoodAudit.setFinalComment(common);
        boolean updateApply = new LambdaUpdateChainWrapper<>(cphGoodApplyMapper)
                .eq(CphGoodApply::getId, cphGoodAudit.getApplyId())
                .eq(CphGoodApply::getApplyStatus, "3")
                .set(CphGoodApply::getApplyStatus, status)
                .update();
        boolean updateAudit = updateById(cphGoodAudit);
        if (!updateAudit||!updateApply){
            throw new RuntimeException("审核失败");
        }
        return AjaxResult.success();
    }
}
