<template>
  <div
    class="weather-wrapper"
    :style="{ color: textColor, fontSize: textSize + 'px' }"
  >
    <p>{{ weatherType }}</p>
    <p>{{ weatherTemp }}</p>
  </div>
</template>

<script>
import { reactive, toRefs } from "vue";
export default {
  name: "Weather",
  props: {
    city: {
      type: String,
      default: "北京",
    },
    textColor: {
      type: String,
      default: "#000",
    },
    textSize: {
      type: Number,
      default: 30,
    },
  },
  setup(props, ctx) {
    const _ajax = (options) => {
      return new Promise((resolve, reject) => {
        let { url, methods, data } = options;
        let xhr = null;
        if (window.XMLHttpRequest) {
          xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
          xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (methods.toUpperCase() === "GET") {
          console.log(url + "?" + data);
          xhr.open(methods, url + "?" + data, true);
          xhr.send();
        } else if (methods.toUpperCase() === "POST") {
          xhr.open(methods, url, async);
          xhr.send(data);
          xhr.setRquestHeader(
            "Content-Type",
            "application/x-www-form-urlencoded"
          );
        }
        xhr.onreadystatechange = function () {
          //0未初始化 1已调用open 2已send 3接收中
          if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 300)) {
            resolve(JSON.parse(xhr.responseText));
          }
        };
        xhr.onerrer = function (e) {
          reject(e);
        };
      });
    };
    const state = reactive({
      weatherType: "",
      weatherTemp: "",
    });

    const weatherStatus = _ajax({
      url: "http://wthrcdn.etouch.cn/weather_mini",
      methods: "GET",
      data: `city=${props.city}`,
    });
    weatherStatus.then((data) => {
      state.weatherType = data.data.forecast[0].type;
      state.weatherTemp =
        data.data.forecast[0].low.split(" ")[1] +
        " ~ " +
        data.data.forecast[0].high.split(" ")[1];
    });

    return {
      ...toRefs(state),
    };
  },
};
</script>

<style scoped>
</style>