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.SysUser;
import com.srs.common.enums.QgzxApplyStatus;
import com.srs.comprehensive.domain.SrsStudent;
import com.srs.comprehensive.mapper.SrsStudentMapper;
import com.srs.system.mapper.SysUserMapper;
import com.srs.workstudy.domain.*;
import com.srs.workstudy.domain.dto.ManyMoney;
import com.srs.workstudy.domain.vo.DeptPostCount;
import com.srs.workstudy.mapper.*;
import com.srs.workstudy.service.IQgzxMoneyService;
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.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

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 srs
 * @date 2024-06-11
 */
@Service
public class QgzxMoneyServiceImpl extends ServiceImpl<QgzxMoneyMapper, QgzxMoney> implements IQgzxMoneyService {
    @Autowired
    private QgzxMoneyMapper qgzxMoneyMapper;

    @Autowired
    private QgzxWorkLogMapper _workLogMapper;

    @Autowired
    public PlatformTransactionManager transactionManager;

    @Autowired
    private SysUserMapper _userMapper;

    @Autowired
    private QgzxPostMapper _postMapper;

    @Autowired
    private QgzxStuPostMapper _stuPostMapper;

    @Autowired
    private QgzxMoneyExtraMapper _extraMapper;

    @Autowired
    private SrsStudentMapper _studentMapper;

    @Override
    public AjaxResult editMonth(QgzxMoney param){
        try{
            QgzxMoney money = qgzxMoneyMapper.selectById(param.getId());
            if(money == null){
                throw new Exception("结算月薪记录不存在");
            }

            money.applyTime = param.getApplyTime();

            int res = qgzxMoneyMapper.updateById(money);
            if(res != 1){
                throw new Exception("无修改");
            }

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

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

            Long stuPostId = param.stuPostId;

            QgzxStuPost stuPost = _stuPostMapper.selectById(stuPostId);

            if(stuPost == null){
                throw new Exception("学生岗位不存在");
            }

            Long postId = stuPost.getPostId();
            QgzxPost post = _postMapper.selectById(postId);
            if(post == null){
                throw new Exception("岗位不存在");
            }

            if(Objects.equals(post.postType, param.postType)){
                throw new Exception("修改的岗位类型不能与原岗位类型相同");
            }

            Long moneyId = param.id;
            QgzxMoney money = qgzxMoneyMapper.selectById(moneyId);
            if(money == null){
                throw new Exception("结算月薪记录不存在");
            }

            money.applyStatus = "15";
            money.finalCmt = "修改学生岗位类型以及月工时";

            int res1 = qgzxMoneyMapper.updateById(money);
            if(res1 != 1){
                throw new Exception("更新旧记录状态失败");
            }

            SysUser user = _userMapper.selectUserById(getUserId());
            if (user.getSignature() == null || Objects.equals(user.getSignature(), "")) {
                throw new Exception("您的签名未上传");
            }

            QgzxMoneyExtra extra = new QgzxMoneyExtra();
            extra.applyTime = getNowDate();
            extra.stuNo = stuPost.stuNo;
            extra.postName = post.postName;
            extra.deptCode = post.deptCode;
            extra.postType = param.postType;
            extra.zdlsNo = stuPost.getZdlsNo();
            extra.totalTime = param.totalTime;
            extra.familyCondition = stuPost.familyCondition;
            extra.auditRemark = "-资助办领导手动添加-";
            String finalSign = user.getSignature();
            extra.finalSign = finalSign;
            SysUser zdls = _userMapper.selectUserByUserName(stuPost.getZdlsNo());
            if (zdls == null) {
                throw new Exception("找不到指导老师");
            }
            if (zdls.getSignature() == null || Objects.equals(zdls.getSignature(), "")) {
                throw new Exception("指导老师签名未上传");
            }
            extra.zdlsSign = zdls.getSignature();
            extra.finalTime = getNowDate();
            extra.bankCard = stuPost.bankCard;
            extra.bankAddr = stuPost.bankAddr;
            extra.workNeed = post.workNeed;
            extra.applyTime = money.applyTime;
            extra.applyStatus = "6";
            extra.finalNo = getUsername();

            int res2 = _extraMapper.insert(extra);
            if(res2 != 1){
                throw new Exception("插入新记录失败");
            }

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

    @Override
    public AjaxResult checkDeptAll(QgzxMoney param){
        try{
            StringBuilder msg = new StringBuilder();
            boolean hasNot = false;
            List<QgzxMoney> moneyList = qgzxMoneyMapper.listOld(param);

            QgzxPost postQuery = new QgzxPost();
            postQuery.setDeptName(param.getDeptName());
            postQuery.setApplyStatus("3");
            List<QgzxPost> postList = _postMapper.listView(postQuery);
            for(QgzxPost post : postList){
                QueryWrapper<QgzxStuPost> stuPostQuery = new QueryWrapper<>();
                stuPostQuery.eq("post_id", post.getId())
                       .eq("apply_status",4)
                        .eq("work_status","是");
                List<QgzxStuPost> stuPostList = _stuPostMapper.selectList(stuPostQuery);
                if(stuPostList.size() != 0){
                    List<QgzxMoney> moneyList1 = moneyList.stream().filter(x->x.postId.equals(post.getId())).collect(Collectors.toList());
                    if(moneyList1.size() != stuPostList.size()){
                        msg.append(post.getPostName()).append("岗位有").append(stuPostList.size() - moneyList1.size()).append("名学生的薪资未填报；");
                        hasNot = true;
                    }
                }
            }
            if(hasNot) {
                throw new Exception(msg.toString());
            }

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


    @Override
    public AjaxResult zzbOneClickAudit(){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            SysUser user = _userMapper.selectUserById(getUserId());
            if (user.getSignature() == null || Objects.equals(user.getSignature(), "")) {
                throw new Exception("您的签名未上传");
            }

            String finalSign = user.getSignature();
            QueryWrapper<QgzxMoney> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("apply_status", 2);
            List<QgzxMoney> moneyList = qgzxMoneyMapper.selectList(queryWrapper);
            if (moneyList.size() == 0) {
                return AjaxResult.success("没有需要审核的记录");
            }

            moneyList.forEach(x -> {
                x.applyStatus = QgzxMoney.applyStatusDict.High.getValue();
                x.highNo = getUsername();
                x.highTime = getNowDate();
                x.highCmt = "同意";
                x.highSign = finalSign;
            });

            boolean res = this.updateBatchById(moneyList);
            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 oneClickAudit(){
        TransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transactionManager.getTransaction(def);
        try{
            SysUser user = _userMapper.selectUserById(getUserId());
            if (user.getSignature() == null || Objects.equals(user.getSignature(), "")) {
                throw new Exception("您的签名未上传");
            }

            String finalSign = user.getSignature();
            QueryWrapper<QgzxMoney> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("apply_status", 3);
            List<QgzxMoney> moneyList = qgzxMoneyMapper.selectList(queryWrapper);
            if (moneyList.size() == 0) {
                return AjaxResult.success("没有需要审核的记录");
            }

            moneyList.forEach(x -> {
                x.applyStatus = QgzxMoney.applyStatusDict.Final.getValue();
                x.finalNo = getUsername();
                x.finalTime = getNowDate();
                x.finalCmt = "同意";
                x.finalSign = finalSign;
            });

            boolean res = this.updateBatchById(moneyList);
            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 zzbldEdit( QgzxMoney param){
        try{
             QgzxMoney oldRecord = qgzxMoneyMapper.selectById(param.getId());

            if (oldRecord == null) {
                throw new Exception("记录不存在");
            }

            oldRecord.totalTime = param.totalTime;

            int res = qgzxMoneyMapper.updateById(oldRecord);
            if (res == 0) {
                throw new Exception("更新记录失败");
            }

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



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

            QgzxMoney oldRecord = qgzxMoneyMapper.selectById(param.getId());

            if (oldRecord == null) {
                throw new Exception("旧记录不存在");
            }

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

            oldRecord.applyStatus = QgzxMoney.applyStatusDict.Replay.getValue();

            int res = qgzxMoneyMapper.updateById(oldRecord);
            if (res == 0) {
                throw new Exception("更新旧纪录状态失败");
            }

            QgzxMoney newRecord = new QgzxMoney();
            newRecord.setStuPostId(param.getStuPostId());
            newRecord.setApplyNo(getUsername());

            BigDecimal time = param.totalTime;

            if (time.compareTo(new BigDecimal("40")) > 0) {
                time = new BigDecimal("40");
            }

            if (time.compareTo(new BigDecimal("0")) == 0) {
                throw new Exception("工作总时长为0");
            }

            newRecord.totalTime = time;
            newRecord.applySign = param.applySign;
            newRecord.applyStatus = QgzxMoney.applyStatusDict.Submit.getValue();
            newRecord.applyTime = oldRecord.applyTime;

            int res1 = qgzxMoneyMapper.insert(newRecord);
            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 List<DeptPostCount> listCount() {
        return qgzxMoneyMapper.listCount();
    }


    @Override
    public AjaxResult finalDeptAudit(List<String> deptCodes, String applyStatus) {
        try {

            SysUser user = _userMapper.selectUserById(getUserId());
            if (user.getSignature() == null || Objects.equals(user.getSignature(), "")) {
                throw new Exception("您的签名未上传");
            }

            String finalSign = user.getSignature();
            String finalNo = getUsername();

            QueryWrapper<QgzxPost> postQuery = new QueryWrapper<>();
            postQuery.eq("apply_status", 3)
                    .in("dept_code", deptCodes);
            List<QgzxPost> postList = _postMapper.selectList(postQuery);
            if (postList.size() == 0) {
                throw new Exception("该部门岗位数量为0");
            }

            List<Long> postIds = postList.stream().map(x -> x.id).collect(Collectors.toList());

            QueryWrapper<QgzxStuPost> stuPostQuery = new QueryWrapper<>();
            stuPostQuery.in("post_id", postIds)
                    .eq("apply_status", QgzxApplyStatus.CENTER_OPINION.getCode())
                    .eq("work_status", "是");
            List<QgzxStuPost> stuPostList = _stuPostMapper.selectList(stuPostQuery);

            if (stuPostList.size() == 0) {
                throw new Exception("学工岗位数量为0");
            }

            List<Long> stuPostIds = stuPostList.stream().map(x -> x.id).collect(Collectors.toList());

            QueryWrapper<QgzxMoney> moneyQuery = new QueryWrapper<>();
            moneyQuery.in("stu_post_id", stuPostIds)
                    .eq("apply_status", 3);

            List<QgzxMoney> moneyList = qgzxMoneyMapper.selectList(moneyQuery);
            if (moneyList.size() == 0) {
                throw new Exception("待审核数量为0");
            }

            for (QgzxMoney x : moneyList) {
                x.applyStatus = applyStatus;
                if (Objects.equals(applyStatus, "6")) {
                    x.finalCmt = "同意";
                    x.finalTime = getNowDate();
                }
                if (Objects.equals(applyStatus, "10")) {
                    x.finalCmt = "拒绝";
                    x.finalTime = getNowDate();
                }
                x.finalSign = finalSign;
                x.finalNo = finalNo;
            }

            boolean res = this.updateBatchById(moneyList);
            if (!res) {
                throw new Exception("批量更新审核状态失败");
            }

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

    @Override
    public AjaxResult highDeptAudit(List<String> deptCodes, String applyStatus) {
        try {

            SysUser user = _userMapper.selectUserById(getUserId());
            if (user.getSignature() == null || Objects.equals(user.getSignature(), "")) {
                throw new Exception("您的签名未上传");
            }

            String highSign = user.getSignature();
            String highNo = getUsername();

            QueryWrapper<QgzxPost> postQuery = new QueryWrapper<>();
            postQuery.eq("apply_status", 3)
                    .in("dept_code", deptCodes);
            List<QgzxPost> postList = _postMapper.selectList(postQuery);
            if (postList.size() == 0) {
                throw new Exception("该部门岗位数量为0");
            }

            List<Long> postIds = postList.stream().map(x -> x.id).collect(Collectors.toList());

            QueryWrapper<QgzxStuPost> stuPostQuery = new QueryWrapper<>();
            stuPostQuery.in("post_id", postIds)
                    .eq("apply_status", QgzxApplyStatus.CENTER_OPINION.getCode())
                    .eq("work_status", "是");
            List<QgzxStuPost> stuPostList = _stuPostMapper.selectList(stuPostQuery);

            if (stuPostList.size() == 0) {
                throw new Exception("学工岗位数量为0");
            }

            List<Long> stuPostIds = stuPostList.stream().map(x -> x.id).collect(Collectors.toList());

            QueryWrapper<QgzxMoney> moneyQuery = new QueryWrapper<>();
            moneyQuery.in("stu_post_id", stuPostIds)
                    .eq("apply_status", 2);

            List<QgzxMoney> moneyList = qgzxMoneyMapper.selectList(moneyQuery);
            if (moneyList.size() == 0) {
                throw new Exception("待审核数量为0");
            }

            for (QgzxMoney x : moneyList) {
                x.applyStatus = applyStatus;
                if (Objects.equals(applyStatus, "3")) {
                    x.highCmt = "同意";
                    x.highTime = getNowDate();
                }
                if (Objects.equals(applyStatus, "10")) {
                    x.highCmt = "拒绝";
                    x.highTime = getNowDate();
                }
                x.highSign = highSign;
                x.highNo = highNo;
            }

            boolean res = this.updateBatchById(moneyList);
            if (!res) {
                throw new Exception("批量更新审核状态失败");
            }

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


    @Override
    public List<DeptPostCount> listAuditByDept(QgzxMoney param) {
        return qgzxMoneyMapper.listAuditByDept(param);
    }


    @Override
    public AjaxResult doMany(ManyMoney param) {
        try {

            List<Long> stuPostIds = param.stuPostIds;
            Date month = param.month;
            SysUser user = _userMapper.selectUserById(getUserId());
            if (user.getSignature() == null || Objects.equals(user.getSignature(), "")) {
                throw new Exception("您的签名未上传");
            }

            String applySign = user.getSignature();

            String applyNo = getUsername();

            //LocalDate now = getNowDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate now = month.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());

            StringBuilder msg = new StringBuilder();
            msg.append("操作成功;");

            for (Long stuPostId : stuPostIds) {
                QgzxStuPost stuPost = _stuPostMapper.selectById(stuPostId);
                SrsStudent student = _studentMapper.selectSrsStudentByStuNo(stuPost.getStuNo());
                if (student == null) {
                    msg.append("记录编号为").append(stuPostId).append("号的学生信息不存在;");
                    continue;
                }
                List<String> notApplyStatus = Arrays.asList("10", "14");
                QueryWrapper<QgzxMoney> queryWrapper = new QueryWrapper<>();
                queryWrapper
                        .eq("stu_post_id", stuPostId)
                        .ge("apply_time", firstDayOfMonth)
                        .lt("apply_time", firstDayOfNextMonth)
                        .notIn("apply_status", notApplyStatus);
                List<QgzxMoney> findList = qgzxMoneyMapper.selectList(queryWrapper);
                if (!findList.isEmpty()) {
                    msg.append("学生 ").append(student.getName()).append(" 本月结算过一次了;");
                    continue;
                }

                BigDecimal time = new BigDecimal("0");

                QueryWrapper<QgzxWorkLog> logQuery = new QueryWrapper<>();
                logQuery.eq("stu_post_id", stuPostId)
                        .eq("apply_status", "2")
                        .ge("work_date", firstDayOfMonth)
                        .lt("work_date", firstDayOfNextMonth);

                List<QgzxWorkLog> list = _workLogMapper.selectList(logQuery);

                for (QgzxWorkLog log : list) {
                    time = time.add(log.workTime);
                }

                if (time.compareTo(new BigDecimal("40")) > 0) {
                    time = new BigDecimal("40");
                }

                if (time.compareTo(new BigDecimal("0")) == 0) {
                    msg.append("学生 ").append(student.getName()).append(" 本月工作总时长为0;");
                    continue;
                }
                QgzxMoney qgzxMoney = new QgzxMoney();
                qgzxMoney.stuPostId = stuPostId;
                qgzxMoney.applySign = applySign;
                qgzxMoney.totalTime = time;

                qgzxMoney.applyNo = applyNo;
                qgzxMoney.applyTime = month;
                qgzxMoney.applyStatus = "1";

                int res = qgzxMoneyMapper.insert(qgzxMoney);

                if (res == 0) {
                    msg.append("学生 ").append(student.getName()).append(" 填报月薪记录失败");
                }
            }
            String res = msg.toString();
            return AjaxResult.success(res);
        } catch (Exception ex) {
            return AjaxResult.error(ex.getMessage());
        }
    }


    @Override
    public Map<String, Object> countUnMoney(QgzxMoney param) {
        return qgzxMoneyMapper.countUnMoney(param);
    }


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

            List<Long> ids = param.stream().map(x -> x.id).collect(Collectors.toList());
            QueryWrapper<QgzxMoney> query = new QueryWrapper<>();
            query.in("id", ids);
            List<QgzxMoney> list = qgzxMoneyMapper.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();
                });
            }

            if (Objects.equals(list.get(0).applyStatus, "3")) {
                param.forEach(x -> {
                    x.finalNo = getUsername();
                    x.finalTime = 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 doAudit(QgzxMoney param) {
        try {
            QgzxMoney find = qgzxMoneyMapper.selectById(param.id);
            if (find == null) {
                throw new Exception("该申请记录已被删除，刷新试试");
            }

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

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

            if (Objects.equals(find.applyStatus, "3")) {
                find.finalNo = getUsername();
                find.finalTime = getNowDate();
                find.finalCmt = param.finalCmt;
                find.finalSign = param.finalSign;
            }

            find.applyStatus = param.applyStatus;

            if (Objects.equals(param.applyStatus, QgzxMoney.applyStatusDict.Return.getValue())) {
                find.auditRemark = param.auditRemark;
            }

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

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

    @Override
    public List<QgzxMoney> listView(QgzxMoney param) {
        return qgzxMoneyMapper.listView(param);
    }


    @Override
    public AjaxResult cancelApply(Long id) {
        try {
            QgzxMoney find = qgzxMoneyMapper.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.applyNo, getUsername())) {
                throw new Exception("不是本人");
            }

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

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

    @Override
    public AjaxResult zzbldAdd(QgzxMoney param){
        try{
            LocalDate now = param.applyTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());

            QueryWrapper<QgzxMoney> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq("stu_post_id", param.stuPostId)
                    .ge("apply_time", firstDayOfMonth)
                    .lt("apply_time", firstDayOfNextMonth)
                    .ne("apply_status", "10");

            List<QgzxMoney> findList = qgzxMoneyMapper.selectList(queryWrapper);
            if (findList.size() != 0) {
                throw new Exception("当月结算过一次了");
            }

            QgzxStuPost stuPost = _stuPostMapper.selectById(param.stuPostId);
            if (stuPost == null) {
                throw new Exception("学生岗位不存在");
            }

            param.applyNo = stuPost.getZdlsNo();
            param.finalNo = getUsername();
            param.finalTime = getNowDate();
            param.finalCmt = "同意";

            param.applyStatus = "6";

            int res = qgzxMoneyMapper.insert(param);

            if (res == 0) {
                throw new Exception("添加记录失败");
            }

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

    @Override
    public List<QgzxStuPost> listTeacherCanSelectPostAndMonthTime(QgzxStuPost param){
        List<QgzxStuPost> list1 = _stuPostMapper.listView(param);
        LocalDate now = param.manyApplyTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

        LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());
        list1.forEach(x->{
            BigDecimal time = new BigDecimal("0");

            QueryWrapper<QgzxWorkLog> logQuery = new QueryWrapper<>();
            logQuery.eq("stu_post_id", x.id)
                    .eq("apply_status", "2")
                    .ge("work_date", firstDayOfMonth)
                    .lt("work_date", firstDayOfNextMonth);

            List<QgzxWorkLog> list = _workLogMapper.selectList(logQuery);

            for (QgzxWorkLog log : list) {
                time = time.add(log.workTime);
            }

            if (time.compareTo(new BigDecimal("40")) > 0) {
                time = new BigDecimal("40");
            }
            x.setTotalTime(time);
        });
        return list1;
    }

    @Override
    public Map<String, Object> computeMonthTime(QgzxMoney param){
        try{
            LocalDate now = param.applyTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());

            BigDecimal time = new BigDecimal("0");

            QueryWrapper<QgzxWorkLog> logQuery = new QueryWrapper<>();
            logQuery.eq("stu_post_id", param.getStuPostId())
                    .eq("apply_status", "2")
                    .ge("work_date", firstDayOfMonth)
                    .lt("work_date", firstDayOfNextMonth);

            List<QgzxWorkLog> list = _workLogMapper.selectList(logQuery);

            for (QgzxWorkLog log : list) {
                time = time.add(log.workTime);
            }

            if (time.compareTo(new BigDecimal("40")) > 0) {
                time = new BigDecimal("40");
            }

            if (time.compareTo(new BigDecimal("0")) == 0) {
                throw new Exception("工作总时长为0");
            }
            Map<String, Object> result = new HashMap<>();
            result.put("totalTime", time);
            return result;
        }catch (Exception ex){
            return new HashMap<>();
        }

    }


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

            //LocalDate now = getNowDate().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate now = param.applyTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            LocalDate firstDayOfMonth = now.with(TemporalAdjusters.firstDayOfMonth());
            LocalDate firstDayOfNextMonth = now.with(TemporalAdjusters.firstDayOfNextMonth());

            List<String> notApplyStatus = Arrays.asList("10", "14");
            QueryWrapper<QgzxMoney> queryWrapper = new QueryWrapper<>();
            queryWrapper
                    .eq("stu_post_id", param.stuPostId)
                    .ge("apply_time", firstDayOfMonth)
                    .lt("apply_time", firstDayOfNextMonth)
                    .notIn("apply_status", notApplyStatus);

            List<QgzxMoney> findList = qgzxMoneyMapper.selectList(queryWrapper);
            if (findList.size() != 0) {
                throw new Exception("本月结算过一次了");
            }

            BigDecimal time = new BigDecimal("0");

            QueryWrapper<QgzxWorkLog> logQuery = new QueryWrapper<>();
            logQuery.eq("stu_post_id", param.getStuPostId())
                    .eq("apply_status", "2")
                    .ge("work_date", firstDayOfMonth)
                    .lt("work_date", firstDayOfNextMonth);

            List<QgzxWorkLog> list = _workLogMapper.selectList(logQuery);

            for (QgzxWorkLog log : list) {
                time = time.add(log.workTime);
            }

            if (time.compareTo(new BigDecimal("40")) > 0) {
                time = new BigDecimal("40");
            }

            if (time.compareTo(new BigDecimal("0")) == 0) {
                throw new Exception("工作总时长为0");
            }

            param.totalTime = time;

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

            int res = qgzxMoneyMapper.insert(param);

            if (res == 0) {
                throw new Exception("添加记录失败");
            }

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


    /**
     * 查询勤工助学薪资填报
     *
     * @param id 勤工助学薪资填报主键
     * @return 勤工助学薪资填报
     */
    @Override
    public QgzxMoney selectQgzxMoneyById(Long id) {
        return qgzxMoneyMapper.selectQgzxMoneyById(id);
    }

    /**
     * 查询勤工助学薪资填报列表
     *
     * @param qgzxMoney 勤工助学薪资填报
     * @return 勤工助学薪资填报
     */
    @Override
    public List<QgzxMoney> selectQgzxMoneyList(QgzxMoney qgzxMoney) {
        return qgzxMoneyMapper.selectQgzxMoneyList(qgzxMoney);
    }

    /**
     * 新增勤工助学薪资填报
     *
     * @param qgzxMoney 勤工助学薪资填报
     * @return 结果
     */
    @Override
    public int insertQgzxMoney(QgzxMoney qgzxMoney) {
        return qgzxMoneyMapper.insertQgzxMoney(qgzxMoney);
    }

    /**
     * 修改勤工助学薪资填报
     *
     * @param qgzxMoney 勤工助学薪资填报
     * @return 结果
     */
    @Override
    public int updateQgzxMoney(QgzxMoney qgzxMoney) {
        return qgzxMoneyMapper.updateQgzxMoney(qgzxMoney);
    }

    /**
     * 批量删除勤工助学薪资填报
     *
     * @param ids 需要删除的勤工助学薪资填报主键
     * @return 结果
     */
    @Override
    public int deleteQgzxMoneyByIds(Long[] ids) {
        return qgzxMoneyMapper.deleteQgzxMoneyByIds(ids);
    }

    /**
     * 删除勤工助学薪资填报信息
     *
     * @param id 勤工助学薪资填报主键
     * @return 结果
     */
    @Override
    public int deleteQgzxMoneyById(Long id) {
        return qgzxMoneyMapper.deleteQgzxMoneyById(id);
    }
}
