
// pages/addAddress/addAddress.js
const wxService = require('../../utils/wxService')

wxService.page({

  /**
   * 页面的初始数据
   */
  data: {
    isSelect:true,
    citys: null,
    cityView: '',
    isDefault: 0,
    formData: {},
    selectCityName: ['', ''],
    multiIndex: [0, 0, 0],
    focus: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    if(options.id){
      wx.setNavigationBarTitle({
        title: '编辑地址'
      })
      this.setData({
        addressId: options.id
      })
    }else{
      wx.setNavigationBarTitle({
        title: '新增地址'
      })
    }
    this.init(options)
  },

  init(options) {
    const id = options.id
    if (id) {
      const addressItem = pageParmas.getObject('addressItem')
      if (addressItem) {
        let cityView = ''
        if (addressItem.districtName) {
          cityView = addressItem.districtName.replace(/,/g, ' ')
        }
        this.setData({
          formData: addressItem,
          isDefault: addressItem.isDefault,
          id,
          cityView
        })
      }
      
    }
    wxService.getC1().then((c1) => {
      return wxService.Promise.all([wxService.Promise.resolve(c1), wxService.getC2ByC1('北京'), wxService.getC3ByC2('北京北京市')])
    }).then(res => {
      const citys = res.map(item => {
        return [...item]
      })
      this.setData({
        citys
      })
    })
  },

  bindMultiPickerChange(e) {
    const citys = this.data.citys
    const multiIndex = e.detail.value
    if (citys) {
      const cityView = [citys[0][multiIndex[0]], citys[1][multiIndex[1]], citys[2][multiIndex[2]]].join(' ')
      this.setData({
        multiIndex,
        cityView
      })
    }
  },

  bindMultiPickerColumnChange(e) {
    const detail = e.detail
    const index = detail.value
    let cityName = ''
    switch (detail.column) {
      case 0:
        cityName = this.data.citys[0][index]
        this.data.selectCityName[0] = cityName
        wxService.getC2ByC1(cityName)
          .then(item => {
            let c2 = [...item]
            this.data.selectCityName[1] = c2[0]
            return wxService.Promise.all([wxService.Promise.resolve(item), wxService.getC3ByC2(this.data.selectCityName.join(''))])
          }).then((res) => {
            this.setData({
              'citys[1]': [...res[0]],
              'citys[2]': [...res[1]]
            })
          })
        break
      case 1:
        cityName = this.data.citys[1][index]
        this.data.selectCityName[1] = cityName
        wxService.getC3ByC2(this.data.selectCityName.join(''))
          .then(item => {
            this.setData({
              'citys[2]': [...item]
            })
          })
        break
      default:
        break
    }
  },

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

  },

  settingDefaultAddress(){
    this.setData({
      isSelect: !this.data.isSelect
    })
  }
})