import { login } from "../logic";
import request from "../request/method";

type Status = 'loading' | 'pending' | 'success' | 'fail'
type UpdataStatusCallback = (status: Status) => void
type UpdataValueCallback = (value: string) => void

export function usePhoneNumber() {
  const _updataValue: UpdataValueCallback[] = [];
  const _updateStatus: UpdataStatusCallback[] = [];

  let value = '';
  let status: Status = 'loading';

  login(false).then(token => token ? 'pending' : 'fail' as const, () => 'fail' as const).then(_status => {
    status = _status;
    _updateStatus.forEach(cb => cb(status));
  })

  return {
    updateValue(callback: UpdataValueCallback) {
      _updataValue.push(callback);
      if (value) callback(value);
    },
    updateStatus(callback: UpdataStatusCallback) {
      _updateStatus.push(callback);
      callback(status)
    },
    getPhoneNumber(event: WechatMiniprogram.ButtonGetPhoneNumber) {
      const code = event.detail.code;
      if (!code) return;
      _updateStatus.forEach(cb => cb('loading'))
      request({
        url: `/mobileAccountManage/getAccountPhone`,
        method: 'GET',
        params: { code },
        transform({ data }) { return data; }
      }).then(phone => {
        value = phone;
        status = 'success';

        _updataValue.forEach(cb => cb(value))
        _updateStatus.forEach(cb => cb(status))
      }, (error) => {
        _updateStatus.forEach(cb => cb('pending'))
        wx.showModal({ title: '获取失败', content: error.errMsg || error.message, showCancel: false })
      })
    }
  }
}