package com.blueland.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blueland.bo.AreaEntity;
import com.blueland.bo.AreaExpEntity;
import com.blueland.dao.AreaDao;

import com.blueland.model.TArea;
import com.blueland.service.IAreaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Slf4j
@Service
public class AreaServiceImpl extends ServiceImpl<AreaDao, TArea> implements IAreaService {
    @Autowired
    //Area对应的DAO类,主要用于数据库的增删改查等操作
    private AreaDao areaDao;


    /*根据条件查询*/
    @Override
    public Page<AreaEntity> getList(Map<String,Object> area, int curPage, int pageSize){
        Page<AreaEntity> page = new Page<>(curPage,pageSize);
        Page<AreaEntity> list=areaDao.findPage(page, area);
        return list;
    }

    /**
     * 导入数据
     * @param data
     */
    @Transactional
    @Override
    public void importAreaData(List<AreaExpEntity> data){
        try {
            List<AreaEntity> areaList = areaDao.selectList();
            // 核查两个数组对象里面是否有重复数据
            List<AreaExpEntity> tempList =  areaList.stream()
                    .map(t -> data.stream().filter(s -> Objects.nonNull(t.getTid()) && Objects.nonNull(s.getTid()) && Objects.equals(t.getTid(), s.getTid())).findAny().orElse(null))
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList());
            if(tempList.size()>0){
                System.err.println(JSON.toJSONString(tempList));
                throw new RuntimeException("数据库已存在行政编码，请核查数据再导入！");
            }
            long count = data.stream().distinct().count();
            if(data.size() != count){
                throw new RuntimeException("导入的数据中有重复行政编码数据，请核查数据再导入！！");
            }
            List<AreaExpEntity> firstLeve = data.stream().filter(o -> o.getTid().substring(2,6).equals("0000")).collect(Collectors.toList());
            List<AreaExpEntity> secondLeve = data.stream().filter(o -> o.getTid().substring(4, 6).equals("00") && o.getTid().length() == 6 && !o.getTid().substring(2, 6).equals("0000")).collect(Collectors.toList());
            List<AreaExpEntity> thirdLeve = data.stream().filter(o -> !o.getTid().substring(4, 6).equals("00") || o.getTid().length() > 6 ).collect(Collectors.toList());
            List<AreaEntity> list = new ArrayList<AreaEntity>();
            for (AreaExpEntity areaExcelEntity : firstLeve) { //处理省数据
                AreaEntity area = new AreaEntity();
                area.setPid("0");
                area.setCreateTime(new Date());
                area.setId(areaExcelEntity.getTid());
                area.setTid(areaExcelEntity.getTid());
                area.setAname(areaExcelEntity.getAname());
                list.add(area);
            }
            for (AreaExpEntity areaExcelEntity : secondLeve) { //处理市
                AreaEntity area = new AreaEntity();
                area.setPid(areaExcelEntity.getTid().substring(0,2)+"0000");
                area.setCreateTime(new Date());
                area.setId(areaExcelEntity.getTid());
                area.setTid(areaExcelEntity.getTid());
                area.setAname(areaExcelEntity.getAname());
                list.add(area);
            }
            for (AreaExpEntity areaExcelEntity : thirdLeve) { //处理区
                AreaEntity area = new AreaEntity();
                area.setPid(areaExcelEntity.getTid().substring(0,2)+"0000");
                area.setCreateTime(new Date());
                area.setId(areaExcelEntity.getTid());
                area.setTid(areaExcelEntity.getTid());
                area.setAname(areaExcelEntity.getAname());
                list.add(area);
            }
            areaDao.saveBatch(list);
        } catch (Exception e) {
            e.printStackTrace();
//            log.error("操作失败！异常 importAreaData: {}", e.getMessage());
            throw new RuntimeException("数据异常，请核查数据");
        }
    }

    @Override
    public TArea getbyid(String id) {
        TArea areaEntity=areaDao.selectById(id);
        return areaEntity;
    }

    @Override
    public int updateArea(AreaEntity model) {
     int  result=0;
     if(model.getId() != null && !"".equals(model.getId())){
         result=areaDao.updateArea(model);
     }
     return result;
    }

    @Override
    public List<AreaEntity> queryArea() {
        List<AreaEntity> list=areaDao.queryArea();
        return list;
    }

    @Override
    public int insetArea(AreaEntity areaEntity) {
     int res= areaDao.insetArea(areaEntity);
       return res;
    }

    @Override
    public void deleteArea(String id) {
        areaDao.deleteById(id);
    }

    @Override
    public List<Map<String, Object>> areaTree() {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<AreaEntity> dataList=areaDao.queryall();
        List<AreaEntity> firstLeve = dataList.stream().filter(o -> o.getTid().substring(2,6).equals("0000")).collect(Collectors.toList());
        List<AreaEntity> secondLeve = dataList.stream().filter(o -> o.getTid().substring(4, 6).equals("00") && o.getTid().length() == 6 && !o.getTid().substring(2, 6).equals("0000")).collect(Collectors.toList());
        List<AreaEntity> thirdLeve = dataList.stream().filter(o -> !o.getTid().substring(4, 6).equals("00") || o.getTid().length() > 6).collect(Collectors.toList());
        list = appendTree(firstLeve,secondLeve,thirdLeve);
        return list;

    }
    private List<Map<String, Object>> appendTree(List<AreaEntity> firstLeve, List<AreaEntity> secondLeve,
                                                 List<AreaEntity> thirdLeve) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (AreaEntity first : firstLeve) { // 一级
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("value", first.getTid());
            map.put("label", first.getAname());
            map.put("children", this.appendChildTree(first,secondLeve,thirdLeve));
            list.add(map);
        }
        return list;
    }
    private List<Map<String, Object>> appendChildTree(AreaEntity first, List<AreaEntity> secondLeve, List<AreaEntity> thirdLeve) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        if(first.getTid().equals("810000") || first.getTid().equals("820000")){//香港 澳门
            List<AreaEntity> thirdLeveList = thirdLeve.stream().filter(o -> o.getPid().equals(first.getId())).collect(Collectors.toList());
            for (AreaEntity areaEntity : thirdLeveList) { //二级
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("value", areaEntity.getTid());
                map.put("label", areaEntity.getAname());
                list.add(map);
            }
        }else{
            List<AreaEntity> secondList = secondLeve.stream().filter(o -> o.getPid().equals(first.getId())).collect(Collectors.toList());
            for (AreaEntity areaEntity : secondList) { //二级
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("value", areaEntity.getTid());
                map.put("label", areaEntity.getAname());
                map.put("children", this.appendThirdChildTree(areaEntity,thirdLeve));
                list.add(map);
            }
        }

        return list;
    }
    private Object appendThirdChildTree(AreaEntity areaEntity, List<AreaEntity> thirdLeve) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        List<AreaEntity> thirdList = new ArrayList<AreaEntity>();
        thirdList = thirdLeve.stream().filter(o -> areaEntity.getTid().equals(o.getTid().substring(0, 4)+"00")).collect(Collectors.toList());
        if(areaEntity.getTid().substring(0, 4).equals("6543")
                || areaEntity.getTid().substring(0, 4).equals("4604")){ //处理特殊  阿勒泰地区：654300  儋州市:460400
            thirdList = thirdLeve.stream().filter(o -> areaEntity.getTid().equals(o.getTid().substring(0, 4)+"00") || o.getTid().substring(0, 4).equals("6590")).collect(Collectors.toList());
        }
        for (AreaEntity third : thirdList) {// 三级
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("value", third.getTid());
            map.put("label", third.getAname());
            list.add(map);
        }
        return list;
    }
}
