/*
 * @Descripttion: HJ
 * @Company: 思宏科技
 * @version: v1.0
 * @Author: HJ
 * @Date: 2021-06-09 14:15:06
 * @LastEditors: zhangzhuobin 1093998108@qq.com
 * @LastEditTime: 2022-07-21 10:52:09
 */
import { fhGetPhone } from '../../../api/auth/index'
import { fhGetHospitalAddress } from '../../../api/hospital/index'
import {
  fhControlAddress,
  fhGetAddressDetail,
  fhDeleteAddress,
  fhEditAddress
} from '../../../api/address/index'
import { debounce } from '../../../utils/tool'
const { Tips, Loading, hLoading } = getApp()
const pageOptions = {
  // 页面数据
  data: {
    isFirstOnShow: true, // 是否为首次执行onShow
    form: {
      sex: 1,
      phone: '',
      name: '',
      addressDetail: ''
    },
    addressText: '',
    // 当前操作类型
    type: 'add'
  },
  // 页面载入时
  onLoad(e) {
    this.init(e)
  },
  // 页面初始化
  init(e) {
    const { type, id } = e
    this.setData({
      type,
      form: id ? e : { sex: 1, phone: '', name: '', addressDetail: '' }
    })

    this.getHospitalAddress()
  },
  // 页面准备好时
  onReady() {},
  // 页面显示时
  onShow() {
    const { isFirstOnShow } = this.data

    if (isFirstOnShow) {
      // 首次执行时
      this.setData({
        isFirstOnShow: false
      })
      return
    }
  },
  // 自定义事件
  // 获取医院地址信息
  getHospitalAddress() {
    const results = wx.$getGlobalData('hospitalAddress')
    const { poiName, addressDetail } = results
    console.log(results, addressDetail, 'results, addressDetail')
    this.tempHospitalInfo = { ...results, address: addressDetail }
    console.log(this.tempHospitalInfo, 'tempHospitalInfo')
    const addressText = `${poiName}${addressDetail}`
    this.setData({
      addressText
    })
  },
  // 自动获取手机号
  automaticPhone(e) {
    const { errMsg } = e.detail
    if (errMsg.includes('deny')) return

    const mobile = wx.getStorageSync('auth-phone')
    if (mobile) {
      this.setData({
        'form.phone': mobile
      })
    } else {
      this.authPhone(e)
    }
  },
  // 授权手机号
  authPhone(e) {
    wx.login({
      success: async res => {
        const openId = wx.getStorageSync('openid')
        const { code } = res
        const accountInfo = wx.getAccountInfoSync()
        const { appId } = accountInfo.miniProgram
        try {
          const {
            results: { phoneNumber }
          } = await fhGetPhone({
            appId,
            code,
            openId,
            ...e.detail
          })
          this.setData({
            'form.phone': phoneNumber
          })
          Tips('获取手机号成功')
        } catch (e) {
          console.error('授权手机号 error:', e)
        }
      }
    })
  },
  // 输入
  onInputChange({ currentTarget: { dataset }, detail }) {
    const { key } = dataset
    this.setData({
      [`form.${key}`]: detail
    })
  },
  // 切换性别
  radioChange({ detail: { value } }) {
    this.setData({
      'form.sex': value
    })
  },
  // 获取收货地址详情
  async getAddressDetail(id) {
    try {
      const { results } = await fhGetAddressDetail(id)
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 删除一个地址
  async deleteAddress() {
    try {
      await fhDeleteAddress(this.data.form.id)
      Tips('删除地址成功')
      this.back()
    } catch (e) {
      console.log('debug axios', e)
    }
  },
  // 保存地址
  saveAddress: debounce(async function() {
    if (this.btnLoading) return
    this.btnLoading = true
    console.log(this.tempHospitalInfo, this.data.form, '我要的');
    // 定义sickAreaId,从本地存储获取值, 由于客户后端定义字段为sickAreaId, 我们后端定义为sickareaId, 所以需要新添加一个
    const sickAreaId = wx.getStorageSync('hospital-info').sickareaId
    Loading()
    try {
      await fhControlAddress({
        ...this.data.form,
        ...this.tempHospitalInfo,
        sickAreaId: sickAreaId
      })
      this.back()
      Tips('创建地址成功')
      this.btnLoading = false
    } catch (e) {
      console.error('保存收货地址 error:', e)
    }
  }),
  // 编辑地址
  async editAddress() {
    Loading()
    try {
      await fhEditAddress(this.data.form.id, {
        ...this.tempHospitalInfo,
        ...this.data.form
      })
      this.back()
      Tips('编辑地址成功')
    } catch (e) {
      console.error('保存收货地址 error:', e)
    }
    hLoading()
  },
  // 返回
  back() {
    setTimeout(() => {
      wx.$routerBack()
    }, 800)
  }
}

Page(pageOptions)
