<template><page-meta :root-font-size="fontSize+'px'"></page-meta>
	<member-base :show="false"><view class="div container">
		<view class="div common-header-wrap">
			<view :style="'height:'+navHeight+'px'"></view>
			<view class="common-header-holder"></view>
			<view class="common-header-fixed">
			<title-header />
			<uni-nav-bar :title="getTitle" class="common-header" left-icon="back" @clickLeft="goBack">
			</uni-nav-bar>
		</view>
		</view>
		<view v-if="config && config.chain_isuse==1" class="div notice">
			<text class="span">使用代收点</text>
			<view class="div common-btn ds-button-small btn" @click="goChain"><text class="span">使用</text></view>
		</view>
		<view class="div main-content">
    <flex-line class="field-line" :show-border="true"><text class="span field-name">姓名</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="address_info.address_realname" /></view></flex-line>
		<flex-line class="field-line" :show-border="true"><text class="span field-name">手机</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="address_info.address_mob_phone" /></view></flex-line>
    <flex-line :is-link="true" :show-border="true">
    <text class="span">地区</text>
    <view class="div" slot="right" @click="onRegion">
        <text class="span">{{address_info.area_info}}</text>
    </view>
    </flex-line>
		<flex-line class="field-line" :show-border="true"><text class="span field-name">地址</text><view class="div field-line-right" slot="right"><input class="field-input" v-model="address_info.address_detail" /></view></flex-line>
    <flex-line :show-border="true"><text class="span line-name">默认地址</text><view class="div" slot="right"><switch @change="switchChange" :checked="!!address_info.address_is_default"></switch></view></flex-line>
		<view class="div pt-10 pb-10"><view class="div common-btn ds-button-large" @click="submit">{{getSumitTitle}}</view></view>
    </view>
		<region-picker ref="picker" v-on:onConfirm="onPickerConfirm"></region-picker>

	</view></member-base>
</template>

<script>
import {getFontSize} from '@/util/common'
import TitleHeader from '../../TitleHeader'
import { urlencode } from '@/util/common'
import MemberBase from '../MemberBase'
import { getPointByAddress } from '../../../util/bmap'
import { mapState, mapMutations, mapActions } from 'vuex'
import RegionPicker from '../../RegionPicker'
import MapSelect from '../../MapSelect'
import { getAddressInfo, addAddress, editAddress } from '../../../api/memberAddress'
import flexLine from '../../flexLine'
export default {
  components:{
    TitleHeader,
    MemberBase,
    flexLine,
    RegionPicker,
    // MapSelect
  },
  computed:{
	  fontSize(){
	    return getFontSize()
	  },
	  ...mapState({
		  config: state => state.config.config
	  }),
    isAddMode () {
      let mode = this.action
      // add: 添加地址，edit: 编辑地址
      if (mode === 'add') {
        return true
      } else {
        return false
      }
    },
    getTitle () {
      if (this.isAddMode) {
        return '新增地址'
      } else {
        return '修改收货地址'
      }
    },
    getSumitTitle () {
      let isFromCheckout = this.isFromCheckout
      if (isFromCheckout) {
        return '保存并使用'
      } else {
        return '保存'
      }
    }
  },
  mounted(){
  // #ifdef  MP-WEIXIN
  this.navHeight = uni.getMenuButtonBoundingClientRect().top
  // #endif
  },
  data(){
    return {
      navHeight: 0,
      isFromCheckout:0,
      action:'',
      popMap: false,
      address_id: 0,
      goBackLevel : 1,
      address_info: {
        address_realname: '',
        address_mob_phone: '',
        address_detail: '',
        address_is_default: true,
        area_info: '请选择地区',
        city_id: 0,
        area_id: 0,
        address_longitude: 0,
        address_latitude: 0
      }
    }
  },
  onLoad: function (option) {
    this.action=option.action
    this.isFromCheckout=option.isFromCheckout
    this.goBackLevel =option.goBackLevel ? parseInt(option.goBackLevel) : 1
	  this.fetchConfig()
    if (!this.isAddMode) {
      this.address_id = option.address_id
      getAddressInfo(this.address_id).then(res => {
        this.address_info.address_realname = res.result.address_info.address_realname
        this.address_info.address_mob_phone = res.result.address_info.address_mob_phone
        this.address_info.address_detail = res.result.address_info.address_detail
        this.address_info.area_info = res.result.address_info.area_info
        this.address_info.city_id = res.result.address_info.city_id
        this.address_info.area_id = res.result.address_info.area_id
        this.address_info.address_longitude = res.result.address_info.address_longitude
        this.address_info.address_latitude = res.result.address_info.address_latitude
        if (res.result.address_info.address_is_default === '1') {
          this.address_info.address_is_default = true
        } else {
          this.address_info.address_is_default = false
        }
      }).catch(function (error) {
        uni.showToast({icon:'none',title: error.message})
      })
    }
  },
  methods: {
	  ...mapActions({
		  fetchConfig: 'fetchConfig'
	  }),
    switchChange(e){
      this.address_info.address_is_default=e.detail.value
    },
	  goChain () {
		  uni.navigateTo({ url: '/pages/member/address/ChainForm'+'?'+urlencode( { action: 'add' } )})
	  },
    goBack () {
      uni.navigateBack({delta:this.goBackLevel})
    },
    getPosition () {
      getPointByAddress(this.address_info.area_info + this.address_info.address_detail).then(res => {
        if (res.result.location) {
          this.address_info.address_longitude = res.result.location.lng
          this.address_info.address_latitude = res.result.location.lat
        }
      }).catch(function (error) {
        uni.showToast({icon:'none',title: error.message})
      })
    },
    setPosition (lat, lng, name) {
      this.popMap = false
      this.address_info.address_detail = name
      this.address_info.address_longitude = lng
      this.address_info.address_latitude = lat
    },
    submit () {
      if (this.address_info.address_realname === '') {
        uni.showToast({icon:'none',title: '请填写收件人姓名'})
        return
      }
      if (this.address_info.address_realname.length === 0) {
        uni.showToast({icon:'none',title: '请填写收件人姓名'})
        return
      }
      if (this.address_info.address_realname.length < 2 || this.address_info.address_realname.length > 15) {
        uni.showToast({icon:'none',title: '2-15个字符限制'})
        return
      }
      if (this.address_info.address_mob_phone === '') {
        uni.showToast({icon:'none',title: '请填写手机号码'})
        return
      }
      if (this.address_info.address_mob_phone.length === 0) {
        uni.showToast({icon:'none',title: '请填写手机号码'})
        return
      }
      if (this.address_info.area_id === 0 || this.address_info.area_id === undefined) {
        uni.showToast({icon:'none',title: '请选择所在地区'})
        return
      }
      if (this.address_info.address_detail === '') {
        uni.showToast({icon:'none',title: '请填写详细地址'})
        return
      }
      if (this.address_info.address_detail.length === 0) {
        uni.showToast({icon:'none',title: '请填写详细地址'})
      }
      if (this.address_info.address_longitude === 0 || this.address_info.address_latitude === 0) {
        // uni.showToast({icon:'none',title: '请在地图选址'})
      }

      if (this.isAddMode) {
        uni.showLoading({ title: '加载中' })
        addAddress(this.address_info).then(
          (response) => {
            uni.hideLoading()
            this.updateSelectedAddress()
          }, (error) => {
            uni.hideLoading()
            uni.showToast({icon:'none',title: error.message})
          })
      } else {
        uni.showLoading({ title: '加载中' })
        editAddress(this.address_info, this.address_id).then(
          (response) => {
            uni.hideLoading()
            this.updateSelectedAddress()
          }, (error) => {
            uni.hideLoading()
            uni.showToast({icon:'none',title: error.message})
          })
      }
    },
    onRegion (picker, values) {
      this.$refs.picker.show()
    },
    onPickerConfirm (values) {
      this.address_info.area_info = this.getRegionStr(values)

      this.address_info.area_id = values[2].area_id
      this.address_info.city_id = values[1].area_id
    },
    getRegionStr (values) {
      let title = ''
      for (let i = 0; i < values.length; i++) {
        const element = values[i]
        if (i !== 0) {
          title = title + ' ' + element.area_name
        } else {
          title = title + element.area_name
        }
      }
      return title
    },
    updateSelectedAddress () {
      uni.navigateBack({delta:1})
    }
  }
}
</script>

<style lang="scss" scoped>
  .main-content{background: #fff;padding:0 $pageSpace}
	.right-arrow{transform: rotate(-90deg);color:#ddd;font-size:$fontSize;display: inline-block;}
	.input-wrap{position: relative;
		.i{position: absolute;right:0;top:0;line-height: 2.4rem;display: block;width:2rem;text-align: center;font-size:$h1}
	}
	.notice{font-size:$subFontSize;padding:.5rem;background:#FCF8E3;color:#C09853;line-height: 1.65rem;
		.red{color:#F00}
		.btn{float:right}
	}
</style>
