package com.srs.workstudy.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.DateUtils;
import com.srs.workstudy.domain.QgzxPost;
import com.srs.workstudy.domain.QgzxStuPost;
import com.srs.workstudy.mapper.QgzxPostMapper;
import com.srs.workstudy.mapper.QgzxStuPostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.srs.workstudy.mapper.QgzxPostChangeMapper;
import com.srs.workstudy.domain.QgzxPostChange;
import com.srs.workstudy.service.IQgzxPostChangeService;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

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

/**
 * 勤工助学岗位修改人数Service业务层处理
 *
 * @author srs
 * @date 2024-09-11
 */
@Service
public class QgzxPostChangeServiceImpl extends ServiceImpl<QgzxPostChangeMapper, QgzxPostChange> implements IQgzxPostChangeService {
    @Autowired
    private QgzxPostChangeMapper qgzxPostChangeMapper;

    @Autowired
    private QgzxPostMapper _postMapper;

    @Autowired
    private QgzxStuPostMapper _stuPostMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;

    @Override
    public AjaxResult doAudit(QgzxPostChange param) {
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            QgzxPostChange find = qgzxPostChangeMapper.selectById(param.id); //查询申请记录
            if (find == null) {
                throw new Exception("该申请记录已被删除");
            }

            if (Objects.equals(param.applyStatus, QgzxPostChange.applyStatusDict.Dept.getValue()) ||
                    Objects.equals(param.applyStatus, QgzxPostChange.applyStatusDict.High.getValue())) {
                QueryWrapper<QgzxStuPost> query = new QueryWrapper<>();
                query.eq("apply_status", "4")
                        .eq("work_status", "是")
                        .eq("post_id", find.postId);
                Long res = _stuPostMapper.selectCount(query); //查询在岗人数

                if (res > find.newCount) {
                    throw new Exception("当前在岗人数大于修改后的人数，建议拒绝");
                }
            }

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

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

            find.applyStatus = param.applyStatus;

            int res = qgzxPostChangeMapper.updateById(find);

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

            if (Objects.equals(find.applyStatus, QgzxPostChange.applyStatusDict.High.getValue())) {
                QgzxPost post = _postMapper.selectById(find.postId);
                if (post == null) {
                    throw new Exception("该岗位不存在");
                }

                post.postCount = find.newCount.toString();

                int res1 = _postMapper.updateById(post);
                if (res1 == 0) {
                    throw new Exception("更新岗位设岗人数失败");
                }

            }

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


    @Override
    public AjaxResult cancelChange(Long id) {
        try {
            QgzxPostChange find = qgzxPostChangeMapper.selectQgzxPostChangeById(id);
            if (find == null) {
                throw new Exception("记录不存在");
            }

            if (!Objects.equals(find.applyStatus, QgzxPostChange.applyStatusDict.Submit.getValue())) {
                throw new Exception("该记录已被审核，不可取消");
            }

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

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


    @Override
    public AjaxResult doChange(QgzxPostChange param) {
        try {

            List<String> statusList = new ArrayList<>();
            statusList.add(QgzxPostChange.applyStatusDict.Submit.getValue());
            statusList.add(QgzxPostChange.applyStatusDict.Dept.getValue());

            QueryWrapper<QgzxPostChange> existQuery = new QueryWrapper<>();
            existQuery.in("apply_status", statusList)
                    .eq("post_id", param.postId);
            List<QgzxPostChange> existList = qgzxPostChangeMapper.selectList(existQuery);//查询未审核完成的记录

            if (existList.size() != 0) {
                throw new Exception("当前岗位存在未审核完成的修改设岗人数申请");
            }

            param.applyTime = getNowDate();
            param.applyStatus = QgzxPostChange.applyStatusDict.Submit.getValue();

            int res = qgzxPostChangeMapper.insert(param);
            if (res == 0) {
                throw new Exception("添加申请记录失败");
            }

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


    @Override
    public List<QgzxPostChange> listView(QgzxPostChange param) {
        return qgzxPostChangeMapper.listView(param);
    }


    /**
     * 查询勤工助学岗位修改人数
     *
     * @param id 勤工助学岗位修改人数主键
     * @return 勤工助学岗位修改人数
     */
    @Override
    public QgzxPostChange selectQgzxPostChangeById(Long id) {
        return qgzxPostChangeMapper.selectQgzxPostChangeById(id);
    }

    /**
     * 查询勤工助学岗位修改人数列表
     *
     * @param qgzxPostChange 勤工助学岗位修改人数
     * @return 勤工助学岗位修改人数
     */
    @Override
    public List<QgzxPostChange> selectQgzxPostChangeList(QgzxPostChange qgzxPostChange) {
        return qgzxPostChangeMapper.selectQgzxPostChangeList(qgzxPostChange);
    }

    /**
     * 新增勤工助学岗位修改人数
     *
     * @param qgzxPostChange 勤工助学岗位修改人数
     * @return 结果
     */
    @Override
    public int insertQgzxPostChange(QgzxPostChange qgzxPostChange) {
        qgzxPostChange.setCreateTime(getNowDate());
        return qgzxPostChangeMapper.insertQgzxPostChange(qgzxPostChange);
    }

    /**
     * 修改勤工助学岗位修改人数
     *
     * @param qgzxPostChange 勤工助学岗位修改人数
     * @return 结果
     */
    @Override
    public int updateQgzxPostChange(QgzxPostChange qgzxPostChange) {
        qgzxPostChange.setUpdateTime(getNowDate());
        return qgzxPostChangeMapper.updateQgzxPostChange(qgzxPostChange);
    }

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

    /**
     * 删除勤工助学岗位修改人数信息
     *
     * @param id 勤工助学岗位修改人数主键
     * @return 结果
     */
    @Override
    public int deleteQgzxPostChangeById(Long id) {
        return qgzxPostChangeMapper.deleteQgzxPostChangeById(id);
    }
}
