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.core.domain.entity.SysDept;
import com.srs.common.core.domain.entity.SysUser;
import com.srs.common.enums.QgzxApplyStatus;
import com.srs.comprehensive.domain.CphTeacher;
import com.srs.comprehensive.mapper.CphTeacherMapper;
import com.srs.system.domain.QgzxTeacher;
import com.srs.system.mapper.QgzxTeacherMapper;
import com.srs.system.mapper.SysDeptMapper;
import com.srs.system.mapper.SysUserMapper;
import com.srs.workstudy.domain.QgzxMoney;
import com.srs.workstudy.domain.QgzxPost;
import com.srs.workstudy.domain.QgzxStuPost;
import com.srs.workstudy.domain.QgzxWorkLog;
import com.srs.workstudy.mapper.QgzxMoneyMapper;
import com.srs.workstudy.mapper.QgzxPostMapper;
import com.srs.workstudy.mapper.QgzxStuPostMapper;
import com.srs.workstudy.mapper.QgzxWorkLogMapper;
import com.srs.workstudy.service.IQgzxPostService;
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.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
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-05-30
 */
@Service
public class QgzxPostServiceImpl extends ServiceImpl<QgzxPostMapper,QgzxPost> implements IQgzxPostService {
    @Autowired
    private QgzxPostMapper qgzxPostMapper;

    @Autowired
    private QgzxMoneyMapper _moneyMapper;

    @Autowired
    private QgzxStuPostMapper _stuPostMapper;

    @Autowired
    private QgzxWorkLogMapper _workLogMapper;

    @Autowired
    private SysDeptMapper _deptMapper;

    @Autowired
    private CphTeacherMapper _teacherMapper;
    @Autowired
    private QgzxTeacherMapper _qgzxteacherMapper;

    @Autowired
    private SysUserMapper _userMapper;


    @Autowired
    public PlatformTransactionManager transactionManager;


    @Override
    public AjaxResult countZzbldUnTodo(){
        try {
            Map<String, Object> data = new HashMap<>();
            QgzxPost qgzxPost = new QgzxPost();
            qgzxPost.applyStatus = "2";
            List<QgzxPost> list1 = qgzxPostMapper.listView(qgzxPost);
            data.put("post", list1.size());

            QgzxStuPost qgzxStuPost = new QgzxStuPost();
            qgzxStuPost.applyStatus = QgzxApplyStatus.INSTRUCTOR_APPROVED.getCode();
            List<QgzxStuPost> list2 = _stuPostMapper.listView(qgzxStuPost);
            data.put("stuPost", list2.size());

            QgzxMoney qgzxMoney = new QgzxMoney();
            qgzxMoney.applyStatus = "3";
            List<QgzxMoney> list3 = _moneyMapper.listView(qgzxMoney);
            data.put("money", list3.size());

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

    @Override
    public AjaxResult countZzbUnTodo(){
        try {
            Map<String, Object> data = new HashMap<>();

            QgzxMoney qgzxMoney = new QgzxMoney();
            qgzxMoney.applyStatus = "2";
            List<QgzxMoney> list3 = _moneyMapper.listView(qgzxMoney);
            data.put("money", list3.size());

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


    @Override
    public AjaxResult countZdlsUnTodo(String zdlsNo){
        try {
            Map<String, Object> data = new HashMap<>();

            QgzxStuPost qgzxStuPost = new QgzxStuPost();
            qgzxStuPost.setZdlsNo(zdlsNo);
            qgzxStuPost.applyStatus = QgzxApplyStatus.COUNSELOR_APPROVED.getCode();

            List<QgzxStuPost> list1 = _stuPostMapper.listView(qgzxStuPost);
            data.put("stuPost", list1.size());

            QgzxWorkLog qgzxWorkLog = new QgzxWorkLog();
            qgzxWorkLog.zdlsNo = zdlsNo;
            qgzxWorkLog.applyStatus = "1";

            List<QgzxWorkLog> list2 = _workLogMapper.listView(qgzxWorkLog);
            data.put("workLog", list2.size());

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


    @Override
    public AjaxResult countFdyUnTodo(String fdyNo){
        try {
            Map<String, Object> data = new HashMap<>();

            QgzxStuPost qgzxStuPost = new QgzxStuPost();
            qgzxStuPost.setFdyNo(fdyNo);
            qgzxStuPost.applyStatus = QgzxApplyStatus.SUBMITTED.getCode();

            List<QgzxStuPost> list = _stuPostMapper.listView(qgzxStuPost);
            data.put("stuPost", list.size());

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



    @Override
    public AjaxResult countDeptUnTodo(String deptName){
        try {
            Map<String, Object> data = new HashMap<>();
            QgzxPost qgzxPost = new QgzxPost();
            qgzxPost.setDeptName(deptName);
            qgzxPost.setApplyStatus("1");
            List<QgzxPost> list1 = qgzxPostMapper.listView(qgzxPost);
            data.put("post", list1.size());

            QgzxMoney qgzxMoney = new QgzxMoney();
            qgzxMoney.setDeptName(deptName);
            qgzxMoney.setApplyStatus("1");
            List<QgzxMoney> list2 = _moneyMapper.listView(qgzxMoney);
            data.put("money", list2.size());


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


    public AjaxResult manyAudit(List<QgzxPost> param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {

            List<Long> ids = param.stream().map(x -> x.id).collect(Collectors.toList());
            QueryWrapper<QgzxPost> query = new QueryWrapper<>();
            query.in("id", ids);
            List<QgzxPost> list = qgzxPostMapper.selectList(query);
            if (list.size() == 0) {
                throw new Exception("没有查询到记录");
            }

            if (Objects.equals(list.get(0).applyStatus, "1")) {
                param.forEach(x ->{
                    x.deptNo = getUsername();
                    x.deptTime = getNowDate();
                });
            }

            if (Objects.equals(list.get(0).applyStatus, "2")) {
                param.forEach(x -> {
                    x.highNo = getUsername();
                    x.highTime = getNowDate();
                });
            }

            boolean res = this.updateBatchById(param);
            if (!res) {
                throw new Exception("更新审核状态失败，刷新试试");
            }

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


    @Override
    public AjaxResult doReply(QgzxPost param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {

            QgzxPost oldRecord = qgzxPostMapper.selectById(param.id);//查询勤工助学旧记录

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

            QgzxPost.applyStatusDict replay = QgzxPost.applyStatusDict.Replay; // 重新提交的状态

            oldRecord.applyStatus = replay.getValue(); // 将旧纪录的状态改为 已重新提交

            int res1 = qgzxPostMapper.updateById(oldRecord); // 更新旧记录的状态
            if (res1 == 0) {
                throw new Exception("更新旧纪录状态失败");
            }

            QgzxPost needInsert = new QgzxPost(); // 重新提交的记录对象
            needInsert.applyStatus = "1";
            needInsert.postName = param.postName;
            needInsert.postType = param.postType;
            needInsert.postCount = param.postCount;
            needInsert.deptCode = param.deptCode;
            needInsert.fzrName = param.fzrName;
            needInsert.fzrNo = param.fzrNo;
            needInsert.zdlsNo = param.zdlsNo;
            needInsert.zdlsPhone = param.zdlsPhone;
            needInsert.willMoney = param.willMoney;
            needInsert.willMoneyTotal = param.willMoneyTotal;
            needInsert.workNeed = param.workNeed;
            needInsert.skillNeed = param.skillNeed;
            needInsert.weekTime = param.weekTime;
            needInsert.campusName = param.campusName;
            needInsert.workAddr = param.workAddr;
            needInsert.remark = param.remark;
            needInsert.applyNo = param.applyNo;
            needInsert.applyTime =getNowDate();
            needInsert.applyReason = param.applyReason;

            int res2 = qgzxPostMapper.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 AjaxResult doAudit(QgzxPost qgzxPost) {
        try {
            QgzxPost find = qgzxPostMapper.selectById(qgzxPost.id);
            if (find == null) {
                throw new Exception("该申请记录已被删除，刷新试试");
            }

            if (Objects.equals(find.applyStatus, "1")) {
                find.deptNo = getUsername();
                find.deptCmt = qgzxPost.deptCmt;
                find.deptSign = qgzxPost.deptSign;
                find.deptTime = getNowDate();
            }

            if (Objects.equals(find.applyStatus, "2")) {
                find.highNo = getUsername();
                find.highCmt = qgzxPost.highCmt;
                find.highSign = qgzxPost.highSign;
                find.highTime = getNowDate();
            }

            if (Objects.equals(qgzxPost.applyStatus, "11")) { // 驳回
                find.returnMsg = qgzxPost.returnMsg;
            }

            find.applyStatus = qgzxPost.applyStatus;


            int res = qgzxPostMapper.updateById(find);
            if (res == 0) {
                throw new Exception("更新审核状态失败");
            }

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



    @Override
    public AjaxResult getUserSign(Long uid){
        try{
            SysUser user = _userMapper.selectUserById(uid);
            return AjaxResult.success(user);
        }catch(Exception ex){
            return AjaxResult.error(ex.getMessage());
        }
    }




    @Override
    public List<QgzxPost> listView(QgzxPost param){
        return qgzxPostMapper.listView(param);
    }

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

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

            if(!Objects.equals(find.applyNo, getUsername())){
                throw new Exception("你是谁?");
            }

            int res = qgzxPostMapper.deleteQgzxPostById(id);
            if(res == 0){
                throw new Exception("删除记录失败");
            }

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




    @Override
    public AjaxResult doSave(QgzxPost param){
        try{
            SysDept dept = _deptMapper.selectById(param.deptId);
            if(dept == null){
                throw new Exception("部门不存在");
            }
            if(param.id != null){
                QgzxPost find = qgzxPostMapper.selectById(param.id);
                if(find == null){
                    throw new Exception("该记录不存在，刷新试试");
                }
            }

//            QueryWrapper<CphTeacher> fzrQuery = new QueryWrapper<>();
//            fzrQuery.eq("employee_id", param.fzrNo)
//                    .last("limit 1");
//            CphTeacher fzr = _teacherMapper.selectOne(fzrQuery);
                QueryWrapper<QgzxTeacher> fzrQuery = new QueryWrapper<>();
                fzrQuery.eq("employee_id", param.fzrNo)
                        .last("limit 1");
                QgzxTeacher fzr = _qgzxteacherMapper.selectOne(fzrQuery);
            if (fzr == null) {
                throw new Exception("负责人工号不存在");
            } else {
                param.fzrName = fzr.getName();
            }


            //由于指导老师不需要在创建岗位的时候填写 故以下判断作废
//            QueryWrapper<CphTeacher> zdlsQuery = new QueryWrapper<>();
//            zdlsQuery.eq("employee_id",param.zdlsNo)
//                    .last("limit 1");
//            CphTeacher zdls = _teacherMapper.selectOne(zdlsQuery);
//            if(zdls == null){
//                throw new Exception("指导老师工号不存在");
//            }else{
//                param.zdlsName = zdls.getName();
//            }

            param.setDeptCode(dept.getDeptCode());

            param.applyNo = getUsername();
            param.applyStatus = "0";
            param.applyTime =getNowDate();

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

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


    @Override
    public AjaxResult doApply(QgzxPost param){
        try{
            SysDept dept = _deptMapper.selectById(param.deptId);
            if(dept == null){
                throw new Exception("部门不存在");
            }
            if(param.id != null){
                QgzxPost find = qgzxPostMapper.selectById(param.id);
                if(find == null){
                    throw new Exception("该记录不存在，刷新试试");
                }
            }

//            QueryWrapper<CphTeacher> fzrQuery = new QueryWrapper<>();
//            fzrQuery.eq("employee_id", param.fzrNo)
//                    .last("limit 1");
//            CphTeacher fzr = _teacherMapper.selectOne(fzrQuery);
            QueryWrapper<QgzxTeacher> fzrQuery = new QueryWrapper<>();
            fzrQuery.eq("employee_id", param.fzrNo)
                    .last("limit 1");
            QgzxTeacher fzr = _qgzxteacherMapper.selectOne(fzrQuery);
            if (fzr == null) {
                throw new Exception("负责人工号不存在");
            } else {
                param.fzrName = fzr.getName();
            }
            //由于指导老师不需要在创建岗位的时候填写 故以下判断作废
//            QueryWrapper<CphTeacher> zdlsQuery = new QueryWrapper<>();
//            zdlsQuery.eq("employee_id",param.zdlsNo)
//                    .last("limit 1");
//            CphTeacher zdls = _teacherMapper.selectOne(zdlsQuery);
//            if(zdls == null){
//                throw new Exception("指导老师工号不存在");
//            }else{
//                param.zdlsName = zdls.getName();
//            }

            param.setDeptCode(dept.getDeptCode());

            param.applyNo = getUsername();
            param.applyStatus = "1";
            param.applyTime =getNowDate();

            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 QgzxPost selectQgzxPostById(Long id) {
        return qgzxPostMapper.selectQgzxPostById(id);
    }

    /**
     * 查询勤工助学岗位列表
     *
     * @param qgzxPost 勤工助学岗位
     * @return 勤工助学岗位
     */
    @Override
    public List<QgzxPost> selectQgzxPostList(QgzxPost qgzxPost) {
        return qgzxPostMapper.selectQgzxPostList(qgzxPost);
    }

    /**
     * 新增勤工助学岗位
     *
     * @param qgzxPost 勤工助学岗位
     * @return 结果
     */
    @Override
    public int insertQgzxPost(QgzxPost qgzxPost) {
                qgzxPost.setCreateTime(getNowDate());
            return qgzxPostMapper.insertQgzxPost(qgzxPost);
    }

    /**
     * 修改勤工助学岗位
     *
     * @param qgzxPost 勤工助学岗位
     * @return 结果
     */
    @Override
    public int updateQgzxPost(QgzxPost qgzxPost) {
                qgzxPost.setUpdateTime(getNowDate());
        return qgzxPostMapper.updateQgzxPost(qgzxPost);
    }

    /**
     * 批量删除勤工助学岗位
     *
     * @param ids 需要删除的勤工助学岗位主键
     * @return 结果
     */
    @Override
    public int deleteQgzxPostByIds(Long[] ids) {
        return qgzxPostMapper.deleteQgzxPostByIds(ids);
    }

    /**
     * 删除勤工助学岗位信息
     *
     * @param id 勤工助学岗位主键
     * @return 结果
     */
    @Override
    public int deleteQgzxPostById(Long id) {
        return qgzxPostMapper.deleteQgzxPostById(id);
    }
}
