package com.cool.store.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.cool.store.dao.*;
import com.cool.store.dto.partner.ZoneCheckDTO;
import com.cool.store.entity.EnterpriseUserDO;
import com.cool.store.entity.HyIntendDevZoneInfoDO;
import com.cool.store.entity.HyIntendDevelopementMappingDO;
import com.cool.store.entity.HyOpenAreaInfoDO;
import com.cool.store.enums.ErrorCodeEnum;
import com.cool.store.exception.ServiceException;
import com.cool.store.request.IntentAreaSettingRequest;
import com.cool.store.service.ZoneService;
import com.cool.store.utils.CoolDateUtils;
import com.cool.store.utils.StringUtil;
import com.cool.store.vo.OpenAreaSingleVO;
import com.cool.store.vo.OrganizationVO;
import com.cool.store.vo.ZoneCheckVO;
import com.cool.store.vo.ZoneVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author suzhuhong
 * @Date 2023/6/14 14:26
 * @Version 1.0
 */
@Service
public class ZoneServiceImpl implements ZoneService {


    @Resource
    HyIntendDevZoneInfoDAO hyIntendDevZoneInfoDAO;

    @Resource
    HyIntendDevMappingDAO hyIntendDevMappingDAO;

    @Resource
    HyOpenAreaInfoDAO openAreaInfoDAO;
    @Resource
    EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    RegionDAO regionDAO;
    @Resource
    HyOpenAreaInfoDAO hyOpenAreaInfoDAO;



    @Override
    public Boolean addZone(String userId, IntentAreaSettingRequest intentAreaSettingRequest) {
        if (CollectionUtils.isEmpty(intentAreaSettingRequest.getOpenAreaIdList())){
            throw  new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        HyIntendDevZoneInfoDO hyIntendDevZoneInfoDO = new HyIntendDevZoneInfoDO();
        hyIntendDevZoneInfoDO.setZoneName(intentAreaSettingRequest.getZoneName());
        if (CollectionUtils.isNotEmpty(intentAreaSettingRequest.getOrgIdList())){
            hyIntendDevZoneInfoDO.setAssociatedRegionId(JSONObject.toJSONString(intentAreaSettingRequest.getOrgIdList()));
        }
        hyIntendDevZoneInfoDO.setCreateUserId(userId);
        hyIntendDevZoneInfoDO.setType(intentAreaSettingRequest.getType());
        hyIntendDevZoneInfoDAO.insertSelective(hyIntendDevZoneInfoDO);
        //添加战区映射的意向区域
        hyIntendDevMappingDAO.deleteByOpenAreaIds(intentAreaSettingRequest.getOpenAreaIdList(),hyIntendDevZoneInfoDO.getType());
        List<Long> openAreaIdList = intentAreaSettingRequest.getOpenAreaIdList();
        List<Long> openAreaIdFilterList = hyOpenAreaInfoDAO.filterLeafNode(openAreaIdList);
        List<HyIntendDevelopementMappingDO> list = new ArrayList<>();
        openAreaIdFilterList.stream().forEach(x->{
            HyIntendDevelopementMappingDO hyIntendDevelopementMappingDO = new HyIntendDevelopementMappingDO();
            hyIntendDevelopementMappingDO.setType(intentAreaSettingRequest.getType());
            hyIntendDevelopementMappingDO.setOpenAreaMappingId(String.valueOf(x));
            hyIntendDevelopementMappingDO.setMappingId(hyIntendDevZoneInfoDO.getId());
            list.add(hyIntendDevelopementMappingDO);
        });
        hyIntendDevMappingDAO.batchInsert(list);
        return Boolean.TRUE;
    }

    @Override
    public Boolean updateZone(String userId, IntentAreaSettingRequest intentAreaSettingRequest) {
        if (CollectionUtils.isEmpty(intentAreaSettingRequest.getOpenAreaIdList())){
            throw  new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        HyIntendDevZoneInfoDO hyIntendDevZoneInfoDO = new HyIntendDevZoneInfoDO();
        hyIntendDevZoneInfoDO.setId(intentAreaSettingRequest.getId());
        hyIntendDevZoneInfoDO.setZoneName(intentAreaSettingRequest.getZoneName());
        hyIntendDevZoneInfoDO.setUpdateUserId(userId);
        hyIntendDevZoneInfoDO.setAssociatedRegionId(CollectionUtils.isNotEmpty(intentAreaSettingRequest.getOrgIdList())?JSONObject.toJSONString(intentAreaSettingRequest.getOrgIdList()):null);
        hyIntendDevZoneInfoDAO.updateByPrimaryKeySelective(hyIntendDevZoneInfoDO);
        //添加战区映射的意向区域
        hyIntendDevMappingDAO.deleteByOpenAreaIds(intentAreaSettingRequest.getOpenAreaIdList(),intentAreaSettingRequest.getType());
        hyIntendDevMappingDAO.deleteByMappingIds(Arrays.asList(intentAreaSettingRequest.getId())
                ,intentAreaSettingRequest.getType());
        List<Long> openAreaIdList = intentAreaSettingRequest.getOpenAreaIdList();
        List<Long> openAreaIdFilterList = hyOpenAreaInfoDAO.filterLeafNode(openAreaIdList);
        List<HyIntendDevelopementMappingDO> list = new ArrayList<>();
        openAreaIdFilterList.stream().forEach(x->{
            HyIntendDevelopementMappingDO hyIntendDevelopementMappingDO = new HyIntendDevelopementMappingDO();
            hyIntendDevelopementMappingDO.setType(intentAreaSettingRequest.getType());
            hyIntendDevelopementMappingDO.setOpenAreaMappingId(String.valueOf(x));
            hyIntendDevelopementMappingDO.setMappingId((hyIntendDevZoneInfoDO.getId()));
            list.add(hyIntendDevelopementMappingDO);
        });
        hyIntendDevMappingDAO.batchInsert(list);
        return Boolean.TRUE;
    }


    @Override
    public PageInfo<ZoneVO> getZoneList(String type, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageInfo hyIntendDevZoneInfoList = new PageInfo(hyIntendDevZoneInfoDAO.getHyIntendDevZoneInfoList(type));
        List<ZoneVO> result = new ArrayList<>();
        List<HyIntendDevZoneInfoDO> list = hyIntendDevZoneInfoList.getList();
        if (CollectionUtils.isEmpty(list)){
            return hyIntendDevZoneInfoList;
        }
        List<String> updateUserIdList = list.stream().map(HyIntendDevZoneInfoDO::getUpdateUserId).collect(Collectors.toList());
        List<EnterpriseUserDO> updateUserList = enterpriseUserDAO.getUserInfoByUserIds(updateUserIdList);
        Map<String, String> updateUserNameMap = updateUserList.stream().collect(Collectors.toMap(EnterpriseUserDO::getUserId, EnterpriseUserDO::getName));

        Set<String> regionSet = new HashSet<>();
        list.stream().forEach(x->{
            if (StringUtil.isNotEmpty(x.getAssociatedRegionId())){
                List<String> regionIds = JSONObject.parseArray(x.getAssociatedRegionId(), String.class);
                regionSet.addAll(regionIds);
            }
        });
        Map<String, String> regionMap = regionDAO.getRegionMap(new ArrayList<>(regionSet));
        list.forEach(x->{
            ZoneVO zoneVO = handleZoneVO(regionMap, x);
            zoneVO.setUpdateUserName(updateUserNameMap.get(x.getUpdateUserId()));
            result.add(zoneVO);
        });
        hyIntendDevZoneInfoList.setList(result);
        return hyIntendDevZoneInfoList;
    }

    @Override
    public ZoneVO zoneDetail(Long zoneId) {
        HyIntendDevZoneInfoDO hyIntendDevZoneInfoDO = hyIntendDevZoneInfoDAO.selectById(zoneId);
        if (hyIntendDevZoneInfoDO==null){
            throw new ServiceException(ErrorCodeEnum.ZONE_NOT_EXIST);
        }
        ZoneVO zoneVO = null;
        EnterpriseUserDO enterpriseUserDO = enterpriseUserDAO.getUserInfoById(hyIntendDevZoneInfoDO.getUpdateUserId());
        if (StringUtil.isNotEmpty(hyIntendDevZoneInfoDO.getAssociatedRegionId())){
            List<String> regionIds = JSONObject.parseArray(hyIntendDevZoneInfoDO.getAssociatedRegionId(), String.class);
            Map<String, String> regionMap = regionDAO.getRegionMap(regionIds);
            zoneVO = handleZoneVO(regionMap, hyIntendDevZoneInfoDO);
        }
        if (enterpriseUserDO!=null){
            zoneVO.setUpdateUserName(enterpriseUserDO.getName());
        }
        List<ZoneCheckDTO> zoneCheckDTOS = hyIntendDevMappingDAO.selectByMappingIdList(Arrays.asList(zoneId));
        List<OpenAreaSingleVO> openAreaVOS = new ArrayList<>();
        zoneCheckDTOS.forEach(x->{
            OpenAreaSingleVO openAreaSingleVO = new OpenAreaSingleVO();
            openAreaSingleVO.setId(x.getOpenAreaMappingId());
            openAreaVOS.add(openAreaSingleVO);
        });
        zoneVO.setOpenAreaVOS(openAreaVOS);
        return zoneVO;
    }


    private ZoneVO handleZoneVO(Map<String, String> regionMap,HyIntendDevZoneInfoDO hyIntendDevZoneInfoDO){
        ZoneVO zoneVO = new ZoneVO();
        zoneVO.setZoneName(hyIntendDevZoneInfoDO.getZoneName());
        zoneVO.setId(hyIntendDevZoneInfoDO.getId());
        zoneVO.setUpdateTime(DateUtil.format(hyIntendDevZoneInfoDO.getUpdateTime(), CoolDateUtils.DATE_FORMAT_SEC_2));
        List<OrganizationVO> organizationVOS = new ArrayList<>();
        if (StringUtil.isNotEmpty(hyIntendDevZoneInfoDO.getAssociatedRegionId())){
            List<String> regionIds = JSONObject.parseArray(hyIntendDevZoneInfoDO.getAssociatedRegionId(), String.class);
            regionIds.forEach(regionId->{
                OrganizationVO organizationVO = new OrganizationVO();
                organizationVO.setId(regionId);
                organizationVO.setName(regionMap.get(regionId));
                organizationVOS.add(organizationVO);
            });
        }
        zoneVO.setOrgVos(organizationVOS);
        zoneVO.setUpdateUserId(hyIntendDevZoneInfoDO.getUpdateUserId());
        return zoneVO;
    }

    @Override
    public Boolean deletedZone(Long id) {
        HyIntendDevZoneInfoDO hyIntendDevZoneInfoDO = hyIntendDevZoneInfoDAO.selectById(id);
        if (hyIntendDevZoneInfoDO==null){
           throw new ServiceException(ErrorCodeEnum.ZONE_NOT_EXIST);
        }
        hyIntendDevZoneInfoDO.setDeleted(1);
        hyIntendDevZoneInfoDAO.updateByPrimaryKeySelective(hyIntendDevZoneInfoDO);
        hyIntendDevMappingDAO.deleteByMappingIds(Arrays.asList(id),hyIntendDevZoneInfoDO.getType());
        return Boolean.TRUE;
    }

    @Override
    public List<ZoneCheckVO> checkZone(IntentAreaSettingRequest intentAreaSettingRequest) {
        if (CollectionUtils.isEmpty(intentAreaSettingRequest.getOpenAreaIdList())){
            throw  new ServiceException(ErrorCodeEnum.PARAMS_REQUIRED);
        }
        //查询已经绑定战区的 意向区域
        List<ZoneCheckDTO> list = hyIntendDevMappingDAO.selectByOpenAreaMappingIdList(intentAreaSettingRequest.getOpenAreaIdList(),intentAreaSettingRequest.getType(),intentAreaSettingRequest.getId());
        List<Long> openAreaIdList = list.stream().map(ZoneCheckDTO::getOpenAreaMappingId).collect(Collectors.toList());
        List<Long> openAreaIdFilterList = hyOpenAreaInfoDAO.filterLeafNode(openAreaIdList);
        List<HyOpenAreaInfoDO> hyOpenAreaInfoDOList = openAreaInfoDAO.selectByIds(openAreaIdFilterList);
        Map<Long, String> areaNameMap = hyOpenAreaInfoDOList.stream().collect(Collectors.toMap(HyOpenAreaInfoDO::getId, HyOpenAreaInfoDO::getAreaName));
        List<ZoneCheckVO> result = new ArrayList<>();
        list.forEach(x->{
            ZoneCheckVO zoneCheckVO = new ZoneCheckVO();
            zoneCheckVO.setZoneName(x.getZoneName());
            String areaName = areaNameMap.get(x.getOpenAreaMappingId());
            zoneCheckVO.setAreaName(areaName);
            result.add(zoneCheckVO);
        });
        return result;
    }

    @Override
    public List<String> queryAllBingZoneRegionList(String type) {
        PageInfo<HyIntendDevZoneInfoDO> intend = new PageInfo<>(hyIntendDevZoneInfoDAO.getHyIntendDevZoneInfoList(type));
        List<HyIntendDevZoneInfoDO> list = intend.getList();
        List<String> resultList = list.stream().filter(x->StringUtil.isNotEmpty(x.getAssociatedRegionId()))
                .flatMap(HyIntendDevZoneInfoDO -> JSONObject.parseArray(HyIntendDevZoneInfoDO.getAssociatedRegionId(), String.class).stream())
                .collect(Collectors.toList());
        return resultList;
    }


}
