package org.dromara.zhishu.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.zhishu.domain.TDistrict;
import org.dromara.zhishu.domain.bo.TDistrictBo;
import org.dromara.zhishu.domain.vo.DistrictsVo;
import org.dromara.zhishu.domain.vo.TDistrictVo;
import org.dromara.zhishu.enums.MunicipalityEnum;
import org.dromara.zhishu.mapper.TDistrictMapper;
import org.dromara.zhishu.service.ITDistrictService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

@RequiredArgsConstructor
@Service
public class TDistrictServiceImpl implements ITDistrictService {

    private final TDistrictMapper baseMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 主键
     * @return 【请填写功能名称】
     */
    @Override
    public TDistrictVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询【请填写功能名称】列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 【请填写功能名称】分页列表
     */
    @Override
    public TableDataInfo<TDistrictVo> queryPageList(TDistrictBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TDistrict> lqw = buildQueryWrapper(bo);
        Page<TDistrictVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Override
    public List<TDistrictVo> queryList(TDistrictBo bo) {
        LambdaQueryWrapper<TDistrict> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    /**
     * 查询符合条件的【请填写功能名称】列表
     *
     * @param bo 查询条件
     * @return 【请填写功能名称】列表
     */


    private LambdaQueryWrapper<TDistrict> buildQueryWrapper(TDistrictBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TDistrict> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(TDistrict::getId);
        lqw.eq(bo.getPid() != null, TDistrict::getPid, bo.getPid());
        lqw.eq(StringUtils.isNotBlank(bo.getCode()), TDistrict::getCode, bo.getCode());
        lqw.like(StringUtils.isNotBlank(bo.getName()), TDistrict::getName, bo.getName());
        lqw.eq(bo.getStatus() != null, TDistrict::getStatus, bo.getStatus());
        lqw.eq(bo.getLevel() != null, TDistrict::getLevel, bo.getLevel());
        return lqw;
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(TDistrictBo bo) {
        TDistrict add = MapstructUtils.convert(bo, TDistrict.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param bo 【请填写功能名称】
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(TDistrictBo bo) {
        TDistrict update = MapstructUtils.convert(bo, TDistrict.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TDistrict entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除【请填写功能名称】信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<TDistrictVo> selectList(){
        return baseMapper.selectDistrictList();
    }

    @Override
    public List<TDistrictVo> selectDistrictByPid(String pid){
        return baseMapper.selectDistrictByPid(pid);
    }

    @Override
    public List<TDistrictVo> selectCityList(TDistrictVo vo) {
        return baseMapper.selectCityList(vo);
    }

    @Override
    public List<TDistrictVo> selectAreaList(TDistrictVo vo) {
        return baseMapper.selectAreaList(vo);
    }

    /**
     * 查询地址数据
     *
     * @param vo
     * @return
     */
    @Override
    public List<DistrictsVo> selectDistricts(TDistrictVo vo) {
        // 查询所有省级区划
        List<TDistrictVo> districtList = baseMapper.selectDistrictList();
        // 查询所有区级区划
        List<TDistrictVo> cityList = baseMapper.selectCityList(vo);
        // 直辖市ID集合
        List<Long> municipalityIdList = new ArrayList<>();
        municipalityIdList.add(MunicipalityEnum.BEIJING.getId());
        municipalityIdList.add(MunicipalityEnum.SHANGHAI.getId());
        municipalityIdList.add(MunicipalityEnum.TIANJIN.getId());
        municipalityIdList.add(MunicipalityEnum.CHONGQING.getId());
        // 单独查出直辖市下的区级区划
        List<TDistrictVo> municipalityAreaList = baseMapper.selectMunicipalityAreaList(municipalityIdList);

        // 省级区划响应集合
        List<DistrictsVo> provinceVoList = new ArrayList<>();

        // 循环将省级区划信息插曲到省级区划响应集合
        for (TDistrictVo tDistrictVo : districtList) {
            DistrictsVo provinceDistrictsVo = new DistrictsVo();
            provinceDistrictsVo.setLabel(tDistrictVo.getName());
            provinceDistrictsVo.setValue(tDistrictVo.getName());
            provinceDistrictsVo.setId(tDistrictVo.getCode());
            //
            List<DistrictsVo> childrenList = new ArrayList<>();
            // 循环将市级区划信息插曲到市级区划响应集合
            cityList.forEach(city -> {
                if (city.getPid().equals(tDistrictVo.getId())) {
                    DistrictsVo cityDistrictsVo = new DistrictsVo();
                    cityDistrictsVo.setLabel(city.getName());
                    cityDistrictsVo.setValue(city.getName());
                    cityDistrictsVo.setId(city.getCode());
                    // 将查出的直辖市下区级区划信息循环插入到市级区划信息中
                    if (municipalityIdList.contains(city.getId())) {
                        List<DistrictsVo> municipalityAreaVoList = new ArrayList<>();
                        for (TDistrictVo municipalityArea : municipalityAreaList) {
                            if (municipalityArea.getPid().equals(city.getId())) {
                                DistrictsVo municipalityAreaVo = new DistrictsVo();
                                municipalityAreaVo.setLabel(municipalityArea.getName());
                                municipalityAreaVo.setValue(municipalityArea.getName());
                                municipalityAreaVo.setId(municipalityArea.getCode());
                                municipalityAreaVoList.add(municipalityAreaVo);
                            }
                        }
                        if (!municipalityAreaVoList.isEmpty()) {
                            cityDistrictsVo.setChildren(municipalityAreaVoList);
                        }
                    }
                    childrenList.add(cityDistrictsVo);
                }
            });
            if (!childrenList.isEmpty()) {
                provinceDistrictsVo.setChildren(childrenList);
            }
            provinceVoList.add(provinceDistrictsVo);
        }
        return provinceVoList;
    }

    @Override
    public List<TDistrictVo> queryListByName(List<String> districtNames) {
        return new LambdaQueryChainWrapper<>(baseMapper)
                .eq(TDistrict::getStatus, 0)
                .in(TDistrict::getName, districtNames)
                .list().stream().map(o -> {
                    TDistrictVo tDistrictVo = new TDistrictVo();
                    BeanUtils.copyProperties(o, tDistrictVo);
                    return tDistrictVo;
                }).toList();
    }


}