package com.testor.module.emergency.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.module.emergency.dao.TEmergencyWorkingGroupDao;
import com.testor.module.emergency.model.domain.TEmergencyWorkingGroup;
import com.testor.module.emergency.model.dto.TEmergencyWorkingGroupDTO;
import com.testor.module.emergency.model.dto.TEmergencyWorkingGroupParam;
import com.testor.module.emergency.model.dto.TEmergencyWorkingGroupUpdateAddDel;
import com.testor.module.emergency.model.dto.TEmergencyWorkingUserParam;
import com.testor.module.emergency.model.vo.TEmergencyWorkingUserVO;
import com.testor.module.emergency.service.TEmergencyWorkingGroupService;
import com.testor.module.emergency.service.TEmergencyWorkingUserService;
import com.tongtech.tfw.backend.common.exception.BusinessException;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 应急救援组织机构Service业务层处理
 *
 * @author testor-framework
 * @date 2022-11-17 11:51:40
 */
@Service
public class TEmergencyWorkingGroupServiceImpl extends SuperServiceImpl<TEmergencyWorkingGroupDao, TEmergencyWorkingGroup> implements TEmergencyWorkingGroupService {

    @Autowired(required = false)
    private TEmergencyWorkingGroupDao tEmergencyWorkingGroupDao;

    @Autowired(required = false)
    private SysRuleService sysRuleService;

    @Autowired(required = false)
    private TEmergencyWorkingUserService tEmergencyWorkingUserService;


    @Override
    public IPage getResponsibilityList(TEmergencyWorkingGroupParam tEmergencyWorkingGroupParam) {
        Page<TEmergencyWorkingGroupDTO> page = new Page<>();
        page.setSize(tEmergencyWorkingGroupParam.getLimit());
        page.setCurrent(tEmergencyWorkingGroupParam.getPage());
        if (ObjectUtil.isEmpty(tEmergencyWorkingGroupParam.getIds())){
            tEmergencyWorkingGroupParam.setIds(null);
        }
        IPage<TEmergencyWorkingGroupDTO> page1 = tEmergencyWorkingGroupDao.getResponsibilityList(page, tEmergencyWorkingGroupParam);
        List<TEmergencyWorkingGroupDTO> records = page1.getRecords();
        records.forEach(tEmergencyWorkingGroupDTO -> {
            List list = JSONObject.parseObject(tEmergencyWorkingGroupDTO.getResponsibility(), List.class);
            tEmergencyWorkingGroupDTO.setResponsibilityList(list);
        });
        page1.setRecords(records);
        return page1;
    }

    @Override
    public List<TEmergencyWorkingUserVO> getWorkingGroupListAndUser(String id) {
        List<TEmergencyWorkingGroupDTO> tEmergencyWorkingGroupDTOList = tEmergencyWorkingGroupDao.getWorkingGroupList(id);
        Map<Boolean, List<TEmergencyWorkingGroupDTO>> isEmptyMap = tEmergencyWorkingGroupDTOList
                .stream().collect(Collectors.partitioningBy(tEmergencyWorkingGroupDTO -> ObjectUtil.isEmpty(tEmergencyWorkingGroupDTO.getName())));
        //获取组数据
        List<TEmergencyWorkingGroupDTO> groupDTOS = isEmptyMap.get(false);

        List<String> groupId = groupDTOS.stream().map(TEmergencyWorkingGroup::getId).collect(Collectors.toList());
        TEmergencyWorkingUserParam tEmergencyWorkingUserParam = new TEmergencyWorkingUserParam();
        tEmergencyWorkingUserParam.setIds(groupId);
        List<TEmergencyWorkingUserVO> records = tEmergencyWorkingUserService.getUserList(tEmergencyWorkingUserParam).getRecords();
        if (records == null){
            throw new RuntimeException("没有工作组");
        }
        Map<String, Map<String, List<TEmergencyWorkingUserVO>>> collect = records.stream().collect(Collectors.groupingBy(TEmergencyWorkingUserVO::getLittleGroupName, Collectors.groupingBy(TEmergencyWorkingUserVO::getGroupName)));
        Set<String> strings = collect.keySet();
        //第一层
        ArrayList<TEmergencyWorkingUserVO> tEmergencyWorkingUserVOS = new ArrayList<>();
        for (String string : strings) {
            TEmergencyWorkingUserVO tEmergencyWorkingUserVO = new TEmergencyWorkingUserVO();
            ArrayList<TEmergencyWorkingUserVO> tEmergencyWorkingUserVOS1 = new ArrayList<>();

            tEmergencyWorkingUserVO.setGroupName(string);
            Map<String, List<TEmergencyWorkingUserVO>> stringListMap = collect.get(string);
            Set<String> strings1 = stringListMap.keySet();
            for (String s : strings1) {
                TEmergencyWorkingUserVO tEmergencyWorkingUserVO1 = new TEmergencyWorkingUserVO();
                tEmergencyWorkingUserVO1.setLittleGroupName(s);
                tEmergencyWorkingUserVO1.setTEmergencyWorkingUserVOList(stringListMap.get(s));
                tEmergencyWorkingUserVOS1.add(tEmergencyWorkingUserVO1);
            }
            tEmergencyWorkingUserVO.setTEmergencyWorkingUserVOList(tEmergencyWorkingUserVOS1);
            tEmergencyWorkingUserVOS.add(tEmergencyWorkingUserVO);
        }

        return tEmergencyWorkingUserVOS;
    }


    @Override
    public List<TEmergencyWorkingGroupDTO> getWorkingGroupList(String id) {
        List<TEmergencyWorkingGroupDTO> tEmergencyWorkingGroupDTOList = tEmergencyWorkingGroupDao.getWorkingGroupList(id);
        Map<Boolean, List<TEmergencyWorkingGroupDTO>> isEmptyMap = tEmergencyWorkingGroupDTOList
                .stream().collect(Collectors.partitioningBy(tEmergencyWorkingGroupDTO -> ObjectUtil.isEmpty(tEmergencyWorkingGroupDTO.getName())));
        //获取组数据
        List<TEmergencyWorkingGroupDTO> groupDTOS = isEmptyMap.get(true);

        //获取小组数据
        List<TEmergencyWorkingGroupDTO> littleList = isEmptyMap.get(false);
        //处理小组职责数据
        littleList.forEach(tEmergencyWorkingGroupDTO -> {
            List list = JSONObject.parseObject(tEmergencyWorkingGroupDTO.getResponsibility(), List.class);
            tEmergencyWorkingGroupDTO.setResponsibilityList(list);
        });

        //分组
        if (ObjectUtil.isNotEmpty(littleList)) {
            Map<String, List<TEmergencyWorkingGroupDTO>> groupMap = littleList.stream().collect(Collectors.groupingBy(TEmergencyWorkingGroupDTO::getGroupName));

            groupDTOS.forEach(tEmergencyWorkingGroupDTO -> {
                String groupName = tEmergencyWorkingGroupDTO.getGroupName();
                List<TEmergencyWorkingGroupDTO> tEmergencyWorkingGroupDTOS = groupMap.get(groupName);
                tEmergencyWorkingGroupDTO.setTEmergencyWorkingGroupDTOList(tEmergencyWorkingGroupDTOS);
            });
            return groupDTOS;
        }
        return null;
    }


    @Override
    @Transactional
    public boolean updateAddDel(TEmergencyWorkingGroupUpdateAddDel tEmergencyWorkingGroupUpdateAddDel) throws BusinessException {
        //校验是否重复添加
        int size = tEmergencyWorkingGroupUpdateAddDel.getTEmergencyWorkingGroupDTOList().stream()
                .map(TEmergencyWorkingGroup::getGroupId).distinct().collect(Collectors.toList()).size();
        int size1 = tEmergencyWorkingGroupUpdateAddDel.getTEmergencyWorkingGroupDTOList().size();
        int compare = Integer.compare(size, size1);
        if (compare != 0) {
            throw new BusinessException("应急救援组不可重复添加");
        }
        UpdateWrapper<TEmergencyWorkingGroup> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("org_id", tEmergencyWorkingGroupUpdateAddDel.getOrgId());
        //先删除
        updateWrapper.set("status", 1);
        this.update(updateWrapper);

        ArrayList<TEmergencyWorkingGroupDTO> tEmergencyWorkingGroupDTOList = new ArrayList<>();
        tEmergencyWorkingGroupUpdateAddDel.getTEmergencyWorkingGroupDTOList().forEach(tEmergencyWorkingGroupDTO -> {
            tEmergencyWorkingGroupDTOList.add(tEmergencyWorkingGroupDTO);
            tEmergencyWorkingGroupDTOList.addAll(tEmergencyWorkingGroupDTO.getTEmergencyWorkingGroupDTOList());
        });

        //处理职责数据
        Map<Boolean, List<TEmergencyWorkingGroup>> collect = tEmergencyWorkingGroupDTOList.stream().map(tEmergencyWorkingGroupDTO -> {
            String json = JSONObject.toJSONString(tEmergencyWorkingGroupDTO.getResponsibilityList());
            tEmergencyWorkingGroupDTO.setResponsibility(json);
            tEmergencyWorkingGroupDTO.setStatus("0");
            TEmergencyWorkingGroup tEmergencyWorkingGroup = BeanUtil.copyProperties(tEmergencyWorkingGroupDTO, TEmergencyWorkingGroup.class);
            return tEmergencyWorkingGroup;
        }).collect(Collectors.partitioningBy(tEmergencyWorkingGroup -> ObjectUtil.isEmpty(tEmergencyWorkingGroup.getId())));
        saveBatch(collect.get(true));
        updateBatchById(collect.get(false));
        return true;
    }

}
