/**
 * 添加行政区域
 * @param {*} map
 * @param {*} adcode 如 北京市 110000
 * @see adcode https://webapi.amap.com/ui/1.0/ui/geo/DistrictExplorer/assets/d_v1/area_tree.txt
 */
export const insertDistrict = (map, adcode) => {
  /* 绘制小地图的各个省份的分界线 */
  window.AMapUI.loadUI(['geo/DistrictExplorer'], DistrictExplorer => {
    //创建一个实例
    const districtExplorer = new DistrictExplorer({
      map
    });

    districtExplorer._loadJson('/src/_mock/map/an_100000.json', (error, distData) => {
      if (error) {
        console.error(error);
        return;
      }
      districtExplorer._buildAreaNode(adcode, distData);
      const areaNode = districtExplorer._areaNodeCache[adcode];
      // districtExplorer.loadAreaNode(adcode, (error, areaNode) => {
        // 清除已有的绘制内容
      districtExplorer.clearFeaturePolygons();

      districtExplorer.renderSubFeatures(areaNode, (feature, i) => {
        if (feature.properties.name === '陕西省'){
          return {
            cursor: 'default',
            bubble: true,
            strokeColor: '#1577E8', //线颜色
            fillColor: '#fcfcfc',
            strokeWeight: 6, //线宽
            fillOpacity: 0.4, //填充透明度
          };
        }
      });

      //绘制父区域
      // districtExplorer.renderParentFeature(areaNode, {
      //   cursor: 'default',
      //   bubble: true,
      //   strokeColor: '#152AE8', //线颜色
      //   fillColor: '#B4B8F7',
      //   strokeWeight: 2, //线宽
      //   fillOpacity: 0.4, //填充透明度
      // });
      function getAllRings(feature) {
        var coords = feature.geometry.coordinates,
          rings = [];
        for (var i = 0, len = coords.length; i < len; i++) {
          rings.push(coords[i][0]);
        }
        return rings;
      }

      function getLongestRing(feature) {
        var rings = getAllRings(feature);
        rings.sort((a, b) => {
          return b.length - a.length;
        });
        return rings[0];
      }

      var countryCode = 100000, //全国
        provCodes = [
          610000 //陕西
        ];

      districtExplorer.loadMultiAreaNodes(
          //只需加载全国和市，全国的节点包含省级
          [countryCode],
          (error, areaNodes) => {

            var countryNode = areaNodes[0];

            var path = [];

              //首先放置背景区域，这里是大陆的边界
            path.push(getLongestRing(countryNode.getParentFeature()));

            for (var i = 0, len = provCodes.length; i < len; i++) {
                  //逐个放置需要镂空的省级区域
              path.push.apply(path, getAllRings(countryNode.getSubFeatureByAdcode(provCodes[i])));
            }

            var polygon = new AMap.Polygon({
              bubble: true,
              lineJoin: 'round',
              strokeColor: 'red', //线颜色
              strokeOpacity: 0, //线透明度
              strokeWeight: 1, //线宽
              fillColor: '#c7c7c7', //填充色
              fillOpacity: 0.7, //填充透明度
              map,
              path
            });
          });
    });
  });
};

export default {
};
