import axios from "axios";

export function supervisorChangeList(keyword) {
  return new Promise(function (r, j) {
    try {
      new AMap.Autocomplete({
        city: "全国",
      }).search(keyword, function (status, result) {
        if (status === "complete") {
          r(result);
        } else {
          console.error("根据地址查询位置失败");
          j(result);
        }
      });
    } catch (error) {
      j(error);
    }
  });
}

/**
 * 根据地址查坐标
 * @param {*} address 例如：广东省广州市天河区邮通小区
 * @returns Object
 */
export function getLocation(address) {
  return new Promise(function (r, j) {
    try {
      new AMap.Geocoder().getLocation(address, function (status, result) {
        if (status === "complete" && result.geocodes?.length) {
          r(result.geocodes);
        } else {
          console.error("根据地址查询位置失败");
          j(result);
        }
      });
    } catch (error) {
      j(error);
    }
  });
}

/**
 * 根据坐标查地址
 * @param {*} location 例如：[113.36242, 23.1368425]
 * @returns Object
 */
export function getAddress(location) {
  return new Promise(function (r, j) {
    try {
      new AMap.Geocoder().getAddress(location, function (status, result) {
        if (status === "complete" && result.regeocode) {
          r(result.regeocode);
        } else {
          console.error("根据地址查询位置失败");
          j(result);
        }
      });
    } catch (error) {
      j(error);
    }
  });
}

export function axiosMapZb(params) {
  return axios({
    url: `https://restapi.amap.com/v3/place/around`,
    method: "get",
    params: {
      key: "428a7111e02ea8367a3b34804eaa025b",
      ...params,
    },
  });
}

// 获取ip定位地址
export function getIPAdd() {
  return new Promise(function (r, j) {
    try {
      getIPs((ip) => {
        axios
          .get(
            "https://restapi.amap.com/v3/ip?output=json&key=428a7111e02ea8367a3b34804eaa025b&ip=" +
              ip
          )
          .then(r)
          .catch(j);
      });
    } catch (error) {
      j(error);
    }
  });
}

// export function getIPAdd() {
//   return new Promise(function (r, j) {
//     try {
//       axios
//         .get('https://qifu-api.baidubce.com/ip/local/geo/v1/district')
//         .then((res) => {
//           r(res);
//         })
//         .catch(j);
//     } catch (error) {
//       j(error);
//     }
//   });
// }

// 获取当前ip
function getIPs(callback) {
  var ip_dups = {};
  var RTCPeerConnection =
    window.RTCPeerConnection ||
    window.mozRTCPeerConnection ||
    window.webkitRTCPeerConnection;
  var useWebKit = !!window.webkitRTCPeerConnection;
  var mediaConstraints = {
    optional: [{ RtpDataChannels: true }],
  };
  var servers = {
    iceServers: [
      { urls: "stun:stun.services.mozilla.com" },
      { urls: "stun:stun.l.google.com:19302" },
    ],
  };
  var pc = new RTCPeerConnection(servers, mediaConstraints);
  function handleCandidate(candidate) {
    var ip_regex =
      /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/;
    var hasIp = ip_regex.exec(candidate);
    if (hasIp) {
      var ip_addr = ip_regex.exec(candidate)[1];
      if (ip_dups[ip_addr] === undefined) callback(ip_addr);
      ip_dups[ip_addr] = true;
    }
  }
  pc.onicecandidate = function (ice) {
    if (ice.candidate) {
      handleCandidate(ice.candidate.candidate);
    }
  };
  pc.createDataChannel("");
  pc.createOffer(
    function (result) {
      pc.setLocalDescription(
        result,
        function () {},
        function () {}
      );
    },
    function () {}
  );
  setTimeout(function () {
    var lines = pc.localDescription.sdp.split("\n");
    lines.forEach(function (line) {
      if (line.indexOf("a=candidate:") === 0) handleCandidate(line);
    });
  }, 500);
}
