package com.mosty.rwzx.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mosty.base.model.dto.qwzx.TbQwJlDto;
import com.mosty.base.model.dto.qwzx.TbQwXfbbVo;
import com.mosty.base.model.dto.rwzx.*;
import com.mosty.base.model.entity.qwzx.TbQwJl;
import com.mosty.base.model.entity.rwzx.TbRwTask;
import com.mosty.base.model.entity.rwzx.TbRwTaskLog;
import com.mosty.base.model.entity.rwzx.TbRwTaskUser;
import com.mosty.base.model.entity.rwzx.TbRwTaskUserAll;
import com.mosty.base.model.entity.yjzl.TbZlxx;
import com.mosty.base.model.query.rwzx.*;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.jcgl.TbJcglDsfVo;
import com.mosty.base.model.vo.rwzx.*;
import com.mosty.base.utils.*;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.config.entity.SysDictItem;
import com.mosty.common.core.business.entity.SysUser;
import com.mosty.common.core.business.entity.vo.SysUserDeptVO;
import com.mosty.common.core.business.entity.vo.SysUserVO;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.rwzx.mapper.TbRwTaskUserAllMapper;
import com.mosty.rwzx.remote.TbBaseAdaptRemoteService;
import com.mosty.rwzx.mapper.TbRwTaskLogMapper;
import com.mosty.rwzx.mapper.TbRwTaskMapper;
import com.mosty.rwzx.mapper.TbRwTaskUserMapper;
import com.mosty.rwzx.remote.TbJcglAdaptRemoteService;
import com.mosty.rwzx.remote.TbQwzxAdaptRemoteService;
import com.mosty.rwzx.service.TbRwTaskService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class TbRwTaskServiceImpl extends ServiceImpl<TbRwTaskMapper, TbRwTask> implements TbRwTaskService {

    private final TbRwTaskMapper tbRwTaskMapper;
    private final TbRwTaskLogMapper tbRwTaskLogMapper;
    private final TbRwTaskUserMapper tbRwTaskUserMapper;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbJcglAdaptRemoteService tbJcglAdaptRemoteService;
    private final TbQwzxAdaptRemoteService tbQwzxAdaptRemoteService;
    private final TbRwTaskUserAllMapper tbRwTaskUserAllMapper;


    @Override
    @Transactional
    public int addRw(TbRwTaskDto dto) {
        TbRwTask task = new TbRwTask();
        BeanUtils.copyProperties(dto, task);
        task.setId(UUIDGenerator.getUUID());
        task.setRwfqsj(new Date());
        task.setRwzt("0");
        task.setRwjxzt("1");
        task.setCjrid(dto.getCjrid());
        task.setCjrxm(dto.getCjrxm());
        task.setCjrsfzh(dto.getCjrsfzh());
        task.setCjrlxdh("");
        DeptInfoVo dept;
        dept = this.tbBaseAdaptRemoteService.getOrgByDeptId(dto.getSsbmid());
        if (dept != null) {
            task.setSsbmid(dept.getDeptid());
            task.setSsbm(dept.getDeptname());
            task.setSsbmdm(dept.getDeptcode());
            task.setSsxgajid(dept.getFxjid());
            task.setSsxgaj(dept.getFxjname());
            task.setSsxgajdm(dept.getFxjcode());
            task.setSssgajid(dept.getDszid());
            task.setSssgaj(dept.getDszname());
            task.setSssgajdm(dept.getDszcode());
        }
        task.setXtSjly("1");
        // 保存任务接收人信息
        List<TbRwTaskUserDto> userDtoList = dto.getUserDtoList();
        if (CollectionUtils.isEmpty(userDtoList)) {
            throw new BusinessException("请至少选择一个人员接收任务！！");
        }
        // TODO 计算任务接收人数量
        userDtoList.forEach(item -> {
            TbRwTaskUser taskUser = new TbRwTaskUser();
            BeanUtils.copyProperties(task, taskUser);
            taskUser.setId(UUIDGenerator.getUUID());
            taskUser.setRwid(task.getId());
            taskUser.setGrrwzt("0");
            taskUser.setRwid(task.getId());
            taskUser.setRwjsdx(task.getRwjsdx());
            taskUser.setRwzflx("1");
            taskUser.setJsrid(item.getJsrid());
            taskUser.setJsrlxdh(item.getJsrlxdh());
            taskUser.setJsrmc(item.getJsrmc());
            taskUser.setJsrsfzh(item.getJsrsfzh());
            taskUser.setJsxzmc(item.getJsxzmc());
            taskUser.setJsxzid(item.getJsxzid());
            taskUser.setJsbmdm(item.getJsbmdm());
            taskUser.setJsbmmc(item.getJsbmmc());
            DeptInfoVo userDept = null;
            if ("01".equals(dto.getRwjsdx())) {
                userDept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(item.getJsrid());
            } else if ("02".equals(dto.getRwjsdx())) {
                userDept = this.tbBaseAdaptRemoteService.getOrgByDeptId(item.getJsbmdm());
                taskUser.setJsbmmc(userDept.getDeptname());
            } else if ("03".equals(dto.getRwjsdx())) {
                TbQwXfbbVo bb = this.tbQwzxAdaptRemoteService.getBbInfo(item.getJsxzid());
                if (bb != null) {
                    taskUser.setJsxzmc(bb.getJzMc());
                    userDept = this.tbBaseAdaptRemoteService.getOrgByDeptId(bb.getSsbmid());
                }
            }
            if (userDept != null) {
                taskUser.setSsbmid(userDept.getDeptid());
                taskUser.setSsbm(userDept.getDeptname());
                taskUser.setSsbmdm(userDept.getDeptcode());
                taskUser.setSsxgajid(userDept.getFxjid());
                taskUser.setSsxgaj(userDept.getFxjname());
                taskUser.setSsxgajdm(userDept.getFxjcode());
                taskUser.setSssgajid(userDept.getDszid());
                taskUser.setSssgaj(userDept.getDszname());
                taskUser.setSssgajdm(userDept.getDszcode());
                taskUser.setXtSjly("1");
            }
            this.tbRwTaskUserMapper.insert(taskUser);
            // 保存所有任务
            TbRwTaskUserAll userAll = new TbRwTaskUserAll();
            BeanUtils.copyProperties(taskUser, userAll);
            this.tbRwTaskUserAllMapper.insert(userAll);
        });
        // 保存任务日志
        TbRwTaskLog log = new TbRwTaskLog();
        log.setId(UUIDGenerator.getUUID());
        log.setRwid(task.getId());
        log.setRzlx("09");
        log.setRznr(DateUtils.getQueryDateString(new Date(), "02") + "," + task.getCjrxm() + "发送了该任务。");
        log.setBgrid(task.getCjrid());
        log.setBgsj(new Date());
        log.setBgrdhhm(task.getCjrlxdh());
        log.setBgrsfzh(task.getCjrsfzh());
        log.setBgrxm(task.getCjrxm());
        if (dept != null) {
            log.setSsbmid(dept.getDeptid());
            log.setSsbm(dept.getDeptname());
            log.setSsbmdm(dept.getDeptcode());
            log.setSsxgajid(dept.getFxjid());
            log.setSsxgaj(dept.getFxjname());
            log.setSsxgajdm(dept.getFxjcode());
            log.setSssgajid(dept.getDszid());
            log.setSssgaj(dept.getDszname());
            log.setSssgajdm(dept.getDszcode());
        }
        log.setXtSjly("1");
        this.tbRwTaskLogMapper.insertEntity(log);
        return this.baseMapper.insert(task);
    }

    @Override
    public TbRwTaskVo getTaskInfo(String id) {
        UserInfo userInfo = UserInfoManager.get();
        List<TbRwTaskUser> userList = this.tbRwTaskUserMapper.selectList(
                new LambdaQueryWrapper<TbRwTaskUser>()
                        .eq(TbRwTaskUser::getRwid, id)
                        .eq(TbRwTaskUser::getXtSjzt, "1")
        );
        if (userList != null && userList.size() > 0) {
            List<TbRwTaskUserVo> voList = new ArrayList<>();
            userList.forEach(item -> {
                TbRwTaskUserVo userVo = new TbRwTaskUserVo();
                BeanUtils.copyProperties(item, userVo);
                voList.add(userVo);
            });
            TbRwTaskVo vo = new TbRwTaskVo();
            BeanUtils.copyProperties(userList.get(0), vo);
            vo.setUserDtoList(voList);
            return vo;
        }
        return null;
    }

    @Override
    public IPage<TbRwTaskUserVo> getTaskUserList(TbRwTaskUserQuery dto) {
        IPage<TbRwTaskUser> userPage = this.tbRwTaskUserMapper.selectPage(
                new Page<>(dto.getPageCurrent(), dto.getPageSize()),
                new LambdaQueryWrapper<TbRwTaskUser>()
                        .eq(!StringUtils.isEmpty(dto.getRwid()), TbRwTaskUser::getRwid, dto.getRwid())
                        .eq(!StringUtils.isEmpty(dto.getRwzt()), TbRwTaskUser::getRwzt, dto.getRwzt())
                        .like(!StringUtils.isEmpty(dto.getJsrmc()), TbRwTaskUser::getJsrmc, dto.getJsrmc())
                        .eq(!StringUtils.isEmpty(dto.getSsbmdm()), TbRwTaskUser::getSsbmdm, dto.getSsbmdm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmid()), TbRwTaskUser::getSsbmid, dto.getSsbmid()));
        List<TbRwTaskUserVo> voList = new ArrayList<>();
        userPage.getRecords().forEach(item -> {
            TbRwTaskUserVo vo = new TbRwTaskUserVo();
            BeanUtils.copyProperties(item, vo);
            voList.add(vo);
        });
        IPage<TbRwTaskUserVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page.setRecords(voList);
        page.setTotal(userPage.getTotal());
        return page;
    }

    @Override
    public IPage<TbRwTaskLogVo> getTaskLogList(TbRwTaskLogQuery dto) {
        IPage<TbRwTaskLog> userPage = this.tbRwTaskLogMapper.selectPage(
                new Page<>(dto.getPageCurrent(), dto.getPageSize()),
                new LambdaQueryWrapper<TbRwTaskLog>()
                        .eq(!StringUtils.isEmpty(dto.getRwid()), TbRwTaskLog::getRwid, dto.getRwid())
                        .eq(!StringUtils.isEmpty(dto.getRzlx()), TbRwTaskLog::getRzlx, dto.getRzlx())
                        .like(!StringUtils.isEmpty(dto.getRznr()), TbRwTaskLog::getRznr, dto.getRznr())
                        .like(!StringUtils.isEmpty(dto.getBgrxm()), TbRwTaskLog::getBgrxm, dto.getBgrxm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmdm()), TbRwTaskLog::getSsbmdm, dto.getSsbmdm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmid()), TbRwTaskLog::getSsbmid, dto.getSsbmid()));
        List<TbRwTaskLogVo> voList = new ArrayList<>();
        userPage.getRecords().forEach(item -> {
            TbRwTaskLogVo vo = new TbRwTaskLogVo();
            BeanUtils.copyProperties(item, vo);
            voList.add(vo);
        });
        IPage<TbRwTaskLogVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page.setRecords(voList);
        page.setTotal(userPage.getTotal());
        return page;
    }

    @Override
    public TbRwTaskStatisticsVo getDataStatistics(TbRwTaskStatisticsDto dto) {
        Date d = null;
        if (!StringUtils.isEmpty(dto.getDateType())) {
            if ("1".equals(dto.getDateType())) {
                d = new Date();
            } else if ("2".equals(dto.getDateType())) {
                d = DateUtils.getNextDate(new Date(), "D", -7);
            } else {
                d = DateUtils.getNextDate(new Date(), "M", -1);
            }
        }
        TbRwTaskStatisticsVo vo = new TbRwTaskStatisticsVo();
        //总任务数
        Integer all = this.baseMapper.getCount("", d, dto.getSfzh());
        //进行中
        Integer jxz = this.baseMapper.getCount("1", d, dto.getSfzh());
        //超期进行中
        Integer cqjxz = this.baseMapper.getCount("2", d, dto.getSfzh());
        //已完成
        Integer ywc = this.baseMapper.getCount("3", d, dto.getSfzh());
        //超期完成
        Integer cqwc = this.baseMapper.getCount("4", d, dto.getSfzh());
        //超期未完成
        Integer cqwwc = this.baseMapper.getCount("5", d, dto.getSfzh());
        vo.setAll(all);
        vo.setJxz(jxz);
        vo.setCqjxz(cqjxz);
        vo.setCqwc(cqwc);
        vo.setYwc(ywc);
        vo.setCqwwc(cqwwc);
        return vo;
    }

    @Override
    public List<TbRwTaskLXStatisticsVo> getRWLXDataStatistics(TbRwTaskStatisticsDto dto) {
        String d;
        if ("1".equals(dto.getDateType())) {
            d = DateUtils.getQueryDateString(new Date(), "01");
        } else if ("2".equals(dto.getDateType())) {
            d = DateUtils.getQueryDateString(DateUtils.getNextDate(new Date(), "D", -7), "01");
        } else {
            d = DateUtils.getQueryDateString(DateUtils.getNextDate(new Date(), "M", -1), "01");
        }
        List<SysDictItem> rwxl = tbRwTaskMapper.selectDict("D_BZ_RWXL");
        List<TbRwTaskLXStatisticsVo> ret = new ArrayList<>();
        if (null != rwxl) {
            for (SysDictItem sysDictItem : rwxl) {
                //分类查询
                TbRwTaskLXStatisticsVo vo = new TbRwTaskLXStatisticsVo();
                //后面 通过字典查询
                vo.setCt(sysDictItem.getZdmc());
                vo.setDm(sysDictItem.getDm());
                //总任务数
                Integer all = this.baseMapper.selectCount(new LambdaQueryWrapper<TbRwTask>()
                        .last(" and DATE_FORMAT(rwfqsj,'%Y-%m-%d')" +
                                " between DATE_FORMAT('" + d + "','%Y-%m-%d')" +
                                " and DATE_FORMAT(now(),'%Y-%m-%d')")
                );
                //进行中
                Integer jxz = this.baseMapper.selectCount(new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getRwjxzt, "1")
                        .eq(TbRwTask::getRwxl, sysDictItem.getDm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmdm()), TbRwTask::getSsbmdm, dto.getSsbmdm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmid()), TbRwTask::getSsbmid, dto.getSsbmid())
                        .last(" and DATE_FORMAT(rwfqsj,'%Y-%m-%d')" +
                                " between DATE_FORMAT('" + d + "','%Y-%m-%d')" +
                                " and DATE_FORMAT(now(),'%Y-%m-%d')")
                );
                //超期进行中
                Integer cqjxz = this.baseMapper.selectCount(new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getRwjxzt, "2")
                        .eq(TbRwTask::getRwxl, sysDictItem.getDm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmdm()), TbRwTask::getSsbmdm, dto.getSsbmdm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmid()), TbRwTask::getSsbmid, dto.getSsbmid())
                        .last(" and DATE_FORMAT(rwfqsj,'%Y-%m-%d')" +
                                " between DATE_FORMAT('" + d + "','%Y-%m-%d')" +
                                " and DATE_FORMAT(now(),'%Y-%m-%d')")
                );
                //已完成
                Integer ywc = this.baseMapper.selectCount(new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getRwjxzt, "3")
                        .eq(TbRwTask::getRwxl, sysDictItem.getDm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmdm()), TbRwTask::getSsbmdm, dto.getSsbmdm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmid()), TbRwTask::getSsbmid, dto.getSsbmid())
                        .last(" and DATE_FORMAT(rwfqsj,'%Y-%m-%d')" +
                                " between DATE_FORMAT('" + d + "','%Y-%m-%d')" +
                                " and DATE_FORMAT(now(),'%Y-%m-%d')")
                );
                // 超期完成
                Integer cqwc = this.baseMapper.selectCount(new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getRwjxzt, "4")
                        .eq(TbRwTask::getRwxl, sysDictItem.getDm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmdm()), TbRwTask::getSsbmdm, dto.getSsbmdm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmid()), TbRwTask::getSsbmid, dto.getSsbmid())
                        .last(" and DATE_FORMAT(rwfqsj,'%Y-%m-%d')" +
                                " between DATE_FORMAT('" + d + "','%Y-%m-%d')" +
                                " and DATE_FORMAT(now(),'%Y-%m-%d')")
                );
                // 超期未完成
                Integer cqwwc = this.baseMapper.selectCount(new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getRwjxzt, "5")
                        .eq(TbRwTask::getRwxl, sysDictItem.getDm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmdm()), TbRwTask::getSsbmdm, dto.getSsbmdm())
                        .eq(!StringUtils.isEmpty(dto.getSsbmid()), TbRwTask::getSsbmid, dto.getSsbmid())
                        .last(" and DATE_FORMAT(rwfqsj,'%Y-%m-%d')" +
                                " between DATE_FORMAT('" + d + "','%Y-%m-%d')" +
                                " and DATE_FORMAT(now(),'%Y-%m-%d')")
                );
                vo.setAll(all);
                vo.setJxz(jxz);
                vo.setCqjxz(cqjxz);
                vo.setCqwc(cqwc);
                vo.setYwc(ywc);
                vo.setCqwwc(cqwwc);
                ret.add(vo);
            }
        }
        return ret;
    }

    @Override
    public List<TbRwTaskRankingVo> getTaskRanking(TbRwTaskStatisticsDto dto) {
        return tbRwTaskMapper.getTaskRanking(dto);
    }

    @Override
    public void changeState() {
        // 任务到期之后还能继续执行的任务，修改状态为超期进行中
        List<TbRwTask> list = this.baseMapper.selectList(
                new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getXtSjzt, "1")
                        .eq(TbRwTask::getRwjxzt, "1")
                        .le(TbRwTask::getRwyqwcsj, DateUtils.getQueryDateString(new Date(), "02"))
                        .eq(TbRwTask::getSfaqwc, "0")
        );
        list.forEach(item -> {
            item.setRwjxzt("2");
            this.baseMapper.updateById(item);
        });
        List<TbRwTaskUser> userList = this.tbRwTaskUserMapper.selectList(
                new LambdaQueryWrapper<TbRwTaskUser>()
                        .eq(TbRwTaskUser::getXtSjzt, "1")
                        .eq(TbRwTaskUser::getRwjxzt, "1")
                        .le(TbRwTaskUser::getRwyqwcsj, DateUtils.getQueryDateString(new Date(), "02"))
                        .eq(TbRwTaskUser::getSfaqwc, "0")
        );
        userList.forEach(item -> {
            item.setRwjxzt("2");
            this.tbRwTaskUserMapper.updateById(item);
        });
        List<TbRwTaskUserAll> userAllList = this.tbRwTaskUserAllMapper.selectList(
                new LambdaQueryWrapper<TbRwTaskUserAll>()
                        .eq(TbRwTaskUserAll::getXtSjzt, "1")
                        .eq(TbRwTaskUserAll::getRwjxzt, "1")
                        .le(TbRwTaskUserAll::getRwyqwcsj, DateUtils.getQueryDateString(new Date(), "02"))
                        .eq(TbRwTaskUserAll::getSfaqwc, "0")
        );
        userAllList.forEach(item -> {
            item.setRwjxzt("2");
            this.tbRwTaskUserAllMapper.updateById(item);
        });
        // 任务到期之后不能继续执行的任务，修改状态为超期未完成
        list = this.baseMapper.selectList(
                new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getXtSjzt, "1")
                        .eq(TbRwTask::getRwjxzt, "1")
                        .le(TbRwTask::getRwyqwcsj, DateUtils.getQueryDateString(new Date(), "02"))
                        .eq(TbRwTask::getSfaqwc, "1")
        );
        list.forEach(item -> {
            item.setRwjxzt("5");
            this.baseMapper.updateById(item);
        });
        userAllList = this.tbRwTaskUserAllMapper.selectList(
                new LambdaQueryWrapper<TbRwTaskUserAll>()
                        .eq(TbRwTaskUserAll::getXtSjzt, "1")
                        .eq(TbRwTaskUserAll::getRwjxzt, "1")
                        .le(TbRwTaskUserAll::getRwyqwcsj, DateUtils.getQueryDateString(new Date(), "02"))
                        .eq(TbRwTaskUserAll::getSfaqwc, "1")
        );
        userAllList.forEach(item -> {
            item.setRwjxzt("5");
            this.tbRwTaskUserAllMapper.updateById(item);
        });
        // 删除进行中表的任务
        userList = this.tbRwTaskUserMapper.selectList(
                new LambdaQueryWrapper<TbRwTaskUser>()
                        .eq(TbRwTaskUser::getXtSjzt, "1")
                        .eq(TbRwTaskUser::getRwjxzt, "1")
                        .le(TbRwTaskUser::getRwyqwcsj, DateUtils.getQueryDateString(new Date(), "02"))
                        .eq(TbRwTaskUser::getSfaqwc, "1")
        );
        userList.forEach(item -> this.tbRwTaskUserMapper.deleteEntity(item.getId()));
    }

    @Override
    public TbRwTask getRwByYwid(TbRwTaskByYwidQuery dto) {
        return this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getYwid, dto.getYwid())
                        .eq(TbRwTask::getRwxl, dto.getRwxl())
                        .last(" limit 1")
        );
    }

    @Override
    public List<TbRwTaskRankingVo> getTaskByDept() {
        List<TbRwTaskRankingVo> rList = new ArrayList<>();
        List<Map<String, Object>> list = this.baseMapper.getTaskByDept();
        list.forEach(item -> {
            TbRwTaskRankingVo vo = new TbRwTaskRankingVo();
            vo.setSsbm(item.get("ssbm").toString());
            // 完成数
            int ys = this.baseMapper.getCountByDept(item.get("ssbmdm").toString(), "1");
            // 未完成数
            int ns = this.baseMapper.getCountByDept(item.get("ssbmdm").toString(), "2");
            vo.setYS(String.valueOf(ys));
            vo.setNS(String.valueOf(ns));
            vo.setRate(String.valueOf(
                    ns + ys == 0 ? "0.0000" :
                            (new BigDecimal(String.valueOf(ys)).divide(new BigDecimal(String.valueOf(ns))
                                    .add(new BigDecimal(String.valueOf(ys))), 4, BigDecimal.ROUND_HALF_UP))
            ));
            rList.add(vo);
        });
        rList.sort((o1, o2) -> new BigDecimal(o2.getRate()).compareTo(new BigDecimal(o1.getRate())));
        if (rList.size() >= 10) {
            return rList.subList(0, 10);
        } else {
            return rList;
        }
    }

    @Override
    public Boolean checkMyTask(String id) {
        UserInfo user = UserInfoManager.get();

        TbRwTaskUserAll taskUser = this.tbRwTaskUserAllMapper.selectByRwId(user.getIdEntityCard(), id, String.valueOf(user.getDeptId()));
        return taskUser != null;
    }

    @Override
    @Transactional
    public void changeTaskStateByZlid(TbZlxx zl) {
        TbRwTask task = this.baseMapper.selectById(
                new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getXtSjzt, "1")
                        .eq(TbRwTask::getYwid, zl.getId())
                        .eq(TbRwTask::getRwxxlx, "01")
                        .orderByDesc(TbRwTask::getRwfqsj)
                        .last(" limit 1")
        );
        task.setYwid(zl.getId());
        task.setRwmc(zl.getZlbt());
        task.setRwnr(zl.getZlnr());
        task.setRwfqsj(zl.getZlfqsj());
        task.setSfaqwc("1");
        task.setRwyqwcsj(DateUtils.getNextDate(new Date(), "H", 1));
        task.setRwjxzt("01");
        this.baseMapper.updateById(task);
        List<TbRwTaskUser> userList = this.tbRwTaskUserMapper.selectList(
                new LambdaQueryWrapper<TbRwTaskUser>()
                        .eq(TbRwTaskUser::getRwid, zl.getId())
                        .eq(TbRwTaskUser::getXtSjzt, "1")
        );
        userList.forEach(item -> {
            item.setYwid(zl.getId());
            item.setRwmc(zl.getZlbt());
            item.setRwnr(zl.getZlnr());
            item.setRwfqsj(zl.getZlfqsj());
            item.setSfaqwc("1");
            item.setRwyqwcsj(DateUtils.getNextDate(new Date(), "H", 1));
            item.setRwjxzt("01");
            item.setGrrwzt("01");
            this.tbRwTaskUserMapper.updateById(item);
        });
        List<TbRwTaskUserAll> userAllList = this.tbRwTaskUserAllMapper.selectList(
                new LambdaQueryWrapper<TbRwTaskUserAll>()
                        .eq(TbRwTaskUserAll::getRwid, zl.getId())
                        .eq(TbRwTaskUserAll::getXtSjzt, "1")
        );
        userAllList.forEach(item -> {
            item.setYwid(zl.getId());
            item.setRwmc(zl.getZlbt());
            item.setRwnr(zl.getZlnr());
            item.setRwfqsj(zl.getZlfqsj());
            item.setSfaqwc("1");
            item.setRwyqwcsj(DateUtils.getNextDate(new Date(), "H", 1));
            item.setRwjxzt("01");
            item.setGrrwzt("01");
            this.tbRwTaskUserAllMapper.updateById(item);
        });
    }

    @Override
    public Integer getYclTask() {
        UserInfo user = UserInfoManager.get();

        return this.baseMapper.getYclTask(user.getIdEntityCard(), String.valueOf(user.getDeptId()));
    }

    @Override
    public IPage<TbRwTaskUserAll> getYclTaskList(TbRwTaskMyInnerQuery dto) {
        if (!StringUtils.isEmpty(dto.getKssj())) {
            dto.setKssj(dto.getKssj() + " 00:00:00");
        }
        if (!StringUtils.isEmpty(dto.getJssj())) {
            dto.setJssj(dto.getJssj() + " 00:00:00");
        }
        UserInfo userInfo = UserInfoManager.get();
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        map.put("pageSize", dto.getPageSize());
        map.put("sfzh", userInfo.getIdEntityCard());
        map.put("dto", dto);
        map.put("ssbmid", String.valueOf(userInfo.getDeptId()));
        List<TbRwTaskUserAll> list = this.baseMapper.getMyRwListYwc(map);
        int count = this.baseMapper.getMyRwCountYwc(map);
        IPage<TbRwTaskUserAll> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page.setRecords(list);
        page.setTotal(count);
        return page;
    }

    @Override
    public boolean checkHasNewTask(String sfzh) {
        SysUser user = this.tbBaseAdaptRemoteService.getUserInfoBySfzh(sfzh);
        if (user == null) return false;
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(String.valueOf(user.getId()));
        if (dept == null || StringUtils.isEmpty(dept.getDeptid())) return false;
        Date time = DateUtils.getNextDate(new Date(), "S", -21);
        int count = this.baseMapper.checkHasNewTask(sfzh, dept.getDeptid(), DateUtils.getQueryDateString(time, "02"));
        return count >= 1;
    }
}
