package com.njzscloud.supervisory.sys.district.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njzscloud.common.core.tree.Tree;
import com.njzscloud.common.mp.support.PageParam;
import com.njzscloud.common.mp.support.PageResult;
import com.njzscloud.supervisory.config.AppProperties;
import com.njzscloud.supervisory.sys.district.mapper.DistrictMapper;
import com.njzscloud.supervisory.sys.district.pojo.entity.DistrictEntity;
import com.njzscloud.supervisory.sys.district.pojo.result.DistrictTreeResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 省市区表
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class DistrictService extends ServiceImpl<DistrictMapper, DistrictEntity> implements IService<DistrictEntity> {

    private final AppProperties appProperties;

    /**
     * 新增
     */
    public void add(DistrictEntity districtEntity) {
        this.save(districtEntity);
    }

    /**
     * 修改
     */
    public void modify(DistrictEntity districtEntity) {
        this.updateById(districtEntity);
    }

    /**
     * 删除
     */
    @Transactional(rollbackFor = Exception.class)
    public void del(List<Long> ids) {
        this.removeBatchByIds(ids);
    }

    /**
     * 详情
     */
    public DistrictEntity detail(Long id) {
        return this.getById(id);
    }

    /**
     * 分页查询
     */
    public PageResult<DistrictEntity> paging(PageParam pageParam, DistrictEntity districtEntity) {
        return PageResult.of(this.page(pageParam.toPage(), Wrappers.<DistrictEntity>query(districtEntity)));
    }

    /**
     * 树查询
     */
    public List<DistrictTreeResult> tree() {
        List<DistrictTreeResult> list = this.list()
                .stream()
                .map(it -> BeanUtil.copyProperties(it, DistrictTreeResult.class))
                .collect(Collectors.toList());
        return Tree.listToTree(list, DistrictTreeResult::getId, DistrictTreeResult::getPid, DistrictTreeResult::setChildren, "0");
    }

    public List<DistrictEntity> listDistrict(String pid, String name) {
        return this.list(Wrappers.<DistrictEntity>lambdaQuery()
                .eq(DistrictEntity::getPid, pid)
                .like(StrUtil.isNotBlank(name), DistrictEntity::getDistrictName, name)
        );
    }

    public List<DistrictEntity> areaList() {
        AppProperties.DefaultPlace defaultPlace = appProperties.getDefaultPlace();
        return this.list(Wrappers.<DistrictEntity>lambdaQuery().eq(DistrictEntity::getPid, defaultPlace.getCity()));
    }
}
