package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.annotation.TableField;
import com.ruoyi.common.constant.DeletedEnum;
import com.ruoyi.common.core.domain.BaseLongitudeLatitude;
import com.ruoyi.common.core.domain.entity.TbSysArea;
import com.ruoyi.common.core.domain.entity.TbSysAreaUser;
import com.ruoyi.common.enums.BaseLongitudeLatitudeEnumServiceCode;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.CodeUtils;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.vo.AreaResultDTO;
import com.ruoyi.system.domain.vo.AreaTreeResultDTO;
import com.ruoyi.system.domain.vo.AreaUserDTO;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.TbSysAreaMapper;
import com.ruoyi.system.service.IBaseLongitudeLatitudeService;
import com.ruoyi.system.service.ITbSysAreaService;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * 区域Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-01
 */
@Service
public class TbSysAreaServiceImpl implements ITbSysAreaService {
    @Autowired
    private TbSysAreaMapper tbSysAreaMapper;

//    @Autowired
//    private TbSysAreaUserRelationMapper tbSysAreaUserRelationMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private IBaseLongitudeLatitudeService baseLongitudeLatitudeService;


    /**
     * 查询区域
     *
     * @param id 区域主键
     * @return 区域
     */
    @Override
    public TbSysArea selectTbSysAreaById(Long id) {
        TbSysArea tbSysArea = tbSysAreaMapper.selectTbSysAreaById(id);
        //填充负责人信息
//        List<TbSysAreaUser> sysUsers = tbSysAreaUserRelationMapper.selectUserNickNameByAreaIdList(Arrays.asList(tbSysArea.getId()));
        List<TbSysAreaUser> sysUsers = tbSysAreaMapper.selectUserNickNameByAreaIdList(Arrays.asList(tbSysArea.getId()));
        tbSysArea.setUserList(sysUsers);
        return tbSysArea;
    }

    /**
     * 查询区域列表
     *
     * @param tbSysArea 区域
     * @return 区域
     */
    @Override
    public List<TbSysArea> selectTbSysAreaList(TbSysArea tbSysArea) {
        List<TbSysArea> tbSysAreaList = tbSysAreaMapper.selectTbSysAreaList(tbSysArea);
        //填充负责人
        if (!CollectionUtils.isEmpty(tbSysAreaList)) {
            List<Long> areaIdList = tbSysAreaList.stream().map(TbSysArea::getId).collect(Collectors.toList());
//            List<TbSysAreaUserRelation> sysUsers = tbSysAreaUserRelationMapper.selectUserNickNameByAreaIdList(areaIdList);
            List<TbSysAreaUser> sysUsers = tbSysAreaMapper.selectUserNickNameByAreaIdList(areaIdList);
            Map<Long, List<TbSysAreaUser>> userMap = sysUsers.stream().collect(Collectors.groupingBy(TbSysAreaUser::getAreaId));
            for (TbSysArea sysArea : tbSysAreaList) {
                sysArea.setUserList(userMap.get(sysArea.getId()));
            }
        }
        return tbSysAreaList;
    }

    @Override
    public List<AreaTreeResultDTO> areaTree() {
        List<TbSysArea> tbSysAreaList = tbSysAreaMapper.selectTbSysAreaList(new TbSysArea());

        List<AreaTreeResultDTO> list = new ArrayList<>(tbSysAreaList.size());

        for (TbSysArea tbSysArea : tbSysAreaList) {
            AreaTreeResultDTO areaResultDTO = new AreaTreeResultDTO();
            areaResultDTO.setId(tbSysArea.getId());
            areaResultDTO.setName(tbSysArea.getAreaName());
            areaResultDTO.setParentId(tbSysArea.getParentId());
            areaResultDTO.setChildren(null);
            list.add(areaResultDTO);
        }

        List<AreaTreeResultDTO> areaTree = areaTree(list, NumberUtils.LONG_ZERO);

        return areaTree;
    }

    /**
     * 获取区域树
     *
     * @param areaResultDTOS
     * @param parentCategoryId
     * @return
     */
    public static List<AreaTreeResultDTO> areaTree(List<AreaTreeResultDTO> areaResultDTOS, Long parentCategoryId) {
        if (CollectionUtils.isEmpty(areaResultDTOS)) {
            return new ArrayList<>(0);
        }
        List<AreaTreeResultDTO> treeNodes = new ArrayList<>(areaResultDTOS.size());
        areaResultDTOS.stream().forEach(categoryVo -> {
            if (categoryVo != null) {
                //根据父id判断是否有从属关系
                boolean isChildren = areaResultDTOS.stream().anyMatch(categoryVo1 -> categoryVo.getParentId().equals(parentCategoryId));
                if (isChildren) {
                    AreaTreeResultDTO node = categoryVo;
                    //设置子节点
                    List<AreaTreeResultDTO> children = areaTree(areaResultDTOS, node.getId());
                    node.setChildren(children);
                    treeNodes.add(node);
                }
            }
        });
        return treeNodes;
    }


    /**
     * param mapArray 区域管理的列表中添加坐标数组
     *
     * @return
     */
    @Override
//    public List<AreaResultDTO> getAreaTree(Integer mapArray) {
    public List<AreaResultDTO> getAreaTree() {
        List<TbSysArea> tbSysAreaList = tbSysAreaMapper.selectTbSysAreaList(new TbSysArea());

        List<AreaResultDTO> list = new ArrayList<>();

        List<TbSysAreaUser> sysAreaUserList = sysUserMapper.selectAreaUser(null);

        List<AreaUserDTO> areaUserDTOList = new ArrayList<>();
        Map<Long, List<AreaUserDTO>> userMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(sysAreaUserList)) {
            for (TbSysAreaUser sysAreaUser : sysAreaUserList) {
                AreaUserDTO areaUserDTO = new AreaUserDTO();
                BeanUtils.copyProperties(sysAreaUser, areaUserDTO);
                areaUserDTO.setId(sysAreaUser.getAreaId());
                areaUserDTOList.add(areaUserDTO);
            }
            userMap = areaUserDTOList.stream().collect(Collectors.groupingBy(AreaUserDTO::getId));
        }


        //查询区域经纬度
        BaseLongitudeLatitude baseLongitudeLatitude = new BaseLongitudeLatitude();
        baseLongitudeLatitude.setServiceCode(BaseLongitudeLatitudeEnumServiceCode.SYS_AREA.getValue());
        List<BaseLongitudeLatitude> baseLongitudeLatitudeList = baseLongitudeLatitudeService.selectBaseLongitudeLatitudeList(baseLongitudeLatitude);

        List<BaseLongitudeLatitude> baseLongitudeLatitudeDTOList = new ArrayList<>();
        Map<String, List<BaseLongitudeLatitude>> baseLongitudeLatitudeDTOMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(baseLongitudeLatitudeList)) {
            for (BaseLongitudeLatitude data : baseLongitudeLatitudeList) {
//                AreaUserDTO areaUserDTO = new AreaUserDTO();
//                BeanUtils.copyProperties(sysAreaUser, areaUserDTO);
//                areaUserDTO.setId(sysAreaUser.getAreaId());
                baseLongitudeLatitudeDTOList.add(data);
            }
            baseLongitudeLatitudeDTOMap = baseLongitudeLatitudeDTOList.stream().collect(Collectors.groupingBy(BaseLongitudeLatitude::getServiceId));
        }

//        if(mapArray != null && mapArray == 1){
//            BaseLongitudeLatitude  = new BaseLongitudeLatitude();
//            serviceIdList
//        }


        for (TbSysArea tbSysArea : tbSysAreaList) {
            AreaResultDTO areaResultDTO = new AreaResultDTO();
            BeanUtils.copyProperties(tbSysArea, areaResultDTO);
            //封装人员
            areaResultDTO.setAreaUserList(userMap.get(tbSysArea.getId()));
            //封装经纬度坐标
            areaResultDTO.setCurrentLnglatList(baseLongitudeLatitudeDTOMap.get(tbSysArea.getId().toString()));

            list.add(areaResultDTO);


            // 经纬度的集合

            List<BaseLongitudeLatitude> currentLnglatList = new ArrayList<>();
        }

        List<AreaResultDTO> areaTree = getAreaTree(list, NumberUtils.LONG_ZERO);

        return areaTree;
    }

    /**
     * 获取区域树
     *
     * @param areaResultDTOS
     * @param parentCategoryId
     * @return
     */
    public static List<AreaResultDTO> getAreaTree(List<AreaResultDTO> areaResultDTOS, Long parentCategoryId) {
        if (CollectionUtils.isEmpty(areaResultDTOS)) {
            return new ArrayList<>(0);
        }
        List<AreaResultDTO> treeNodes = new ArrayList<>(areaResultDTOS.size());
        areaResultDTOS.stream().forEach(categoryVo -> {
            if (categoryVo != null) {
                //根据商品分类父id判断是否有从属关系
                boolean isChildren = areaResultDTOS.stream().anyMatch(categoryVo1 -> categoryVo.getParentId().equals(parentCategoryId));
                if (isChildren) {
                    AreaResultDTO node = categoryVo;
                    //设置子节点
                    List<AreaResultDTO> children = getAreaTree(areaResultDTOS, node.getId());
                    node.setChildList(children);
                    treeNodes.add(node);
                }
            }
        });
        return treeNodes;
    }


    /**
     * 新增区域
     *
     * @param tbSysArea 区域
     * @return 结果
     */
    @Override
    @Transactional
    public int insertTbSysArea(TbSysArea tbSysArea) {
        if (tbSysArea.getPostId() == null) {
            throw new BaseException("岗位ID为空！");
        }
        Date now = new Date();
        tbSysArea.setCreateDate(now);
        tbSysArea.setUpdateDate(now);
        tbSysArea.setIsDel(DeletedEnum.VALID.getValue());
        int count = tbSysAreaMapper.insertTbSysArea(tbSysArea);
//        for(Long userId : tbSysArea.getUserIdList()){
//            TbSysAreaUserRelation tbSysAreaUserRelation = new TbSysAreaUserRelation();
//            tbSysAreaUserRelation.setAreaId(tbSysArea.getId());
//            tbSysAreaUserRelation.setUserId(userId);
//            tbSysAreaUserRelation.setCreateUserId(tbSysArea.getCreateUserId());
//            tbSysAreaUserRelation.setCompanyCode(tbSysArea.getCompanyCode());
//            tbSysAreaUserRelation.setCreateDate(now);
//            tbSysAreaUserRelationMapper.insertTbSysAreaUserRelation(tbSysAreaUserRelation);
//        }
        Long id = tbSysArea.getId();
        int time = 1;
        Date createDate = new Date();
        List<BaseLongitudeLatitude> currentLnglatList = tbSysArea.getCurrentLnglatList();
        if (!CollectionUtils.isEmpty(currentLnglatList) && id != null) {
            for (BaseLongitudeLatitude dataInfo : currentLnglatList) {
                dataInfo.setId(UUID.randomUUID().toString());
                dataInfo.setServiceId(id.toString());
                dataInfo.setServiceCode(BaseLongitudeLatitudeEnumServiceCode.SYS_AREA.getValue());
                dataInfo.setCreateDefault();
                dataInfo.setCreateDate(DateUtils.addSeconds(createDate, time++));
                baseLongitudeLatitudeService.insertBaseLongitudeLatitude(dataInfo);
            }
        }
        return count;
    }

    /**
     * 修改区域
     *
     * @param tbSysArea 区域
     * @return 结果
     */
    @Override
    @Transactional
    public int updateTbSysArea(TbSysArea tbSysArea) {
        if (tbSysArea.getPostId() == null) {
            throw new BaseException("岗位ID为空！");
        }
        Date now = new Date();
        tbSysArea.setUpdateDate(now);
        int count = tbSysAreaMapper.updateTbSysArea(tbSysArea);
//        tbSysAreaUserRelationMapper.deleteTbSysAreaUserRelationByAreaIds(Arrays.asList(tbSysArea.getId()));
//        for(Long userId : tbSysArea.getUserIdList()){
//            TbSysAreaUserRelation tbSysAreaUserRelation = new TbSysAreaUserRelation();
//            tbSysAreaUserRelation.setAreaId(tbSysArea.getId());
//            tbSysAreaUserRelation.setUserId(userId);
//            tbSysAreaUserRelation.setCreateUserId(tbSysArea.getUpdateUserId());
//            tbSysAreaUserRelation.setCompanyCode(tbSysArea.getCompanyCode());
//            tbSysAreaUserRelation.setCreateDate(now);
//            tbSysAreaUserRelationMapper.insertTbSysAreaUserRelation(tbSysAreaUserRelation);
//        }


        Long id = tbSysArea.getId();


        //插入经纬度
        List<BaseLongitudeLatitude> currentLnglatList = tbSysArea.getCurrentLnglatList();
        if (!CollectionUtils.isEmpty(currentLnglatList) && id != null) {
            //删除经纬度
            String serviceId = id.toString();
            String serviceCode = BaseLongitudeLatitudeEnumServiceCode.SYS_AREA.getValue();
            baseLongitudeLatitudeService.deleteBaseLongitudeLatitudeByService(serviceId, serviceCode);

            int time = 1;
            Date createDate = new Date();
            for (BaseLongitudeLatitude dataInfo : currentLnglatList) {
                dataInfo.setId(UUID.randomUUID().toString());
                dataInfo.setServiceId(id.toString());
                dataInfo.setServiceCode(BaseLongitudeLatitudeEnumServiceCode.SYS_AREA.getValue());
                dataInfo.setCreateDefault();
                dataInfo.setCreateDate(DateUtils.addSeconds(createDate, time++));
                baseLongitudeLatitudeService.insertBaseLongitudeLatitude(dataInfo);
            }
        }
        return count;
    }

    /**
     * 批量删除区域
     *
     * @param ids 需要删除的区域主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTbSysAreaByIds(Long[] ids) {
//        tbSysAreaUserRelationMapper.deleteTbSysAreaUserRelationByAreaIds(Arrays.asList(ids));
        return tbSysAreaMapper.deleteTbSysAreaByIds(ids);
    }

    /**
     * 删除区域信息
     *
     * @param id 区域主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteTbSysAreaById(Long id) {
//        tbSysAreaUserRelationMapper.deleteTbSysAreaUserRelationByAreaIds(Arrays.asList(id));
        return tbSysAreaMapper.deleteTbSysAreaById(id);
    }

    /**
     * 统计生产区域数量：企业下
     *
     * @param companyCode 企业编码
     * @return
     */
    @Override
    public Integer selectAreaCount(String companyCode) {
        return tbSysAreaMapper.selectAreaCount(companyCode);
    }
}
