const uploadJS = require('../../mixin/upload.js')
const { userApplyShop } = require('./api/index')
const { isMobile } = require('../../utils/validate')
const { getShopDetail } = require('../../api/common')
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    form: {
      'user_name': '', // 用户姓名
      'shop_name': '', // 店铺名称
      'user_card': '', // 身份证
      'shop_phone': '', // 手机号码
      'country_msg': '', // 乡村信息
      'user_code_url': [], // 微信二维码
      'user_wechat_code': '', // 微信号
      'shop_img_url': [], // 店铺图片地址
      'shop_address': {
        'longitude': 0, // 经度
        'latitude': 0, // 纬度
        'address_name': '', // 起点位置名称
        'name': ''
      }, // 店铺地址
      'shop_remark': '' // 备注
    },
    booLock: false,
    userInfo: {}
  },
  tempFormKey: '',
  tempPostData: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.bindCallBack()
    app.fetchUserDataCallback = () => {
      this.bindCallBack()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },
  bindCallBack() {
    this.setData({
      userInfo: app.globalData.userInfo
    }, () => {
      this.fetchShopDetail()
    })
  },
  async fetchShopDetail() {
    const { user_shop_id } = this.data.userInfo
    let temp = {}

    if (!user_shop_id) {
      return
    }

    try {
      const { status, data, msg } = await getShopDetail(user_shop_id)
      if (status) {

        for (let key in data) {
          let value = data[key]
          if ((Array.isArray(value) && value.length >= 1) || (Object.prototype.toString.call(value) === '[object Object]') || (typeof value === 'string' && value) || typeof value === 'number') {

            if (key === 'user_code_url' || key === 'shop_img_url') {
              value = [
                {
                  'formkey': key,
                  'url': value
                }
              ]
            }

            if (key === 'shop_address') {
              value = JSON.parse(value)
            }

            if (this.data.form.hasOwnProperty(key)) {
              temp[`form.${key}`] = value
            }
          }
        }

        this.setData(temp)
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    } catch (err) {}
  },
  ...uploadJS,
  uploadCallBack(res) {
    const temp = res.map(item => {
      return {
        'url': item.url,
        'formkey': item.formkey
      }
    })
    let tempForm = {}
    let formkey = ''
    if (temp.length > 0) {
      formkey = temp[0].formkey
    }

    switch (formkey) {
      case 'user_code_url':
      case 'shop_img_url':
        tempForm[`form.${formkey}[0]`] = temp[0]
        break
      default:
    }

    if (Object.keys(tempForm).length > 0) {
      this.setData(tempForm)
    }
  },
  setFormValue(event) {
    const { value } = event.detail
    const { formkey } = event.target.dataset
    let tempForm = {}

    switch (formkey) {
      case 'user_name':
      case 'shop_name':
      case 'user_card':
      case 'country_msg':
      case 'user_wechat_code':
      case 'shop_remark':
        tempForm[`form.${formkey}`] = value
        break
      case 'shop_phone':
        tempForm[`form.${formkey}`] = value.replace(/[^\d]$/, '').replace(/^0/, '').replace(/(\d{11}(.*))/, '$1')
        break
      default:
    }

    this.setData(tempForm)
  },
  // 获取定位权限、定位权限授权
  async handleGetSetting() {
    const that = this

    try {
      const { errMsg, authSetting } = await wx.getSetting()
      if (errMsg === 'getSetting:ok') {
        // 有定位授权
        if (authSetting['scope.userLocation']) {
          if (that.tempFormKey === '') {

          } else {
            await that.chooseLocationBridge()
          }
          return
        }
      }
    } catch (err) {}

    try {
      await wx.authorize({ scope: 'scope.userLocation' })
      if (that.tempFormKey === '') {

      } else {
        await that.chooseLocationBridge()
      }
    } catch (err) {
      wx.showModal({
        title: '提示',
        content: '未开启获取地理位置权限,去设置中打开',
        success(res) {
          if (res.confirm) {
            that.openSetting()
          }
        }
      })
    }
  },
  // 去小程序自带设置页:返回
  async openSetting() {
    try {
      const openSettingData = await wx.openSetting()
      // 开启了定位权限
      if (openSettingData.authSetting['scope.userLocation']) {
        if (this.tempFormKey === '') {

        } else {
          await this.chooseLocationBridge()
        }
      }
    } catch (err) {}
  },
  async handleChooseLocation(e) {
    const { lat, lon, formkey } = e.currentTarget.dataset
    this.tempPostData = lat && lon ? {
      latitude: lat,
      longitude: lon
    } : {}
    this.tempFormKey = 'form.' + formkey
    await this.handleGetSetting()
  },
  async chooseLocationBridge() {
    if (!this.tempFormKey) {
      return
    }
    try {
      const { errMsg, address, latitude, longitude, name } = await wx.chooseLocation(this.tempPostData)
      if (errMsg === 'chooseLocation:ok' && address && name) {
        const pointInfo = {
          address_name: address,
          name,
          latitude,
          longitude
        }

        this.setData({
          [this.tempFormKey]: pointInfo
        })
      }
    } catch (err) {
      // 点击了取消按钮
      if (err.errMsg === 'chooseLocation:fail cancel') {
      }
      // 未开启授权
      if (err.errMsg === 'chooseLocation:fail auth deny') {
      }
    }
  },
  getForm() {
    const {
      user_name,
      shop_name,
      user_card,
      shop_phone,
      country_msg,
      user_code_url,
      user_wechat_code,
      shop_img_url,
      shop_address,
      shop_remark
    } = this.data.form

    return {
      user_name,
      shop_name,
      user_card,
      shop_phone,
      country_msg,
      user_code_url: user_code_url.map(item => item.url).join(''),
      user_wechat_code,
      shop_img_url: shop_img_url.map(item => item.url).join(''),
      shop_address,
      shop_remark
    }
  },
  verify() {
    let errorList = []
    const {
      user_name,
      user_card,
      shop_phone,
      country_msg,
      shop_address,
    } = this.getForm()

    if (!user_name) {
      errorList.push('请输入姓名')
    }
    if (!user_card) {
      errorList.push('请输入身份证号码')
    }
    if (!isMobile(shop_phone)) {
      errorList.push('请输入手机号')
    }
    if (!country_msg) {
      errorList.push('请输入村信息')
    }

    if (!shop_address.address_name) {
      errorList.push('请选择详细地址')
    }

    return errorList
  },
  async onSubmit() {
    const temp = this.getForm()
    const verifyList = this.verify()

    if (verifyList.length) {
      wx.showToast({
        title: verifyList[0],
        icon: 'none'
      })
      return
    }
    this.setData({
      booLock: true
    })
    try {
      const { status, data, msg } = await userApplyShop(temp)
      if (status) {
        wx.switchTab({
          url: '/pages/mine/mine'
        })
      } else {
        wx.showToast({
          title: msg,
          icon: 'none'
        })
      }
    } catch (err) {}
    this.setData({
      booLock: false
    })
  }
})