const fs = require("fs");
const path = require("path");
const superagent = require("superagent");

function fetchGeoJson(file, sub = "_full") {
  superagent
    .get(`https://geo.datav.aliyun.com/areas_v3/bound/${file}${sub}.json`)
    .end((err, res) => {
      if (err) {
        console.log(
          `抓取失败 - ${err}`,
          `https://geo.datav.aliyun.com/areas_v3/bound/${file}${sub}.json`
        );
        fetchSimple(file);
      } else {
        const data = JSON.parse(res.text);

        saveFile(`/${file}${sub}.json`, res.text);
        fetchSimple(file);
        data.features.forEach((child) => {
          if (child.properties.level != "district") {
            fetchGeoJson(child.properties.adcode, "_full");
          }
        });
      }
    });
}

function fetchSimple(file) {
  superagent
    .get(`https://geo.datav.aliyun.com/areas_v3/bound/${file}.json`)
    .end((e, r) => {
      if (e) {
        console.log(
          `抓取simple失败 - ${e}`,
          `https://geo.datav.aliyun.com/areas_v3/bound/${file}.json`
        );
      } else {
        saveFile(`/${file}.json`, r.text);
      }
    });
}

function saveFile(ap, text) {
  fs.writeFile(path.resolve(`../${ap}`), text, (err) => {
    if (err) {
      throw err;
    }
  });
}

fetchGeoJson("100000");
