package com.mosty.yjzl.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.jcgl.TbJcglXfllVo;
import com.mosty.base.model.dto.qwzx.TbQwXfbbVo;
import com.mosty.base.model.dto.yjzl.CyjlSearchDto;
import com.mosty.base.model.dto.yjzl.MyZlSearchDto;
import com.mosty.base.model.dto.yjzl.NewZxjlSearchDto;
import com.mosty.base.model.dto.yjzl.third.ThirdMyZlSearchDto;
import com.mosty.base.model.dto.yjzl.third.ThirdZlInfoSearchDto;
import com.mosty.base.model.query.jcgl.TbJcglXfllQueryAllDto;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.yjzl.TbZlxxInfoVo;
import com.mosty.base.model.vo.yjzl.TbZlxxVo;
import com.mosty.base.model.vo.yjzl.TbZlxxZxjlVo;
import com.mosty.base.model.vo.yjzl.TbZlxxZxrVo;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.core.business.entity.SysUser;
import com.mosty.common.core.business.entity.vo.SysUserVO;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import com.mosty.base.model.entity.yjzl.TbZlxx;
import com.mosty.base.model.entity.yjzl.TbZlxxZxjl;
import com.mosty.base.model.entity.yjzl.TbZlxxZxr;
import com.mosty.base.model.query.yjzl.TbZlxxZxjlQuery;
import com.mosty.yjzl.mapper.TbZlxxMapper;
import com.mosty.yjzl.mapper.TbZlxxZxjlMapper;
import com.mosty.yjzl.mapper.TbZlxxZxrMapper;
import com.mosty.yjzl.remote.TbBaseAdaptRemoteService;
import com.mosty.yjzl.remote.TbJcglAdaptRemoteService;
import com.mosty.yjzl.remote.TbQwzxAdaptRemoteService;
import com.mosty.yjzl.service.TbZlxxZxjlService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 指令-执行过程表 服务实现类
 * </p>
 *
 * @author zengbo
 * @since 2022-07-19
 */
@AllArgsConstructor
@Service
public class TbZlxxZxjlServiceImpl extends ServiceImpl<TbZlxxZxjlMapper, TbZlxxZxjl> implements TbZlxxZxjlService {

    private final TbZlxxZxrMapper tbZlxxZxrMapper;
    private final TbZlxxMapper tbZlxxMapper;
    private final TbZlxxZxjlMapper tbZlxxZxjlMapper;
    private final TbJcglAdaptRemoteService tbJcglAdaptRemoteService;
    private final TbQwzxAdaptRemoteService tbQwzxAdaptRemoteService;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;

    @Override
    public List<TbZlxxZxjl> queryList(TbZlxxZxjlQuery zxjl) {
        QueryWrapper<TbZlxxZxjl> queryWrapper = new QueryWrapper<>();
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(queryWrapper, userInfo);
        zxjl.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(zxjl.getSsbmdm(), null));

        queryWrapper.lambda().eq(TbZlxxZxjl::getXtScbz, "0")
        .eq(StringUtils.isNotBlank(zxjl.getZlId()), TbZlxxZxjl::getZlId, zxjl.getZlId())
        .likeRight(StringUtils.isNotBlank(zxjl.getSsbmdm()), TbZlxxZxjl::getSsbmdm, zxjl.getSsbmdm())
        .like(StringUtils.isNotBlank(zxjl.getZlzxzt()), TbZlxxZxjl::getZlzxzt, zxjl.getZlzxzt());
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public int insert(TbZlxxZxjl zxjl) {
        zxjl.setId(UUIDGenerator.getUUID());
        zxjl.setXtSjly("2");
        UserInfo user = UserInfoManager.get();
        zxjl.setSsbm(user.getDeptName());
        zxjl.setSsbmid(String.valueOf(user.getDeptId()));
        zxjl.setSsbmdm(user.getDeptCode());
        zxjl.setSsxgaj(user.getFxjDeptName());
        zxjl.setSsxgajid(String.valueOf(user.getFxjDeptId()));
        zxjl.setSsxgajdm(user.getFxjDeptCode());
        zxjl.setSssgaj(user.getDszDeptName());
        zxjl.setSssgajid(String.valueOf(user.getDszDeptId()));
        zxjl.setSssgajdm(user.getDszDeptCode());
        return this.baseMapper.insert(zxjl);
    }

    @Override
    public int update(TbZlxxZxjl zxjl) {
        zxjl.setXtZhgxsj(new Timestamp(System.currentTimeMillis()));
        return this.baseMapper.updateById(zxjl);
    }

    @Override
    public int deleteById(List<String> list) {
        return this.baseMapper.deleteZxjl(list);
    }

    @Override
    public List<Map<String, Object>> getCyjlList(CyjlSearchDto dto) {
        List<TbZlxx> zlList = this.tbZlxxMapper.selectList(
                new LambdaQueryWrapper<TbZlxx>()
                        .eq(TbZlxx::getYwId, dto.getSjid())
        );
        if (CollectionUtils.isEmpty(zlList)) return null;
        List<String> zlidList = zlList.stream().map(TbZlxx::getId).collect(Collectors.toList());
        List<TbZlxxZxr> zxrList = this.tbZlxxZxrMapper.selectList(new LambdaQueryWrapper<TbZlxxZxr>().in(TbZlxxZxr::getZlId, zlidList));
        List<Map<String, Object>> list = new ArrayList<>();
        zxrList.forEach(item -> {
            if ("01".equals(item.getZxrLx())) {
                List<Map<String, Object>> tempList = list.stream().filter(it -> it.get("sfz").equals(item.getZxrSfz())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(tempList)) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("xm", item.getZxrXm());
                    map.put("sfz", item.getZxrSfz());
                    map.put("dh", item.getZxrDh());
                    map.put("ssbm", item.getSsbm());
                    map.put("fl", item.getZxrJllx());
                    list.add(map);
                }
            } else if ("02".equals(item.getZxrLx())) {
                // 查询该部门下的所有的巡防力量
                TbJcglXfllQueryAllDto queryAllDto = new TbJcglXfllQueryAllDto();
                queryAllDto.setDeptid(item.getSsbmid());
                List<TbJcglXfllVo> llList = this.tbJcglAdaptRemoteService.getXfll(queryAllDto);
                llList.forEach(ll -> {
                    List<Map<String, Object>> tempList = list.stream().filter(it -> it.get("sfz").equals(ll.getSfzh())).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(tempList)) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("xm", ll.getXm());
                        map.put("sfz", ll.getSfzh());
                        map.put("dh", ll.getLxdh());
                        map.put("ssbm", ll.getSsbm());
                        map.put("fl", ll.getFl());
                        list.add(map);
                    }
                });
            } else if ("03".equals(item.getZxrLx())) {
                // 查询巡组信息
                TbQwXfbbVo bb = this.tbQwzxAdaptRemoteService.getBbInfo(item.getZxrXzid());
                if (bb != null) {
                    List<Map<String, Object>> tempList = list.stream().filter(it -> it.get("sfz").equals(bb.getFzrSfzh())).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(tempList)) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("xm", bb.getFzrXm());
                        map.put("sfz", bb.getFzrSfzh());
                        map.put("dh", bb.getFzrLxdh());
                        map.put("ssbm", bb.getSsbm());
                        map.put("fl", "01");
                        list.add(map);
                    }
                    if (!CollectionUtils.isEmpty(bb.getJlList())) {
                        bb.getJlList().forEach(jl -> {
                            if (jl != null && jl.getSfzh() != null) {
                                List<Map<String, Object>> jlTempList = list.stream().filter(it -> it.get("sfz").equals(jl.getSfzh())).collect(Collectors.toList());
                                if (CollectionUtils.isEmpty(jlTempList)) {
                                    Map<String, Object> map = new HashMap<>();
                                    map.put("xm", jl.getJlxm());
                                    map.put("sfz", jl.getSfzh());
                                    map.put("dh", jl.getLxdh());
                                    map.put("ssbm", jl.getSsbm());
                                    map.put("fl", jl.getJllx());
                                    list.add(map);
                                }
                            }
                        });
                    }
                }
            }
        });
        return list;
    }

    @Override
    public List<TbQwXfbbVo> getXczbList(String sjid) {
        List<TbZlxx> zlList = this.tbZlxxMapper.selectList(new LambdaQueryWrapper<TbZlxx>().eq(TbZlxx::getYwId, sjid));
        if (CollectionUtils.isEmpty(zlList)) {
            return null;
        }
        List<String> zlidList = zlList.stream().map(TbZlxx::getId).collect(Collectors.toList());
        List<TbZlxxZxr> zxrList = this.tbZlxxZxrMapper.selectList(new LambdaQueryWrapper<TbZlxxZxr>().in(TbZlxxZxr::getZlId, zlidList));
        List<TbQwXfbbVo> list = new ArrayList<>();
        for (TbZlxxZxr item : zxrList) {
            if ("03".equals(item.getZxrLx())) {
                TbQwXfbbVo bb = this.tbQwzxAdaptRemoteService.getBbInfo(item.getZxrXzid());
                if (bb != null) {
                    List<TbQwXfbbVo> temp = list.stream().filter(it -> it.getId().equals(bb.getId())).collect(Collectors.toList());
                    if (CollectionUtils.isEmpty(temp)) {
                        list.add(bb);
                    }
                }
            }
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> getMyZlCount() {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            return null;
        }
        Map<String, Object> mp = new HashMap<>();
        mp.put("sfz", user.getIdEntityCard());
        mp.put("ssbmid", String.valueOf(user.getDeptId()));
        return this.tbZlxxMapper.getMyZlCount(mp);
    }

    @Override
    public IPage<TbZlxxZxrVo> getMyZlList(MyZlSearchDto dto) {
        if (StringUtils.isNotBlank(dto.getKssj())) {
            dto.setKssj(dto.getKssj() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(dto.getJssj())) {
            dto.setJssj(dto.getJssj() + " 23:59:59");
        }
        UserInfo user = UserInfoManager.get();
        if (user == null) return null;
        Map<String, Object> mp = new HashMap<>();
        mp.put("sfz", user.getIdEntityCard());
        mp.put("ssbmid", String.valueOf(user.getDeptId()));
        List<String> ztList = new ArrayList<>();
        List<String> lxList = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getZlzxzt())) {
            ztList = Arrays.asList(dto.getZlzxzt().split(","));
        }
        if (StringUtils.isNotBlank(dto.getZllx())) {
            lxList = Arrays.asList(dto.getZllx().split(","));
        }
        mp.put("ztList", ztList);
        mp.put("zlnr", dto.getZlnr());
        mp.put("lxList", lxList);
        mp.put("kssj", dto.getKssj());
        mp.put("jssj", dto.getJssj());
        mp.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        mp.put("pageSize", dto.getPageSize());
        int count = this.tbZlxxMapper.getMyZlCountBy(mp);
        List<TbZlxxZxrVo> rList = this.tbZlxxMapper.getMyZlList(mp);
        IPage<TbZlxxZxrVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page.setTotal(count);
        page.setRecords(rList);
        return page;
    }

    @Override
    public List<TbZlxxZxjlVo> getNewZxjl(NewZxjlSearchDto dto) {
        List<TbZlxxZxjl> jlList = this.tbZlxxZxjlMapper.selectList(
                new LambdaQueryWrapper<TbZlxxZxjl>()
                        .eq(TbZlxxZxjl::getZlId, dto.getZlid())
                        .gt(StringUtils.isNotBlank(dto.getTime()), TbZlxxZxjl::getZxsj, dto.getTime())
                        .orderByAsc(TbZlxxZxjl::getZxsj)
                        .orderByDesc(TbZlxxZxjl::getFjid)
        );
        List<TbZlxxZxjlVo> voList = new ArrayList<>();
        jlList.forEach(item -> {
            TbZlxxZxjlVo vo = new TbZlxxZxjlVo();
            BeanUtils.copyProperties(item, vo);
            voList.add(vo);
        });
        return voList;
    }

    @Override
    public List<Map<String, Object>> getStatistics(String sfzh) {
        SysUser user = this.tbBaseAdaptRemoteService.getUserInfoBySfzh(sfzh);
        if (user == null) {
            throw new BusinessException("用户不存在！");
        }
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(String.valueOf(user.getId()));
        if (dept == null) {
            throw new BusinessException("用户未分配任何部门！");
        }
        Map<String, Object> mp = new HashMap<>();
        mp.put("sfz", user.getIdEntityCard());
        mp.put("ssbmid", String.valueOf(dept.getDeptid()));
        return this.tbZlxxMapper.getStatistics(mp);
    }

    @Override
    public IPage<TbZlxxZxrVo> getPageList(ThirdMyZlSearchDto dto) {
        if (StringUtils.isBlank(dto.getSfzh())) {
            throw new BusinessException("身份证号不能为空");
        }
        SysUser user = this.tbBaseAdaptRemoteService.getUserInfoBySfzh(dto.getSfzh());
        if (user == null) {
            throw new BusinessException("用户不存在！");
        }
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(String.valueOf(user.getId()));
        if (dept == null) {
            throw new BusinessException("用户未分配任何部门！");
        }
        if (StringUtils.isNotBlank(dto.getKssj())) {
            dto.setKssj(dto.getKssj() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(dto.getJssj())) {
            dto.setJssj(dto.getJssj() + " 23:59:59");
        }
        Map<String, Object> mp = new HashMap<>();
        mp.put("sfz", user.getIdEntityCard());
        mp.put("ssbmid", String.valueOf(dept.getDeptid()));
        List<String> ztList = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getZlzxzt())) {
            ztList = Arrays.asList(dto.getZlzxzt().split(","));
        }
        List<String> lxList = new ArrayList<>();
        if (StringUtils.isNotBlank(dto.getZllx())) {
            lxList = Arrays.asList(dto.getZllx().split(","));
        }
        mp.put("ztList", ztList);
        mp.put("zlnr", dto.getZlnr());
        mp.put("lxList", lxList);
        mp.put("kssj", dto.getKssj());
        mp.put("jssj", dto.getJssj());
        mp.put("pageIndex", (dto.getPageCurrent() - 1) * dto.getPageSize());
        mp.put("pageSize", dto.getPageSize());
        mp.put("time", dto.getTime());
        int count = this.tbZlxxMapper.getMyZlCountBy(mp);
        List<TbZlxxZxrVo> rList = this.tbZlxxMapper.getMyZlList(mp);
        IPage<TbZlxxZxrVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page.setTotal(count);
        page.setRecords(rList);
        return page;
    }

    @Override
    public TbZlxxInfoVo getInfo(ThirdZlInfoSearchDto dto) {
        if (StringUtils.isBlank(dto.getSfzh())) {
            throw new BusinessException("身份证号不能为空");
        }
        SysUser user = this.tbBaseAdaptRemoteService.getUserInfoBySfzh(dto.getSfzh());
        if (user == null) {
            throw new BusinessException("用户不存在！");
        }
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getDeptInfoByUserId(String.valueOf(user.getId()));
        if (dept == null) {
            throw new BusinessException("用户未分配任何部门！");
        }
        TbZlxx zlxx = this.tbZlxxMapper.selectById(dto.getZlid());
        TbZlxxInfoVo vo = new TbZlxxInfoVo();
        BeanUtils.copyProperties(zlxx, vo);
        TbZlxxZxr zxr = this.tbZlxxMapper.selectZxr(dto.getZlid(), dept.getDeptid(), user.getIdEntityCard());
        if (zxr != null) {
            TbZlxxZxrVo zxrVo = new TbZlxxZxrVo();
            BeanUtils.copyProperties(zxr, zxrVo);
            vo.setZxrVo(zxrVo);
        }
        return vo;
    }
}
