package com.mosty.base.manager.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.manager.mapper.*;
import com.mosty.base.manager.remote.TbBaseAdaptRemoteService;
import com.mosty.base.manager.service.TbJcglJzService;
import com.mosty.base.model.dto.qwzx.AppSearchQuery;
import com.mosty.base.model.entity.jcgl.*;
import com.mosty.base.model.query.jcgl.TbJcglJzQuery;
import com.mosty.base.model.vo.base.DeptInfoVo;
import com.mosty.base.model.vo.jcgl.TbJcglJzAllVo;
import com.mosty.base.utils.UUIDGenerator;
import com.mosty.common.token.UserInfo;
import com.mosty.common.token.UserInfoManager;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * <p>
 * 勤务警组服务实现类
 * </p>
 *
 * @author zengbo
 * @since 2022-06-30
 */
@AllArgsConstructor
@Service
public class TbJcglJzServiceImpl extends ServiceImpl<TbJcglJzMapper, TbJcglJz>
        implements TbJcglJzService {

    //警组
    private TbJcglJzMapper tbJcglJzMapper;
    //警组人员
    private TbJcglJzRyMapper tbJcglJzRyMapper;
    //警组车辆
    private TbJcglJzClMapper TbJcglJzClMapper;
    //通讯装备
    private TbJcglJzZnzbMapper tbJcglJzZnzbMapper;
    //警组警用器械
    private TbJcglJzJyqxMapper tbJcglJzJyqxMapper;
    // 部门feign调用
    private TbBaseAdaptRemoteService tbBaseAdaptRemoteService;

    @Override
    public IPage<TbJcglJzAllVo> queryList(TbJcglJzQuery dto) {
        dto.setSsbmdm(this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null));
//        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("createSql", userInfo != null ? PermissionsUtil.createSql("a", userInfo) : "");
        map.put("dto", dto);
        int count = this.tbJcglJzMapper.queryCount(map);
        List<TbJcglJz> list = this.tbJcglJzMapper.queryList(map);
        List<TbJcglJzAllVo> rList = new ArrayList<>();
        list.forEach(item -> {
            TbJcglJzAllVo vo = new TbJcglJzAllVo();
            BeanUtils.copyProperties(item, vo);
            // 车辆
            List<TbJcglJzCl> clList = this.TbJcglJzClMapper.selectList(
                    new LambdaQueryWrapper<TbJcglJzCl>()
                            .eq(TbJcglJzCl::getQwjzId, item.getId())
                            .eq(TbJcglJzCl::getXtSjzt, "1")
            );
            vo.setClList(clList);
            // 人员
            List<TbJcglJzRy> ryList = this.tbJcglJzRyMapper.selectList(
                    new LambdaQueryWrapper<TbJcglJzRy>()
                            .eq(TbJcglJzRy::getQwjzId, item.getId())
                            .eq(TbJcglJzRy::getXtSjzt, "1")
            );
            vo.setJzryList(ryList);
            // 警用器械
            List<TbJcglJzJyqx> jyqxList = this.tbJcglJzJyqxMapper.selectList(
                    new LambdaQueryWrapper<TbJcglJzJyqx>()
                            .eq(TbJcglJzJyqx::getQwjzId, item.getId())
                            .eq(TbJcglJzJyqx::getXtSjzt, "1")
            );
            vo.setJyqxList(jyqxList);
            // 智能装备
            List<TbJcglJzZnzb> znzbList = this.tbJcglJzZnzbMapper.selectList(
                    new LambdaQueryWrapper<TbJcglJzZnzb>()
                            .eq(TbJcglJzZnzb::getQwjzId, item.getId())
                            .eq(TbJcglJzZnzb::getXtSjzt, "1")
            );
            vo.setTxzbList(znzbList);
            rList.add(vo);
        });
        IPage<TbJcglJzAllVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
        page.setRecords(rList);
        page.setTotal(count);
        return page;
    }

    @Override
    public TbJcglJzAllVo selectById(String id) {
        TbJcglJz jz = this.tbJcglJzMapper.selectById(id);
        TbJcglJzAllVo vo = new TbJcglJzAllVo();
        BeanUtils.copyProperties(jz, vo);
        // 车辆
        List<TbJcglJzCl> clList = this.TbJcglJzClMapper.selectList(
                new LambdaQueryWrapper<TbJcglJzCl>()
                        .eq(TbJcglJzCl::getQwjzId, id)
                        .eq(TbJcglJzCl::getXtSjzt, "1")
        );
        vo.setClList(clList);
        // 人员
        List<TbJcglJzRy> ryList = this.tbJcglJzRyMapper.selectList(
                new LambdaQueryWrapper<TbJcglJzRy>()
                        .eq(TbJcglJzRy::getQwjzId, id)
                        .eq(TbJcglJzRy::getXtSjzt, "1")
        );
        vo.setJzryList(ryList);
        // 警用器械
        List<TbJcglJzJyqx> jyqxList = this.tbJcglJzJyqxMapper.selectList(
                new LambdaQueryWrapper<TbJcglJzJyqx>()
                        .eq(TbJcglJzJyqx::getQwjzId, id)
                        .eq(TbJcglJzJyqx::getXtSjzt, "1")
        );
        vo.setJyqxList(jyqxList);
        // 智能装备
        List<TbJcglJzZnzb> znzbList = this.tbJcglJzZnzbMapper.selectList(
                new LambdaQueryWrapper<TbJcglJzZnzb>()
                        .eq(TbJcglJzZnzb::getQwjzId, id)
                        .eq(TbJcglJzZnzb::getXtSjzt, "1")
        );
        vo.setTxzbList(znzbList);
        return vo;
    }

    @Override
    public int saveJz(TbJcglJzAllVo jzVo) {
        TbJcglJz jz = new TbJcglJz();
        BeanUtils.copyProperties(jzVo, jz);
        jz.setXtSjly("1");
        String id = UUIDGenerator.getUUID();
        jz.setId(id);
        jz.setJzBh(id);
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(jzVo.getSsbmdm());
        saveRelevanceData(jzVo, jz, dept);
        if (dept != null) {
            jz.setSsbm(dept.getDeptname());
            jz.setSsbmid(dept.getDeptid());
            jz.setSsbmdm(dept.getDeptcode());
            jz.setSsxgajdm(dept.getFxjcode());
            jz.setSsxgajid(dept.getFxjid());
            jz.setSsxgaj(dept.getFxjname());
            jz.setSssgaj(dept.getDszname());
            jz.setSssgajdm(dept.getDszcode());
            jz.setSssgajid(dept.getDszid());
        }
        return tbJcglJzMapper.insert(jz);
    }

    @Override
    public int updateJz(TbJcglJzAllVo jzVo) {
        TbJcglJz jz = new TbJcglJz();
        BeanUtils.copyProperties(jzVo, jz);
        deleteRelevanceData(jz.getId());
        DeptInfoVo dept = this.tbBaseAdaptRemoteService.getOrgByOrgcode(jzVo.getSsbmdm());
        saveRelevanceData(jzVo, jz, dept);
        if (dept != null) {
            jz.setSsbm(dept.getDeptname());
            jz.setSsbmid(dept.getDeptid());
            jz.setSsbmdm(dept.getDeptcode());
            jz.setSsxgajdm(dept.getFxjcode());
            jz.setSsxgajid(dept.getFxjid());
            jz.setSsxgaj(dept.getFxjname());
            jz.setSssgaj(dept.getDszname());
            jz.setSssgajdm(dept.getDszcode());
            jz.setSssgajid(dept.getDszid());
        }
        return tbJcglJzMapper.updateById(jz);
    }

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

    @Override
    public Page<TbJcglJzAllVo> selectJzList(AppSearchQuery dto) {
        UserInfo user = UserInfoManager.get();
        LambdaQueryWrapper<TbJcglJz> wrapper = new LambdaQueryWrapper<TbJcglJz>()
                .eq(TbJcglJz::getXtSjzt, "1");

        if ("1".equals(dto.getType())) {
            wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), TbJcglJz::getJzMc, dto.getKeyword())
                    .eq(TbJcglJz::getSsbmdm, String.valueOf(user.getDeptCode()))
                    .orderByAsc(TbJcglJz::getXtCjsj)
            ;
        } else {
            String ssbm = this.tbBaseAdaptRemoteService.getSsbm(dto.getSsbmdm(), null);
            wrapper.likeRight(StringUtils.isNotBlank(ssbm), TbJcglJz::getSsbmdm, ssbm)
                    .and(StringUtils.isNotBlank(dto.getKeyword()),
                            it -> it.like(TbJcglJz::getJzMc, dto.getKeyword())
                                    .or()
                                    .like(TbJcglJz::getSsbm, dto.getKeyword())
                    )
                    .orderByAsc(TbJcglJz::getXtCjsj)
            ;
        }
        Page<TbJcglJz> tbJcglJzPage = this.baseMapper.selectPage(new Page<>(dto.getPageCurrent(), dto.getPageSize()), wrapper);
        List<TbJcglJzAllVo> rList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(tbJcglJzPage) && !CollectionUtils.isEmpty(tbJcglJzPage.getRecords())) {
            tbJcglJzPage.getRecords().forEach(item -> {
                TbJcglJzAllVo vo = new TbJcglJzAllVo();
                BeanUtils.copyProperties(item, vo);
                // 车辆
                List<TbJcglJzCl> clList = this.TbJcglJzClMapper.selectList(
                        new LambdaQueryWrapper<TbJcglJzCl>()
                                .eq(TbJcglJzCl::getQwjzId, item.getId())
                                .eq(TbJcglJzCl::getXtSjzt, "1")
                );
                vo.setClList(clList);
                // 人员
                List<TbJcglJzRy> ryList = this.tbJcglJzRyMapper.selectList(
                        new LambdaQueryWrapper<TbJcglJzRy>()
                                .eq(TbJcglJzRy::getQwjzId, item.getId())
                                .eq(TbJcglJzRy::getXtSjzt, "1")
                );
                vo.setJzryList(ryList);
                // 警用器械
                List<TbJcglJzJyqx> jyqxList = this.tbJcglJzJyqxMapper.selectList(
                        new LambdaQueryWrapper<TbJcglJzJyqx>()
                                .eq(TbJcglJzJyqx::getQwjzId, item.getId())
                                .eq(TbJcglJzJyqx::getXtSjzt, "1")
                );
                vo.setJyqxList(jyqxList);
                // 智能装备
                List<TbJcglJzZnzb> znzbList = this.tbJcglJzZnzbMapper.selectList(
                        new LambdaQueryWrapper<TbJcglJzZnzb>()
                                .eq(TbJcglJzZnzb::getQwjzId, item.getId())
                                .eq(TbJcglJzZnzb::getXtSjzt, "1")
                );
                vo.setTxzbList(znzbList);
                rList.add(vo);
            });
            Page<TbJcglJzAllVo> page = new Page<>(dto.getPageCurrent(), dto.getPageSize());
            BeanUtils.copyProperties(tbJcglJzPage, page);
            page.setRecords(rList);
            return page;
        }
        return null;
    }

    // 保存关联数据
    public void saveRelevanceData(TbJcglJzAllVo vo, TbJcglJz jz, DeptInfoVo dept) {
        String jzid = jz.getId();
        if (vo != null) {
            List<TbJcglJzCl> clList = vo.getClList();
            List<TbJcglJzJyqx> jyqxList = vo.getJyqxList();
            List<TbJcglJzRy> jzryList = vo.getJzryList();
            List<TbJcglJzZnzb> txzbList = vo.getTxzbList();
            if (!CollectionUtils.isEmpty(clList)) {
                for (TbJcglJzCl cl : clList) {
                    cl.setQwjzId(jzid);
                    cl.setXtSjly("1");
                    TbJcglJzClMapper.insert(cl);
                }
                jz.setJzLx("1");
            } else {
                jz.setJzLx("2");
            }
            if (!CollectionUtils.isEmpty(jyqxList)) {
                for (TbJcglJzJyqx jyqx : jyqxList) {
                    jyqx.setQwjzId(jzid);
                    jyqx.setXtSjly("1");
                    tbJcglJzJyqxMapper.insert(jyqx);
                }
            }
            int mjsl = 0, fjsl = 0;
            if (!CollectionUtils.isEmpty(jzryList)) {
                for (TbJcglJzRy ry : jzryList) {
                    if ("01".equals(ry.getJllx())) {
                        mjsl++;
                    } else if ("02".equals(ry.getJllx())) {
                        fjsl++;
                    }
                    ry.setQwjzId(jzid);
                    ry.setXtSjly("1");
                    tbJcglJzRyMapper.insert(ry);
                }
                if (mjsl > 0 && fjsl == 0) {
                    jz.setJzFl("1");
                } else if (mjsl == 0 && fjsl > 0) {
                    jz.setJzFl("2");
                } else {
                    jz.setJzFl("3");
                }
            }
            if (!CollectionUtils.isEmpty(txzbList)) {
                for (TbJcglJzZnzb txzb : txzbList) {
                    txzb.setQwjzId(jzid);
                    txzb.setXtSjly("1");
                    tbJcglJzZnzbMapper.insert(txzb);
                }
            }
        }
    }

    /**
     * 删除关联表数据
     *
     * @param id
     */
    public void deleteRelevanceData(String id) {
        tbJcglJzRyMapper.deleteByQwjzId(id);
        TbJcglJzClMapper.deleteByQwjzId(id);
        tbJcglJzZnzbMapper.deleteByQwjzId(id);
        tbJcglJzJyqxMapper.deleteByQwjzId(id);
    }
    //同步一下警用器械

    @Override
    public void tbJzQx() {
        List<TbJcglJz> tbJcglJzs = this.baseMapper.selectList(new LambdaQueryWrapper<>());
        List<TbJcglJzJyqx> jzJyqxList = this.tbJcglJzJyqxMapper.selectList(new LambdaQueryWrapper<>());
        if (!CollectionUtils.isEmpty(tbJcglJzs)) {
            for (TbJcglJz jz : tbJcglJzs) {
                for (TbJcglJzJyqx jzJyqx: jzJyqxList){
                    jzJyqx.setId(null);
                    jzJyqx.setQwjzId(jz.getId());
                    this.tbJcglJzJyqxMapper.insert(jzJyqx);
                }
            }
        }
    }


}
