package com.mosty.rwzx.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.TbQwXfbb;
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.query.rwzx.TbRwTaskInnerQuery;
import com.mosty.base.model.query.rwzx.TbRwTaskMyInnerQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.rwzx.TbRwTaskMyVo;
import com.mosty.base.model.vo.rwzx.TbRwTaskUserVo;
import com.mosty.base.model.vo.rwzx.TbRwTaskVo;
import com.mosty.base.utils.*;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.core.business.entity.SysUser;
import com.mosty.common.core.business.entity.vo.SysUserDeptVO;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import com.mosty.rwzx.mapper.TbRwTaskLogMapper;
import com.mosty.rwzx.mapper.TbRwTaskMapper;
import com.mosty.rwzx.mapper.TbRwTaskUserAllMapper;
import com.mosty.rwzx.mapper.TbRwTaskUserMapper;
import com.mosty.rwzx.remote.TbBaseAdaptRemoteService;
import com.mosty.rwzx.remote.TbJcglAdaptRemoteService;
import com.mosty.rwzx.remote.TbQwzxAdaptRemoteService;
import com.mosty.rwzx.service.TbRwTaskInnerService;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.awt.geom.FlatteningPathIterator;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class TbRwTaskInnerServiceImpl extends ServiceImpl<TbRwTaskMapper, TbRwTask>
        implements TbRwTaskInnerService {

    private final TbRwTaskLogMapper tbRwTaskLogMapper;
    private final TbRwTaskUserMapper tbRwTaskUserMapper;
    private final TbRwTaskUserAllMapper tbRwTaskUserAllMapper;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbQwzxAdaptRemoteService tbQwzxAdaptRemoteService;

    @Override
    public int addRw(TbRwTaskInnerDto dto) {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("请重新登录！！");
        }
        TbRwTask task = new TbRwTask();
        BeanUtils.copyProperties(dto, task);
        task.setId(UUIDGenerator.getUUID());
        task.setRwfqsj(new Date());
        task.setRwzt("0");
        task.setRwjxzt("1");
        task.setCjrid(String.valueOf(user.getUserId()));
        task.setCjrxm(user.getUserName());
        task.setCjrsfzh(user.getIdEntityCard());
        task.setSsbmid(String.valueOf(user.getDeptId()));
        task.setSsbm(String.valueOf(user.getDeptName()));
        task.setSsbmdm(user.getDeptCode());
        task.setSsxgajid(String.valueOf(user.getFxjDeptId()));
        task.setSsxgaj(user.getFxjDeptName());
        task.setSsxgajdm(user.getFxjDeptCode());
        task.setSssgajid(String.valueOf(user.getDszDeptId()));
        task.setSssgaj(user.getDszDeptName());
        task.setSssgajdm(user.getDszDeptCode());
        task.setXtSjly("1");
        // 添加发送人
        List<TbRwTaskUserInnerDto> userDtoList = dto.getUserDtoList();
        if (CollectionUtils.isEmpty(userDtoList)) {
            throw new BusinessException("请至少选择一个人员接收任务");
        }
        // TODO 计算接收人数量
        task.setRwzxrysl(userDtoList.size());
        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.setJsbmmc(item.getJsbmdm());
            taskUser.setJsbmmc(item.getJsbmmc());
            DeptInfoVo dept = null;
            if ("01".equals(item.getRwjsdx())) {
                dept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(item.getJsrid());
            } else if ("02".equals(item.getRwjsdx())) {
                dept = this.tbBaseAdaptRemoteService.getOrgByDeptId(item.getJsbmdm());
                taskUser.setJsbmmc(dept.getDeptname());
            } else if ("03".equals(item.getRwjsdx())) {
                TbQwXfbbVo bb = this.tbQwzxAdaptRemoteService.getBbInfo(item.getJsxzid());
                if (bb != null) {
                    dept = this.tbBaseAdaptRemoteService.getOrgByDeptId(bb.getSsbmid());
                }
            }
            if (dept != null) {
                taskUser.setSsbmdm(dept.getDeptcode());
                taskUser.setSsbmid(dept.getDeptid());
                taskUser.setSsbm(dept.getDeptname());
                taskUser.setSsxgajid(dept.getFxjid());
                taskUser.setSsxgaj(dept.getFxjname());
                taskUser.setSsxgajdm(dept.getFxjcode());
                taskUser.setSssgaj(dept.getDszname());
                taskUser.setSssgajdm(dept.getDszcode());
                taskUser.setSssgajid(dept.getDszid());
                taskUser.setXtSjly("2");
            }
            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());
        log.setSsbmid(String.valueOf(user.getDeptId()));
        log.setSsbm(String.valueOf(user.getDeptName()));
        log.setSsbmdm(user.getDeptCode());
        log.setSsxgajid(String.valueOf(user.getFxjDeptId()));
        log.setSsxgajdm(user.getFxjDeptCode());
        log.setSsxgaj(user.getFxjDeptName());
        log.setSssgajid(String.valueOf(user.getDszDeptId()));
        log.setSssgaj(user.getDszDeptName());
        log.setSssgajdm(user.getDszDeptCode());
        log.setXtSjly("1");
        this.tbRwTaskLogMapper.insertEntity(log);
        return this.baseMapper.insert(task);
    }

    @Override
    public IPage<TbRwTaskVo> selectPage(TbRwTaskInnerQuery 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");
        }
        IPage<TbRwTaskVo> rPage = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        List<String> rwjsdx = !StringUtils.isEmpty(dto.getRwjsdx()) ? Arrays.asList(dto.getRwjsdx().split(",")) : null;
        List<String> rwxl = !StringUtils.isEmpty(dto.getRwxl()) ? Arrays.asList(dto.getRwxl().split(",")) : null;
        QueryWrapper<TbRwTask> qw = new QueryWrapper<>();
//        UserInfo user = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(qw, user);
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));

        IPage<TbRwTask> page = this.baseMapper.selectPage(
                new Page<>(dto.getPageCurrent(), dto.getPageSize()),
                qw.lambda()
                        .eq(!StringUtils.isEmpty(dto.getYwid()), TbRwTask::getYwid, dto.getYwid())
                        .like(!StringUtils.isEmpty(dto.getRwmc()), TbRwTask::getRwmc, dto.getRwmc())
                        .like(!StringUtils.isEmpty(dto.getRwnr()), TbRwTask::getRwnr, dto.getRwnr())
                        .in(rwjsdx != null, TbRwTask::getRwjsdx, rwjsdx)
                        .in(rwxl != null, TbRwTask::getRwxl, rwxl)
                        .eq(!StringUtils.isEmpty(dto.getRwlx()), TbRwTask::getRwlx, dto.getRwlx())
                        .eq(!StringUtils.isEmpty(dto.getRwjjcd()), TbRwTask::getRwjjcd, dto.getRwjjcd())
                        .eq(!StringUtils.isEmpty(dto.getRwms()), TbRwTask::getRwms, dto.getRwms())
                        .eq(!StringUtils.isEmpty(dto.getRwjxzt()), TbRwTask::getRwjxzt, dto.getRwjxzt())
                        .eq(!StringUtils.isEmpty(dto.getRwzt()), TbRwTask::getRwzt, dto.getRwzt())
                        .eq(!StringUtils.isEmpty(dto.getCjrid()), TbRwTask::getCjrid, dto.getCjrid())
                        .eq(!StringUtils.isEmpty(dto.getRwxxlx()), TbRwTask::getRwxxlx, dto.getRwxxlx())
                        .like(!StringUtils.isEmpty(dto.getCjrxm()), TbRwTask::getCjrxm, dto.getCjrxm())
                        .likeRight(!StringUtils.isEmpty(dto.getSsbmdm()), TbRwTask::getSsbmdm, dto.getSsbmdm())
                        .ge(!StringUtils.isEmpty(dto.getKssj()), TbRwTask::getRwfqsj, dto.getKssj())
                        .le(!StringUtils.isEmpty(dto.getJssj()), TbRwTask::getRwfqsj, dto.getJssj())
                        .orderByDesc(TbRwTask::getRwfqsj)
        );
        List<TbRwTask> list = page.getRecords();
        List<TbRwTaskVo> rList = new ArrayList<>();
        list.forEach(item -> {
            TbRwTaskVo vo = new TbRwTaskVo();
            BeanUtils.copyProperties(item, vo);
            rList.add(vo);
        });
        rPage.setRecords(rList);
        rPage.setTotal(page.getTotal());
        return rPage;
    }

    @Override
    public IPage<TbRwTaskUser> selectMyPage(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<TbRwTaskUser> list = this.baseMapper.getMyRwList(map);
        int count = this.baseMapper.getMyRwCount(map);
        IPage<TbRwTaskUser> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page.setRecords(list);
        page.setTotal(count);
        return page;
    }

    /**
     * 单用户更改已查看
     * 单人模式修改单人状态，并判断是否完成，修改任务状态
     * 多人模式修改所有人状态，修改任务状态
     *
     * @param task
     * @param dto
     */
    private void changeZf(TbRwTask task, TbRwTaskGrChangeStateInnerDto dto) {
        DeptInfoVo zfDept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(dto.getZfjsrid());
        SysUser zfUser = this.tbBaseAdaptRemoteService.getUserInfo(dto.getZfjsrid());
        TbRwTaskUser temp = this.tbRwTaskUserMapper.selectByRwId(zfUser.getIdEntityCard(), task.getId(), zfDept.getDeptid());
        // 判断被转发人是否有该任务，如果有，则提示
        if (temp != null) {
            throw new BusinessException("该人员已存在该任务，不能转发给本人！");
        }
        UserInfo user = UserInfoManager.get();
        TbRwTaskUser taskUser = this.tbRwTaskUserMapper.selectByRwId(user.getIdEntityCard(),
                task.getId(), String.valueOf(user.getDeptId()));
        TbRwTaskUserAll taskUserAll = this.tbRwTaskUserAllMapper.selectByRwId(user.getIdEntityCard(),
                task.getId(), String.valueOf(user.getDeptId()));
        taskUser.setGrrwzt("3");
        taskUserAll.setGrrwzt("3");
        taskUser.setYjsj(new Date());
        taskUserAll.setYjsj(new Date());
        // 记录日志
        TbRwTaskLog log = new TbRwTaskLog();
        SysUser jsr = this.tbBaseAdaptRemoteService.getUserInfo(dto.getZfjsrid());
        String rznr = DateUtils.getQueryDateString(new Date(), "2") + "," + user.getUserName() +
                "转发了该任务,转发给->" + jsr.getUserName();
        String rzlx = "4";
        log.setId(UUIDGenerator.getUUID()).setRwid(task.getId()).setRzlx(rzlx).setRznr(rznr).setJd(dto.getJd()).setWd(dto.getWd())
                .setBgsj(new Date())
                .setBgrid(String.valueOf(user.getUserId()))
                .setBgrxm(user.getUserName())
                .setBgrsfzh(user.getIdEntityCard())
                .setSsbm(user.getDeptName())
                .setSsbmdm(String.valueOf(user.getDeptName()))
                .setSsxgaj(user.getFxjDeptName())
                .setSsxgajdm(String.valueOf(user.getFxjDeptId()))
                .setSssgaj(user.getDszDeptName())
                .setSssgajdm(String.valueOf(user.getDszDeptId()))
                .setXtSjly("2");
        if (log.getJd() != null && log.getWd() != null) {
            log.setZb(JtsUtils.getPoint(log.getJd(), log.getWd())).setZbhash(GeoHashKit.encode(log.getJd(), log.getWd()));
        }
        this.tbRwTaskLogMapper.insertEntity(log);
        // 重新生成一条数据
        TbRwTaskUser newUser = new TbRwTaskUser();
        BeanUtils.copyProperties(taskUser, newUser);
        newUser.setRwzflx("2")
                .setId(UUIDGenerator.getUUID())
                .setGrrwzt("0")
                .setJsrid(String.valueOf(jsr.getId()))
                .setJsrlxdh(jsr.getMobile())
                .setJsrsfzh(jsr.getIdEntityCard())
                .setJsrmc(jsr.getUserName())
                .setJsxzid(null)
                .setJsxzmc(null)
                .setJsbmmc(null)
                .setJsbmdm(null)
                .setXtSjly("2");
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(dto.getZfjsrid());
        newUser.setSsbmid(dept.getDeptid());
        newUser.setSsbmdm(dept.getDeptcode());
        newUser.setSsbm(dept.getDeptname());
        newUser.setSsxgaj(dept.getFxjname());
        newUser.setSsxgajid(dept.getFxjid());
        newUser.setSsxgajdm(dept.getFxjcode());
        newUser.setSssgaj(dept.getDszname());
        newUser.setSssgajid(dept.getDszid());
        newUser.setSssgajdm(dept.getDszcode());
        newUser.setBhtaskuserid(taskUser.getId());
        this.tbRwTaskUserMapper.insert(newUser);
        TbRwTaskUserAll newUserAll = new TbRwTaskUserAll();
        BeanUtils.copyProperties(newUser, newUserAll);
        this.tbRwTaskUserAllMapper.insert(newUserAll);
        this.tbRwTaskUserMapper.updateById(taskUser);
        this.tbRwTaskUserAllMapper.updateById(taskUserAll);
    }

    @Override
    public void changeStateByYwid(TbRwTaskChangeStateByYwidDto dtos) {
        TbRwTask task = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbRwTask>()
                        .eq(TbRwTask::getYwid, dtos.getYwid())
                        .eq(TbRwTask::getXtSjzt, "1")
                        .eq(!StringUtils.isEmpty(dtos.getRwxxlx()), TbRwTask::getRwxxlx, dtos.getRwxxlx())
        );
        if (task != null) {
            TbRwTaskGrChangeStateInnerDto dto = new TbRwTaskGrChangeStateInnerDto();
            dto.setJd(dtos.getJd());
            dto.setWd(dtos.getWd());
            dto.setRwid(task.getId());
            dto.setRwzt(dtos.getRwzt());
            if ("1".equals(dto.getRwzt()) || "2".equals(dto.getRwzt())) {
                // 进行中
                this.changeJxzOrYwc(task, dto, dto.getRwzt());
            } else if ("3".equals(dto.getRwzt())) {
                // 已转发
                this.changeZf(task, dto);
            } else if ("4".equals(dto.getRwzt())) {
                // 被驳回
                this.changeBh(task, dto);
            }
        }
    }

    @Override
    public List<Map<String, Object>> myRwCount() {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("登录过期，请重新登录");
        }
        return this.baseMapper.myRwCount(user.getIdEntityCard(), String.valueOf(user.getDeptId()));
    }

    @Override
    public List<Map<String, Object>> rwCountByState(TbRwTaskInnerQuery 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");
        }
        List<String> rwjsdx = !StringUtils.isEmpty(dto.getRwjsdx()) ? Arrays.asList(dto.getRwjsdx().split(",")) : null;
        List<String> rwxl = !StringUtils.isEmpty(dto.getRwxl()) ? Arrays.asList(dto.getRwxl().split(",")) : null;
        Map<String, Object> map = new HashMap<>();
        map.put("rwjsdxList", rwjsdx);
        map.put("rwxlList", rwxl);
        map.put("dto", dto);
        return this.baseMapper.rwCountByState(map);
    }

    /**
     * 被驳回
     *
     * @param task
     * @param dto
     */
    private void changeBh(TbRwTask task, TbRwTaskGrChangeStateInnerDto dto) {
        UserInfo user = UserInfoManager.get();

        TbRwTaskUser taskUser = this.tbRwTaskUserMapper.selectOne(
                new LambdaQueryWrapper<TbRwTaskUser>()
                        .eq(TbRwTaskUser::getJsrsfzh, user.getIdEntityCard())
                        .eq(TbRwTaskUser::getRwid, task.getId())
        );
        TbRwTaskUserAll taskUserAll = this.tbRwTaskUserAllMapper.selectOne(
                new LambdaQueryWrapper<TbRwTaskUserAll>()
                        .eq(TbRwTaskUserAll::getJsrsfzh, user.getIdEntityCard())
                        .eq(TbRwTaskUserAll::getRwid, task.getId())
        );
        taskUser.setGrrwzt("4");
        taskUserAll.setGrrwzt("4");
        // 记录日志
        TbRwTaskLog log = new TbRwTaskLog();
        String rznr = DateUtils.getQueryDateString(new Date(), "2") + "," + user.getUserName()
                + "驳回了该任务。";
        String rzlx = "8";
        log.setId(UUIDGenerator.getUUID())
                .setRwid(task.getId())
                .setRzlx(rzlx)
                .setRznr(rznr)
                .setJd(dto.getJd())
                .setWd(dto.getWd())
                .setBgsj(new Date())
                .setBgrid(String.valueOf(user.getUserId()))
                .setBgrxm(user.getUserName())
                .setBgrsfzh(user.getIdEntityCard())
                .setSsbm(user.getDeptName())
                .setSsbmdm(String.valueOf(user.getDeptName()))
                .setSsxgaj(user.getFxjDeptName())
                .setSsxgajdm(String.valueOf(user.getFxjDeptId()))
                .setSssgaj(user.getDszDeptName())
                .setSssgajdm(String.valueOf(user.getDszDeptId()))
                .setXtSjly("2");
        if (log.getJd() != null && log.getWd() != null) {
            log.setZb(JtsUtils.getPoint(log.getJd(), log.getWd())).setZbhash(GeoHashKit.encode(log.getJd(), log.getWd()));
        }
        this.tbRwTaskLogMapper.insertEntity(log);
        // 发送新任务
        TbRwTaskUser bhtaskUser = this.tbRwTaskUserMapper.selectById(taskUser.getBhtaskuserid());
        TbRwTaskUserAll bhtaskUserAll = this.tbRwTaskUserAllMapper.selectById(taskUser.getBhtaskuserid());
        bhtaskUser.setRwzflx("3");
        bhtaskUserAll.setRwzflx("3");
        bhtaskUser.setGrrwzt("0");
        bhtaskUserAll.setGrrwzt("0");
        this.tbRwTaskUserMapper.updateById(bhtaskUser);
        this.tbRwTaskUserAllMapper.updateById(bhtaskUserAll);
        this.tbRwTaskUserMapper.updateById(taskUser);
    }

    @Override
    public void changeGrrwState(TbRwTaskGrChangeStateInnerDto dto) {
        TbRwTask task = this.baseMapper.selectById(dto.getRwid());
        if (task != null) {
            if ("1".equals(dto.getRwzt()) || "2".equals(dto.getRwzt())) {
                // 进行中
                this.changeJxzOrYwc(task, dto, dto.getRwzt());
            } else if ("3".equals(dto.getRwzt())) {
                // 已转发
                this.changeZf(task, dto);
            } else if ("4".equals(dto.getRwzt())) {
                // 被驳回
                this.changeBh(task, dto);
            }
        }
    }

    @Override
    public void changeRwState(TbRwTaskChangeStateInnerDto dto) {
        UserInfo user = UserInfoManager.get();
        TbRwTask task = this.baseMapper.selectById(dto.getId());
        if (task != null) {
            task.setRwzt(dto.getRwzt());
            this.baseMapper.updateById(task);
            // 记录日志
            String rznr = "";
            String rzlx = "";
            if ("0".equals(dto.getRwzt())) {
                rznr = "重启了该任务。";
                rzlx = "6";
            } else if ("1".equals(dto.getRwzt())) {
                rznr = "关闭了该任务。";
                rzlx = "1";
            } else if ("2".equals(dto.getRwzt())) {
                rznr = "暂停了该任务。";
                rzlx = "5";
            }
            TbRwTaskLog log = new TbRwTaskLog();
            rznr = DateUtils.getQueryDateString(new Date(), "2") + "," + user.getUserName() + rznr;
            log.setId(UUIDGenerator.getUUID()).setRwid(task.getId()).setRzlx(rzlx).setRznr(rznr)
                    .setJd(dto.getJd()).setWd(dto.getWd()).setBgsj(new Date())
                    .setBgrid(String.valueOf(user.getUserId()))
                    .setBgrxm(user.getUserName())
                    .setBgrsfzh(user.getIdEntityCard())
                    .setSsbm(user.getDeptName())
                    .setSsbmdm(String.valueOf(user.getDeptName()))
                    .setSsxgaj(user.getFxjDeptName())
                    .setSsxgajdm(String.valueOf(user.getFxjDeptId()))
                    .setSssgaj(user.getDszDeptName())
                    .setSssgajdm(String.valueOf(user.getDszDeptId()))
                    .setXtSjly("2");
            if (log.getJd() != null && log.getWd() != null) {
                log.setZb(JtsUtils.getPoint(log.getJd(), log.getWd())).setZbhash(GeoHashKit.encode(log.getJd(), log.getWd()));
            }
            this.tbRwTaskLogMapper.insertEntity(log);
            // 修改用户表的任务状态
            List<TbRwTaskUser> userList = this.tbRwTaskUserMapper.selectList(
                    new LambdaQueryWrapper<TbRwTaskUser>()
                            .eq(TbRwTaskUser::getRwid, task.getId())
            );
            userList.forEach(item -> {
                item.setRwzt(dto.getRwzt());
                this.tbRwTaskUserMapper.updateById(item);
            });
            // 修改所有用户表的状态
            List<TbRwTaskUserAll> userAllList = this.tbRwTaskUserAllMapper.selectList(
                    new LambdaQueryWrapper<TbRwTaskUserAll>()
                            .eq(TbRwTaskUserAll::getRwid, task.getId())
            );
            userAllList.forEach(item -> {
                item.setRwzt(dto.getRwzt());
                this.tbRwTaskUserAllMapper.updateById(item);
            });
        }
    }

    /**
     * 单用户更改已查看
     * 单人模式修改单人状态，并判断是否完成，修改任务状态
     * 多人模式修改所有人状态，修改任务状态
     *
     * @param task 任务
     * @param dto  dto
     */
    private void changeJxzOrYwc(TbRwTask task, TbRwTaskGrChangeStateInnerDto dto, String grrwzt) {
        UserInfo user = UserInfoManager.get();

        TbRwTaskUser taskUser = this.tbRwTaskUserMapper.selectByRwId(user.getIdEntityCard(), task.getId(),
                String.valueOf(user.getDeptId()));
        TbRwTaskUserAll taskUserAll = this.tbRwTaskUserAllMapper.selectByRwId(user.getIdEntityCard(), task.getId(),
                String.valueOf(user.getDeptId()));
        if (taskUser != null) {
            taskUser.setGrrwzt(grrwzt);
            taskUserAll.setGrrwzt(grrwzt);
            // 记录日志
            TbRwTaskLog log = new TbRwTaskLog();
            String rznr;
            String rzlx;
            if ("1".equals(grrwzt)) {
                rznr = DateUtils.getQueryDateString(new Date(), "2") + "," + user.getUserName() +
                        "查看了该任务，任务开始！";
                rzlx = "2";
            } else {
                rznr = DateUtils.getQueryDateString(new Date(), "2") + "," + user.getUserName() + "完成了该任务";
                rzlx = "3";
            }
            log.setId(UUIDGenerator.getUUID())
                    .setRwid(task.getId())
                    .setRzlx(rzlx)
                    .setRznr(rznr)
                    .setJd(dto.getJd())
                    .setWd(dto.getWd())
                    .setBgsj(new Date())
                    .setBgrid(String.valueOf(user.getUserId()))
                    .setBgrxm(user.getUserName())
                    .setBgrsfzh(user.getIdEntityCard())
                    .setSsbm(user.getDeptName())
                    .setSsbmid(String.valueOf(user.getDeptId()))
                    .setSsbmdm(user.getDeptCode())
                    .setSsxgaj(user.getFxjDeptName())
                    .setSsxgajid(String.valueOf(user.getFxjDeptId()))
                    .setSsxgajdm(user.getFxjDeptCode())
                    .setSssgaj(user.getDszDeptName())
                    .setSssgajid(String.valueOf(user.getDszDeptId()))
                    .setSssgajdm(user.getDszDeptCode())
                    .setXtSjly("2");
            if (log.getJd() != null && log.getWd() != null) {
                log.setZb(JtsUtils.getPoint(log.getJd(), log.getWd()))
                        .setZbhash(GeoHashKit.encode(log.getJd(), log.getWd()));
            }
            this.tbRwTaskLogMapper.insertEntity(log);
            if ("2".equals(task.getRwms())) {
                // 判断当所有用户已读的时候，将消息改为已读
                List<TbRwTaskUser> userList = this.tbRwTaskUserMapper.selectList(
                        new LambdaQueryWrapper<TbRwTaskUser>()
                                .eq(TbRwTaskUser::getRwid, task.getId()
                                )
                );
                long count = userList.stream().filter(item -> "0".equals(item.getRwzt()) || "1".equals(item.getRwzt())).count();
                if (count == 0) {
                    task.setRwjxzt("1".equals(task.getRwjxzt()) || "3".equals(task.getRwjxzt()) ? "3" : "4");
                    taskUser.setRwjxzt("1".equals(task.getRwjxzt()) || "3".equals(task.getRwjxzt()) ? "3" : "4");
                    taskUserAll.setRwjxzt("1".equals(task.getRwjxzt()) || "3".equals(task.getRwjxzt()) ? "3" : "4");
                    task.setRwwcsj(new Date());
                    taskUser.setRwwcsj(new Date());
                    taskUserAll.setRwwcsj(new Date());
                }
                this.baseMapper.updateById(task);
            } else {
                // 根据一个用户的状态完成任务状态
                List<TbRwTaskUser> userList = this.tbRwTaskUserMapper.selectList(
                        new LambdaQueryWrapper<TbRwTaskUser>()
                                .eq(TbRwTaskUser::getRwid, task.getId())
                );
                userList.forEach(item -> {
                    item.setGrrwzt(grrwzt);
                    if ("1".equals(grrwzt)) {
                        this.tbRwTaskUserMapper.updateById(item);
                    } else {
                        this.tbRwTaskUserMapper.deleteEntity(item.getId());
                    }
                });
                if ("2".equals(grrwzt)) {
                    task.setRwjxzt("1".equals(task.getRwjxzt()) || "3".equals(task.getRwjxzt()) ? "3" : "4");
                    taskUser.setRwjxzt("1".equals(task.getRwjxzt()) || "3".equals(task.getRwjxzt()) ? "3" : "4");
                    taskUserAll.setRwjxzt("1".equals(task.getRwjxzt()) || "3".equals(task.getRwjxzt()) ? "3" : "4");
                    task.setRwwcsj(new Date());
                    taskUser.setRwwcsj(new Date());
                    taskUserAll.setRwwcsj(new Date());
                    this.baseMapper.updateById(task);
                }
            }
            this.tbRwTaskUserAllMapper.updateById(taskUserAll);
        }
    }
}
