/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-03-10 16:50:09
 * @LastEditors: HJ
 * @LastEditTime: 2021-06-07 18:04:07
 */
const { Tips, Loading, hLoading } = getApp();
const { _AUTH_PHONE_KEY } = require("../../utils/global-key");
const baseUrl = require("../../api/index.js").config;
const order = require("../../api/order.js");
const { clone } = require("../../utils/deep-copy");
const componentOptions = {
  // 组件选项
  options: {
    multipleSlots: true,
  },
  // props
  properties: {
    value: {
      type: Object,
      value: {},
      observer(v) {
        if (v.province) {
          this.initInfo(v);
        }
      },
    },
  },
  // 组件数据
  data: {
    isPageHidden: false, // 页面是否处于隐藏状态
    // 自定义样式
    customStyle: "padding: 10px 0;",
    // 地址信息
    addressText: "",
    // 楼宇名
    buildingName: "",
    // 表单信息
    form: { name: "", phone: "", sex: "", addressDetail: "" },
    // 是否自动聚焦
    autoFocus: false,
  },
  // 组件方法
  methods: {
    init() {},
    // 获取用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        wx.getUserInfo({
          success: function (res) {
            const userInfo = res.userInfo;
            resolve(userInfo);
          },
          fail(err) {
            console.log("get user info error", err);
            reject();
          },
        });
      });
    },
    // 初始化信息
    async initInfo(v) {
      const {
        sendId = null,
        province,
        city,
        area,
        addressDetail,
        buildingName,
        longitude,
        latitude,
        phone: rawPhone,
        houseNumber,
      } = v;
      // 手机号
      const phone = rawPhone || wx.getStorageSync(_AUTH_PHONE_KEY);
      // 用户信息
      const { nickName, gender } = await this.getUserInfo();
      const provinceText = province === city ? province : `${province}${city}`;
      const detailText =
        buildingName === addressDetail
          ? addressDetail
          : `${addressDetail}${buildingName}`;
      const form = Object.assign({}, this.data.form, {
        id: sendId,
        phone,
        city,
        longitude,
        latitude,
        poiName: buildingName,
        address: addressDetail,
        addressDetail: houseNumber || "",
        sex: gender,
        name: nickName,
        // 暂时用于分众活动写死为 true
        focusAddressFlag: true,
      });

      this.setData({
        addressText: `${provinceText}${area}${detailText}`,
        buildingName,
        form,
        tempForm: clone(form),
        autoFocus: !houseNumber,
      });
    },
    // 点击地址
    clickAddress() {
      Tips("当前的订单是活动订单，不允许修改收货地址");
    },
    // 输入内容
    onChange({ detail, currentTarget: { dataset } }) {
      const { type } = dataset;
      this.setData({
        [`form.${type}`]: detail,
      });
    },
    // 校验输入
    verifyForm() {
      return new Promise(async (resolve, rej) => {
        try {
          Loading();

          const { form = {} } = this.data;
          const { phone, name, addressDetail } = form;
          const { id } = form;

          // 校验是否修改
          if (id && !this.verifyChange()) {
            hLoading();
            resolve(form);
            return;
          }

          if (!name) {
            hLoading();
            Tips("请输入联系人");
            rej();
            return;
          }

          if (!phone) {
            hLoading();
            Tips("请输入手机号");
            rej();
            return;
          }

          if (!/^1[3456789]\d{9}$/.test(phone)) {
            hLoading();
            Tips("请输入正确的手机号");
            rej();
            return;
          }

          if (!addressDetail) {
            hLoading();
            Tips("请输入门牌号");
            rej(Error("请输入门牌号"));
            return;
          }

          await (id ? this.updateAddress() : this.createAddress());
          const address = await this.getAddress();
          resolve(address);
        } catch (e) {
          console.log("axios error", e);
        }
      });
    },
    // 校验是否发生改变，没有发生改变的话直接原路返回
    verifyChange() {
      const { form, tempForm } = this.data;

      const keys = ["name", "phone", "addressDetail"];

      let flag = true;
      for (let i = 0; i < keys.length; i++) {
        flag = form[keys[i]] === tempForm[keys[i]];
        if (!flag) break;
      }

      return !flag;
    },
    // 请求创建地址
    createAddress() {
      return new Promise((resolve, reject) => {
        const { form } = this.data;
        const memberId = wx.getStorageSync("memberId");
        order.getAddress(
          baseUrl.waimaiUrl + `/client/${memberId}/address`,
          {},
          form,
          "加载中",
          function (res) {
            hLoading();
            resolve(res.results);
          },
          function (err) {
            console.log("axios error", err);
            reject(err);
            Tips("创建地址错误，请重新进入小程序后重试");
          }
        );
      });
    },
    // 编辑地址
    updateAddress() {
      return new Promise((resolve, reject) => {
        const { form } = this.data;
        const { id: addressId } = form;
        const memberId = wx.getStorageSync("memberId");
        order.putRditAddress(
          baseUrl.waimaiUrl + `/client/${memberId}/address/${addressId}`,
          {},
          form,
          "加载中",
          function (res) {
            hLoading();
            resolve(res.results);
          },
          function (err) {
            console.log("axios error", err);
            reject(err);
            Tips("创建地址错误，请重新进入小程序后重试");
          }
        );
      });
    },
    // 由于后端没有返回地址信息，所以通过请求获取新创建的地址的id
    getAddress() {
      return new Promise((resolve, reject) => {
        const memberId = wx.getStorageSync("memberId");
        order.getRequire(
          baseUrl.waimaiUrl + "/client/" + memberId + "/address",
          {},
          {},
          "加载中",
          (res) => {
            const { results } = res;
            if (Array.isArray(results)) {
              const { longitude, latitude } = this.data.value;
              const { addressDetail, poiName } = this.data.form;
              const temp = results.filter((i) => {
                const {
                  longitude: rawLon,
                  latitude: rawLat,
                  poiName: rawPoi,
                  addressDetail: rawAdd,
                  focusAddressFlag,
                } = i;

                console.log(
                  "debug",
                  focusAddressFlag,
                  (+rawLon).toFixed(3) === (+longitude).toFixed(3),
                  (+rawLat).toFixed(3) === (+latitude).toFixed(3),
                  poiName === rawPoi,
                  addressDetail === rawAdd
                );

                if (
                  focusAddressFlag &&
                  (+rawLon).toFixed(3) === (+longitude).toFixed(3) &&
                  (+rawLat).toFixed(3) === (+latitude).toFixed(3) &&
                  poiName === rawPoi &&
                  addressDetail === rawAdd
                ) {
                  return i;
                }
              });
              console.log("debug", temp);
              if (temp.length > 0) {
                resolve(temp[0]);
              } else {
                reject();
              }
            } else {
              reject();
            }
          },
          function (err) {
            console.log("axios error", err);
            reject(err);
            Tips("创建地址错误，请重新进入小程序后重试");
          }
        );
      });
    },
  },
  // 组件生命周期
  lifetimes: {
    created() {},
    attached() {
      this.init();
    },
    ready() {},
    moved() {},
    detached() {},
  },
  definitionFilter() {},
  // 页面生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      const { isPageHidden } = this.data;

      // show事件发生前，页面不是处于隐藏状态时
      if (!isPageHidden) {
        return;
      }

      // 重新执行定时器等操作
    },
    // 页面被隐藏
    hide() {
      this.setData({
        isPageHidden: true,
      });

      // 清除定时器等操作
    },
    // 页面尺寸变化时
    resize() {},
  },
};

Component(componentOptions);
