package com.xinelu.manage.service.communityinfo.impl;


import com.xinelu.common.constant.Constants;
import com.xinelu.common.core.domain.AjaxResult;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.SecurityUtils;
import com.xinelu.common.utils.codes.GenerateSystemCodeUtil;
import com.xinelu.manage.domain.communityinfo.CommunityInfo;
import com.xinelu.manage.domain.sysarea.SysArea;
import com.xinelu.manage.mapper.communityinfo.CommunityInfoMapper;
import com.xinelu.manage.mapper.sysarea.SysAreaMapper;
import com.xinelu.manage.service.communityinfo.ICommunityInfoService;
import com.xinelu.manage.vo.community.CommunityInfoVO;
import com.xinelu.manage.vo.sysarea.SysAreaVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 居住社区信息Service业务层处理
 *
 * @author xinyilu
 * @date 2022-09-13
 */
@Service
public class CommunityInfoServiceImpl implements ICommunityInfoService {

    @Resource
    private CommunityInfoMapper communityInfoMapper;

    @Resource
    private SysAreaMapper sysAreaMapper;

    @Resource
    private GenerateSystemCodeUtil generateSystemCodeUtil;

    /**
     * 查询居住社区信息
     *
     * @param id 居住社区信息主键
     * @return 居住社区信息
     */
    @Override
    public CommunityInfoVO selectCommunityInfoById(Long id) {
        return communityInfoMapper.selectCommunityInfoById(id);
    }

    /**
     * 查询居住社区信息列表
     *
     * @param communityInfo 居住社区信息
     * @return 居住社区信息
     */
    @Override
    public List<CommunityInfoVO> selectCommunityInfoList(CommunityInfoVO communityInfo) {
        List<CommunityInfoVO> communityInfoVOS = communityInfoMapper.selectCommunityInfoList(communityInfo);
        List<String> areaCodeList = communityInfoVOS
                .stream().filter(Objects::nonNull)
                .map(CommunityInfoVO::getAreaCode)
                .filter(StringUtils::isNotBlank).distinct().collect(Collectors.toList());

        if (CollectionUtils.isEmpty(areaCodeList)) {
            return communityInfoVOS;
        }
        // 获取本护理站的区域信息
        List<SysAreaVO> nurseStationAreaByList = sysAreaMapper.getNurseStationAreaByList(areaCodeList);
        if (CollectionUtils.isEmpty(nurseStationAreaByList)) {
            return communityInfoVOS;
        }
        //以护理站id进行分组将标签配置信息转为Map集合
        Map<String, List<SysAreaVO>> nurseStationAreaMap = nurseStationAreaByList.stream()
                .filter(Objects::nonNull)
                .filter(item -> Objects.nonNull(item.getStreetCode()))
                .collect(Collectors.groupingBy(SysAreaVO::getStreetCode));
        communityInfoVOS.forEach(item ->
                item.setSysAreaVOList(nurseStationAreaMap.getOrDefault(Objects.isNull(item.getAreaCode()) ? 0L : item.getAreaCode(), Lists.newArrayList())));
        return communityInfoVOS;
    }

    /**
     * 新增居住社区信息
     *
     * @param communityInfo 居住社区信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertCommunityInfoList(List<CommunityInfo> communityInfo) throws Exception {
        if (CollectionUtils.isEmpty(communityInfo)) {
            return AjaxResult.error("请添加数据");
        }
        //插如数据
        for (CommunityInfo community : communityInfo) {
            community.setCreateTime(LocalDateTime.now());
            community.setCreateBy(SecurityUtils.getUsername());
            //编号生成
            community.setCommunityCode(Constants.COMMUNITY_CODE
                    + generateSystemCodeUtil.generateSystemCode(Constants.COMMUNITY_CODE));
        }
        //批量新增
        int infoList = communityInfoMapper.insertCommunityInfoList(communityInfo);
        if (infoList <= 0) {
            throw new ServiceException("新增居住社区信息失败，请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 修改居住社区信息
     *
     * @param communityInfo 居住社区信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult updateCommunityInfo(CommunityInfo communityInfo) throws Exception {
        communityInfo.setUpdateTime(LocalDateTime.now());
        communityInfo.setUpdateBy(SecurityUtils.getUsername());
        int updateCommunityInfo = communityInfoMapper.updateCommunityInfo(communityInfo);
        if (updateCommunityInfo <= 0) {
            throw new ServiceException("修改居住社区信息失败，请联系管理员！");
        }
        return AjaxResult.success();
    }

    /**
     * 批量删除居住社区信息
     *
     * @param ids 需要删除的居住社区信息主键
     * @return 结果
     */
    @Override
    public int deleteCommunityInfoByIds(Long[] ids) {
        return communityInfoMapper.deleteCommunityInfoByIds(ids);
    }

    /**
     * 查询省级区域信息信息
     *
     * @return 省级区域信息集合
     */
    @Override
    public AjaxResult getProvinceAreaInfo() {
        SysArea area = new SysArea();
        area.setAreaLevel(1);
        return AjaxResult.success(sysAreaMapper.selectSysAreaList(area));
    }

    /**
     * 根据父id查询其下属区域信息
     *
     * @param parentId 父级区域id
     * @return 下属区域信息集合
     */
    @Override
    public AjaxResult getSubordinateAreaInfo(Long parentId) {
        SysArea area = new SysArea();
        area.setParentId(parentId);
        return AjaxResult.success(sysAreaMapper.selectSysAreaList(area));
    }
}