package com.mosty.qwzx.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.feign.service.MostyJcglFeignService;
import com.mosty.base.model.dto.qwzx.TbQwXfbbStartOrEndBbDto;
import com.mosty.base.model.entity.qwzx.*;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.utils.Constant;
import com.mosty.base.utils.DateUtils;
import com.mosty.base.utils.PageUtils;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.common.base.exception.BusinessException;
import com.mosty.common.core.business.entity.SysDept;
import com.mosty.common.core.business.service.SysDeptService;
import com.mosty.common.core.business.service.SysRoleService;
import com.mosty.common.token.DeptInfo;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import com.mosty.common.util.PermissionsUtil;
import com.mosty.base.model.query.qwzx.TbQwZbbbQuery;
import com.mosty.base.model.vo.qwzx.TbQwZbbbVo;
import com.mosty.qwzx.mapper.*;
import com.mosty.qwzx.remote.TbBaseAdaptRemoteService;
import com.mosty.qwzx.remote.TbJcglAdaptRemoteService;
import com.mosty.qwzx.service.TbQwZbbbService;
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 javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author dw
 * @since 2022-10-09
 */
@AllArgsConstructor
@Service
public class TbQwZbbbServiceImpl extends ServiceImpl<TbQwZbbbMapper, TbQwZbbb>
        implements TbQwZbbbService {

    private final TbQwJlMapper tbQwJlMapper;
    private final TbBaseAdaptRemoteService tbBaseAdaptRemoteService;
    private final TbQwZbpbZqMapper tbQwZbpbZqMapper;
    private final SysRoleService sysRoleService;
    private TbJcglAdaptRemoteService tbJcglAdaptRemoteService;
    private final TbQwQxjMapper tbQwQxjMapper;
    private final SysDeptService sysDeptService;

    @Override
    public Map<String, Object> getJlByBm(String time, String ssbmdm) {
        if (StringUtils.isBlank(ssbmdm)) {
            UserInfo user = UserInfoManager.get();
            ssbmdm = user.getDeptCode();
        }
        Map<String, Object> ryMap = new HashMap<>();
//        SysDept deptByParentid = sysDeptService.getDeptByParentid(ssbmid);
//        ssbmdm = deptByParentid.getOrgCode();
//        DeptInfo sysDeptLevel = sysRoleService.getSysDeptLevel(ssbmdm);
        //查询部门下面所有警力
        Integer rysl = tbJcglAdaptRemoteService.getRysl(ssbmdm);
        ssbmdm = tbBaseAdaptRemoteService.getSsbm(ssbmdm, null);


        ryMap.put("all", rysl);
        //查询值班警力
        QueryWrapper<TbQwZbbb> tb = new QueryWrapper<>();
//        PermissionsUtil.queryWrapperUtilByDeptInfo(tb, sysDeptLevel);
        tb.lambda().ne(TbQwZbbb::getBbzt, "1").likeRight(TbQwZbbb::getSsbmdm, ssbmdm);
        List<TbQwZbbb> tbQwZbbbs = this.baseMapper.selectList(tb);
        Set<String> zbSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(tbQwZbbbs)) {
            for (TbQwZbbb zb : tbQwZbbbs) {
                String zbmj = zb.getZbmj();
                if (StringUtils.isNotBlank(zbmj)) {
                    List<TbQwJl> mjList = JSONObject.parseArray(zbmj, TbQwJl.class);
                    mjList.forEach(v -> {
                        zbSet.add(v.getSfzh());
                    });
                }
                String zbfj = zb.getZbfj();
                if (StringUtils.isNotBlank(zbfj)) {
                    List<TbQwJl> fjList = JSONObject.parseArray(zbfj, TbQwJl.class);
                    fjList.forEach(v -> {
                        zbSet.add(v.getSfzh());
                    });
                }
            }
        }
        ryMap.put("zbjl", zbSet.size());

        //查询未在岗警力
        //查询人员请假休假
        QueryWrapper<TbQwQxj> ryqj = new QueryWrapper<>();
//        PermissionsUtil.queryWrapperUtilByDeptInfo(ryqj, sysDeptLevel);
        ryqj.lambda().likeRight(TbQwQxj::getSsbmdm, ssbmdm).last("and DATE_FORMAT('" + time + "', '%Y-%m-%d') <= jssj and DATE_FORMAT('" + time + "', '%Y-%m-%d') >= kssj");
        List<TbQwQxj> tbQwQxjs = tbQwQxjMapper.selectList(ryqj);
        ryMap.put("wzgjl", tbQwQxjs.size());
        return ryMap;
    }

    @Override
    public IPage<TbQwZbbbVo> queryList(TbQwZbbbQuery zb) {
        zb.setSsbmdm(tbBaseAdaptRemoteService.getSsbm(zb.getSsbmdm(), null));
//        UserInfo userInfo = UserInfoManager.get();
        IPage<TbQwZbbbVo> page = PageUtils.buildPage(zb.getPageSize(), zb.getPageCurrent());
        return this.baseMapper.queryList(page, zb);
    }

    @Override
    public TbQwZbbbVo selectById(String id) {
        TbQwZbbb zb = this.baseMapper.selectById(id);
        TbQwZbbbVo vo = new TbQwZbbbVo();
        BeanUtils.copyProperties(zb, vo);
        List<String> list = new ArrayList<>();
        list.add(id);
        List<TbQwJl> jlList = this.tbQwJlMapper.queryListByYwid(list);
        vo.setJlList(jlList);
        return vo;
    }

    @Override
    public String addQwzb(TbQwZbbbVo vo) {
        TbQwZbbb zbbb = new TbQwZbbb();
        BeanUtils.copyProperties(vo, zbbb);
        zbbb.setId(UUIDGenerator.getUUID());
        if (StringUtils.isBlank(zbbb.getBblx())) {
            zbbb.setBblx("01");
        }
        if (StringUtils.isBlank(vo.getSsbmdm())) throw new BusinessException("请选择值班部门！");
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(vo.getSsbmdm());
        zbbb.setSsbm(dept.getDeptname());
        zbbb.setSsbmid(dept.getDeptid());
        zbbb.setSsbmdm(dept.getDeptcode());
        zbbb.setSsxgajdm(dept.getFxjcode());
        zbbb.setSsxgajid(dept.getFxjid());
        zbbb.setSsxgaj(dept.getFxjname());
        zbbb.setSssgaj(dept.getDszname());
        zbbb.setSssgajdm(dept.getDszcode());
        zbbb.setSssgajid(dept.getDszid());
        zbbb.setXtSjly("2");
        this.saveRelevanceData(zbbb, vo, zbbb.getId());
        this.baseMapper.insert(zbbb);
        return zbbb.getId();
    }

    /**
     * 保存关联数据
     *
     * @param vo
     * @param ywid
     */
    public void saveRelevanceData(TbQwZbbb zbbb, TbQwZbbbVo vo, String ywid) {
        UserInfo user = UserInfoManager.get();
        if (vo != null) {
            List<TbQwJl> jlList = vo.getJlList();
            if (!CollectionUtils.isEmpty(jlList)) {
                List<TbQwJl> mjLists = new ArrayList<>();
                List<TbQwJl> fjLists = new ArrayList<>();
                for (TbQwJl jl : jlList) {
                    if (Constant.JLLX_MJ.equals(jl.getJllx())) {
                        mjLists.add(jl);
                    } else {
                        fjLists.add(jl);
                    }
                }
                zbbb.setZbmj(JSONArray.toJSONString(mjLists));
                zbbb.setZbfj(JSONArray.toJSONString(fjLists));
                zbbb.setMjsl(mjLists.size());
                zbbb.setFjsl(fjLists.size());
                for (TbQwJl jl : jlList) {
                    jl.setId(UUIDGenerator.getUUID());
                    jl.setZblx("4");
                    jl.setYwid(ywid);
                    jl.setXtSjzt("1");
                    jl.setJlzt("1");
                    jl.setXtSjly(StringUtils.isBlank(jl.getXtSjly()) ? "1" : jl.getXtSjly());
                    jl.setXtScbz("0");
                    if (user != null) {
                        jl.setSsbm(user.getDeptName());
                        jl.setSsbmdm(String.valueOf(user.getDeptId()));
                        jl.setSsxgaj(user.getFxjDeptName());
                        jl.setSsxgajdm(String.valueOf(user.getFxjDeptId()));
                        jl.setSssgaj(user.getDszDeptName());
                        jl.setSssgajdm(String.valueOf(user.getDszDeptId()));
                    }
                    tbQwJlMapper.insert(jl);
                }
            }
        }
    }

    @Override
    public boolean deleteBatch(List<String> list) {
        if (list.size() > 0) {
            for (String id : list) {
                deleteRelevanceData(id);
            }
            int rs = this.baseMapper.deleteZb(list);
            return rs > 0;
        }
        return true;
    }

    @Override
    public IPage<TbQwZbbbVo> queryPage(TbQwZbbbQuery zb) {
        IPage<TbQwZbbb> xfpbIPage = queryXfzb(zb);
        IPage<TbQwZbbbVo> voIPage = new Page<>(zb.getPageCurrent(), zb.getPageSize());
        voIPage.setTotal(xfpbIPage.getTotal());
        List<TbQwZbbb> records = xfpbIPage.getRecords();
        List<TbQwZbbbVo> vos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(records)) {
            for (TbQwZbbb record : records) {
                TbQwZbbbVo vo = new TbQwZbbbVo();
                BeanUtils.copyProperties(record, vo);
                List<TbQwJl> jl = tbQwJlMapper.queryListByYwid(new ArrayList<String>() {{
                    this.add(record.getId());
                }});
                vo.setJlList(jl);
                vos.add(vo);
            }
        }
        voIPage.setRecords(vos);
        return voIPage;
    }

    @Override
    public TbQwZbbb getMyBbInfoToday() {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            throw new BusinessException("登录异常，请重新登录！");
        }
        return this.baseMapper.getMyBbInfoToday(String.valueOf(user.getUserId()));
    }

    @Override
    public Integer startOrEndBb(TbQwXfbbStartOrEndBbDto dto) {
        TbQwZbbb bb = this.baseMapper.selectById(dto.getId());
        if ("0".equals(dto.getBbzt())) {
            bb.setBbkssj(new Date());
        } else {
            bb.setBbjssj(new Date());
        }
        bb.setBbzt(dto.getBbzt());
        return this.baseMapper.updateById(bb);
    }

    @Override
    public void authJsbb() {
        // 查询所有的已经报备的报备信息
        List<TbQwZbbb> bbList = this.baseMapper.selectList(
                new LambdaQueryWrapper<TbQwZbbb>()
                        .eq(TbQwZbbb::getBbzt, "0")
                        .eq(TbQwZbbb::getXtSjzt, "1")
        );
        bbList.forEach(bb -> {
            Date jssj;
            if (bb.getKssj().getTime() > bb.getJssj().getTime()) {
                jssj = DateUtils.strToDate(DateUtils.getQueryDateString(
                        DateUtils.getNextDate(bb.getZbrq(), "D", +1), "01") + " "
                        + DateUtils.getQueryDateString(bb.getJssj(), "10"), "02");
            } else {
                jssj = DateUtils.strToDate(DateUtils.getQueryDateString(bb.getZbrq(), "01") + " "
                        + DateUtils.getQueryDateString(bb.getJssj(), "10"), "02");
            }
            if (new Date().getTime() >= jssj.getTime()) {
                bb.setBbzt("1");
                bb.setBbjssj(new Date());
                this.baseMapper.updateById(bb);
            }
        });
    }

    @Override
    public Map<String, Object> getBbCountByDept(String time) {
        Map<String, Object> map = new HashMap<>();
        time = StringUtils.isBlank(time) ? DateUtils.getQueryDateString(new Date(), "01") : time;
        // 查询所有的部门信息
        List<DeptInfoVo> list = this.tbBaseAdaptRemoteService.getDeptAll();
        AtomicInteger y = new AtomicInteger();
        AtomicInteger n = new AtomicInteger();
        String finalTime = time;
        list.forEach(item -> {
            // 查询部门值班信息
            int count = this.baseMapper.selectCount(
                    new LambdaQueryWrapper<TbQwZbbb>()
                            .eq(TbQwZbbb::getSsbmdm, item.getDeptid())
                            .eq(TbQwZbbb::getXtSjzt, "1")
                            .eq(TbQwZbbb::getZbrq, finalTime)
            );
            if (count > 0) y.addAndGet(count);
            else n.addAndGet(1);
        });
        map.put("y", y);
        map.put("n", n);
        return map;
    }

    @Override
    public List<Map<String, Object>> getBbListByDept(String time) {
        List<Map<String, Object>> list = new ArrayList<>();
        time = StringUtils.isBlank(time) ? DateUtils.getQueryDateString(new Date(), "01") : time;
        // 查询所有的部门信息
        List<DeptInfoVo> deptList = this.tbBaseAdaptRemoteService.getDeptAll();
        for (DeptInfoVo dept : deptList) {
            Map<String, Object> map = new HashMap<>();
            map.put("ssbmid", dept.getDeptid());
            map.put("ssbmdm", dept.getDeptcode());
            map.put("ssbmmc", dept.getDeptname());
            List<TbQwZbbb> bbList = this.baseMapper.selectList(
                    new LambdaQueryWrapper<TbQwZbbb>()
                            .eq(TbQwZbbb::getSsbmdm, dept.getDeptid())
                            .eq(TbQwZbbb::getXtSjzt, "1")
                            .eq(TbQwZbbb::getZbrq, time)
            );
            if (bbList != null && bbList.size() > 0) {
                map.put("type", "ybb");
                map.put("list", bbList);
            } else {
                List<TbQwZbpbZq> zqList = this.tbQwZbpbZqMapper.getDeptByMonth(DateUtils.strToDate(time, "01"),
                        dept.getDeptid());
                if (zqList != null && zqList.size() > 0) {
                    map.put("type", "wbb");
                    map.put("list", zqList);
                } else {
                    map.put("type", "wpb");
                }
            }
            list.add(map);
        }
        return list;
    }

    @Override
    public Map<String, Object> getZbld() {
        UserInfo user = UserInfoManager.get();
        if (user == null) {
            return null;
        }
        TbQwZbbb bb = this.baseMapper.selectOne(
                new LambdaQueryWrapper<TbQwZbbb>()
                        .eq(TbQwZbbb::getSsbmdm, String.valueOf(user.getDeptId()))
                        .eq(TbQwZbbb::getZbrq, DateUtils.getQueryDateString(new Date(), "01"))
                        .eq(TbQwZbbb::getBbzt, "0")
                        .last(" limit 1")
        );
        if (bb == null) return null;
        Map<String, Object> map = new HashMap<>();
        map.put("zbldid", bb.getZbldId());
        map.put("zbldxm", bb.getZbldXm());
        map.put("zblddh", bb.getZbldDh());
        map.put("zbldsfzh", bb.getZbldSfzh());
        return map;
    }

    // 获取巡防排班数据
    public IPage<TbQwZbbb> queryXfzb(TbQwZbbbQuery xfpb) {
        IPage<TbQwZbbb> page = new Page<>(xfpb.getPageCurrent(), xfpb.getPageSize());
        LambdaQueryWrapper<TbQwZbbb> queryWrapper = new LambdaQueryWrapper<>();
//        UserInfo userInfo = UserInfoManager.get();
//        PermissionsUtil.queryWrapperUtil(queryWrapper, userInfo);
        xfpb.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(xfpb.getSsbmdm(), null));
        queryWrapper
                .like(StringUtils.isNotBlank(xfpb.getZbldXm()), TbQwZbbb::getZbldXm, xfpb.getZbldXm())
                .likeRight(StringUtils.isNotBlank(xfpb.getSsbmdm()), TbQwZbbb::getSsbmdm, xfpb.getSsbmdm());
        if (xfpb.getStartTime() != null && xfpb.getEndTime() == null) {
            queryWrapper.ge(TbQwZbbb::getZbrq, xfpb.getStartTime());
        }
        if (xfpb.getStartTime() == null && xfpb.getEndTime() != null) {
            queryWrapper.le(TbQwZbbb::getZbrq, xfpb.getEndTime());
        }
        if (xfpb.getStartTime() != null && xfpb.getEndTime() != null) {
            queryWrapper.between(TbQwZbbb::getZbrq, xfpb.getStartTime(), xfpb.getEndTime());
        }
        queryWrapper.orderByDesc(TbQwZbbb::getZbrq);
        return this.baseMapper.selectPage(page, queryWrapper);
    }

    /**
     * 删除关联数据
     *
     * @param id
     */
    public void deleteRelevanceData(String id) {
        tbQwJlMapper.deleteByYwid(id);
    }
}
