<template>
<view id="address-add">
	<view class="indetify-img" v-show="parseResult" @tap="closeImg">
		<image src="https://cdn.guojiang.club/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20200403161800.png" mode="widthFix"></image>
	</view>
   <view class="address-info">
        <view class="info-item">
            <label for="name">姓名:</label>
            <view class="form-control">
                <input type="text" id="name" data-type="accept_name" :value="detail.accept_name" @input="input" />
            </view>
        </view>
		<view class="info-item">
		    <radio-group class="lf-flex">
				<label>
					<radio></radio>
					<text class="lf-m-l-15">女士</text>
				</label>
				<label>
					<radio></radio>
					<text class="lf-m-l-15">先生</text>
				</label>
			</radio-group>
		</view>
        <view class="info-item">
            <label for="phone">联系电话:</label>
            <view class="form-control">
                <input type="number" id="phone" data-type="mobile" :value="detail.mobile" @input="input" />
            </view>
        </view>
		
		<!-- #ifdef MP-WEIXIN -->
		<view class="info-item">
		    <label>所在地:</label>
				<view class="form-control select">
					<picker mode="region" @change="bindRegionChange" :value="detail.address_name">
						<view class="picker">
							{{detail.address_name[0] || ''}} {{detail.address_name[1] || ''}} {{detail.address_name[2] || ''}}
						</view>
					</picker>
				</view>
		</view>
       <!-- #endif -->
	   
	   <!--  #ifdef APP-PLUS || H5 -->
	   <view class="mpvue-picker">
	   	<view class="info-item uni-btn-v" @click="showMulLinkageThreePicker">
	   		<label>所在地:</label>
	   		<view class="form-control select">
	   			<view class="picker uni-common-mt">
	   				{{pickerText.label || ''}}
	   			</view>
	   		</view>
	   	</view>
	   	<mpvue-city-picker :themeColor="themeColor" ref="mpvueCityPicker" :pickerValueDefault="cityPickerValueDefault"
	   	 @onConfirm="onConfirm"></mpvue-city-picker>
	   </view>
	   
	   
	   <!-- #endif -->
	   
		
		
		
        <view class="info-item">
            <label for="address">详细地址:</label>
            <view class="form-control">
                <input type="text" id="address" data-type="address" :value="detail.address" @input="input" />
            </view>
        </view>
		<!-- TODO -->
		<view class="info-item">
		    <label for="name">门牌号:</label>
		    <view class="form-control">
		        <input type="text" id="name" data-type="accept_name" :value="detail.accept_name" @input="input" />
		    </view>
		</view>
        <view class="info-item">
            <label class="checkbox" @tap="check">
                <!-- #ifdef H5 -->
                <checkbox color="red" :checked="detail.is_default"></checkbox>
                <!-- #endif -->
				<!-- #ifdef APP-PLUS -->
				<checkbox color="#FFFFFF" :checked="detail.is_default"></checkbox>
				<!-- #endif -->
				<!-- #ifdef MP-WEIXIN -->
				<checkbox color="#FFFFFF" :checked="detail.is_default"></checkbox>
				<!-- #endif -->
                <text class="lf-m-l-10">设为默认地址</text>
            </label>
        </view>
    </view>
	<view class="identify-address">
		<textarea @input="changeIdentify" :value="address_text" placeholder-class="textarea-placeholder" placeholder="粘贴或输入整段地址，点击“识别”自动拆分姓名、电话和地址。" />
		<view class="btn-box" v-if="address_text">
			<view class="clear" @tap="clearInfo">清空</view>
			<view class="sure" @tap="sureAddress">识别</view>
		</view>
	</view>
   <view class="button-box">
        <button type="primary" :style="'background: ' + config.mainColor" class="submit" @tap="submit" :loading="loading">保存</button>
        <!-- <button type="warn" class="delete" :style="'background: ' + config.secColor" v-if="id" @tap="deleteAddress" :loading="deleteLoading">删除</button> -->
    </view>
</view>

</template>
<script>
import {pageLogin, getUrl,config,is} from '@/common/js/utils.js';

// #ifdef H5
import wPicker from "@/components/w-picker/w-picker.vue";
// #endif
// #ifdef APP-PLUS || H5
	import mpvueCityPicker from '@/components/mpvue-citypicker/mpvueCityPicker.vue';
	import provinceData from '@/components/mpvue-citypicker/city-data/province.js';
	import cityData from '@/components/mpvue-citypicker/city-data/city.js';
	// #endif 
	import AddressParse from '@/common/js/zh-address-parse.min.js'


export default {
  data() {
    return {
      detail: {
        is_default: false,
        address_name: [
			'','',''
		],
        area: 430105,
        city: 430100,
        province: 430000,
      },
      order_no: '',
      id: '',
      loading: false,
      deleteLoading: false,
      config: '',
	 
	  
	   title: 'Hello',
		/* mode:"range", */
		defaultVal:[0,0,0,0,0,0,0],
		tabList:[
		{
			mode:"region",
			name:"省市区"
		}
		],
		tabIndex:0,
		resultInfo:{
			result:""
		},
		// #ifdef H5
		mulLinkageTwoPicker:cityData,
		// #endif
		cityPickerValueDefault: [0, 0, 1],
		themeColor: '#007AFF',
		pickerText:{
			label:'',
			value:'',
			cityCode:''
		},
		mode: '',
		deepLength: 1,
		pickerValueDefault: [0],
		pickerValueArray: [],
		address_text:'',
		parseResult:''
	};
	
  },
  
  components:{
	  // #ifdef H5
	  /* wPicker */
	  // #endif
	  
	  // #ifdef APP-PLUS || H5
	  mpvueCityPicker
	  // #endif

  },
  onShow() {// let app =getApp();
    // app.isBirthday().then(()=>{
    //     if(this.$cookieStorage.get("birthday_gift")){
    //         var giftData=this.$cookieStorage.get("birthday_gift").data;
    //         new app.ToastPannel().__page.showText(giftData);
    //     }
    // });
	
	
  },
   
  onLoad(e) {
    // 第三方平台配置颜色
    var config = this.$cookieStorage.get('globalConfig') || '';
    this.setData({
      config: config
    });
    pageLogin(getUrl());
    this.setData({
      id: e.id
    });

    if (e.id) {
      wx.setNavigationBarTitle({
        title: '修改收货地址'
      });
      this.queryAddress(e.id);
    } else {
      wx.setNavigationBarTitle({
        title: '新增收货地址'
      });
    }
  },

  methods: {
	  //清楚图片
	  closeImg(){
		  this.parseResult = '';
	  },
		  
	  //清空所有地址
	  clearInfo(){
		  this.address_text = '';
	  },
	  //识别地址
	  sureAddress(){
		 if(this.address_text){
			 const options = {
			   type: 0, // 哪种方式解析，0：正则，1：树查找
			   textFilter: [], // 预清洗的字段
			   nameMaxLength: 4, // 查找最大的中文名字长度
			 }
			 let parseResult = AddressParse(this.address_text,options); 
			 this.parseResult = parseResult;
			 this.detail.accept_name = parseResult.name;
			 this.detail.mobile = parseResult.phone;
			 this.detail.address = parseResult.detail;
			 // #ifdef MP-WEIXIN
			  this.detail.address_name = [parseResult.province,parseResult.city,parseResult.area];
			 // #endif
			// #ifdef APP-PLUS || H5
			this.detail.address_name = [parseResult.province,parseResult.city,parseResult.area];
			let address =  [parseResult.province,parseResult.city,parseResult.area];
			 this.pickerText.label = address.join(' ');
			// #endif
		 } else{
			 return
		 } 
		  
	  },
	  changeIdentify(e){
		  this.address_text = e.detail.value;
	  },
	  showMulLinkageThreePicker() {
	  	this.$refs.mpvueCityPicker.show()
	  },
	  onConfirm(e) {
	  	this.pickerText = e;
	  	var index = e.value;
	  	var province_code = provinceData[index[0]].value+"0000";
	  	var city_code = cityData[index[0]][index[1]].value+"00";
	  	var label = e.label;
	  	var address_name = label.split('-');
	  	// 设置传给后台的参数
	  	this.detail.address_name = address_name;
	  	this.detail.city = city_code;
	  	this.detail.province = province_code;
	  	this.detail.area = e.cityCode;
	  	
	  }, 
    bindRegionChange(e) {
      this.setData({
        'detail.address_name': e.detail.value
      });
    },

    check(e) {
      this.setData({
        "detail.is_default": !this.detail.is_default
      });
    },

    input(e) {
      var type = e.currentTarget.dataset.type;
      var value = e.detail.value;
   //    this.setData({
   //      [`detail.${type}`]: value
   //    });
	  // 
	  this.detail[type]=value;
    },

    deleteAddress() {
      this.setData({
        deleteLoading: true
      });
      this.removeAddress(this.id);
    },

    /* onConfirm(val){
				console.log(val);
				//如果页面需要调用多个mode类型，可以根据mode处理结果渲染到哪里;
				// switch(this.mode){
				// 	case "date":
				// 		break;
				// }
				

				this.detail.address_name[0]=val.checkArr[0];
				this.detail.address_name[1]=val.checkArr[1];
				this.detail.address_name[2]=val.checkArr[2];
			
				this.resultInfo.result=val.result;
				
				
	},
 */
	toggleTab(item,index){
					this.tabIndex=index;
					this.mode=item.mode;
					this.defaultVal=item.value;
					this.$refs[item.mode].show();
	},

    submit() {
      this.setData({
        loading: true
      });
      var message = null;
	  
      if (!is.has(this.detail.accept_name)) {
        message = '请输入姓名';
      } else if (!is.has(this.detail.mobile)) {
        message = '请输入手机号码';
      } else if (!is.mobile(this.detail.mobile)) {
        message = '请输入正确的手机号码';
      } else if (!is.has(this.detail.address_name)||!is.has(this.detail.address_name[0]) ) {
        message = '请选择地址';
      } else if (!is.has(this.detail.address)) {
        message = '请输入详细地址';
      }
      if (message) {
        this.setData({
          loading: false
        });
        wx.showModal({
          title: '',
          content: message,
          showCancel: false
        });
      } else {
        if (this.id) {
          this.updateAddress(this.detail);
        } else {
          this.createAddress(this.detail);
        }
      }
    },

    // 获取收货地址详情
    queryAddress(id) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.get({
        api: 'api/address/' + id,
        header: {
          Authorization: token
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;
          var data = res.data;
          data.is_default = !!data.is_default;
          data.address_value = [data.province, data.city, data.area].join(' ');
		 
		  this.resultInfo.result=data.address_name;
		  data.address_name = data.address_name.split(' ');
		
        
          if (res.status) {
            this.setData({
              detail: data
            });
			// #ifndef MP-WEIXIN
			this.pickerText.label = res.data.address_name.join(' ')
			// #endif
			

          } else {
            wx.showToast({
              title: res.message,
              image: '../../../static/error.png'
            });
          }
        } else {
          wx.showToast({
            title: '获取信息失败',
            image: '../../../static/error.png'
          });
        }
      });
    },

    // 新增收货地址
    createAddress(data) {
      var address = {
        accept_name: data.accept_name,
        mobile: data.mobile,
        province: data.province,
        city: data.city,
        area: data.area,
        address_name: data.address_name.join(" "),
        address: data.address,
        is_default: data.is_default ? 1 : 0
      };
      var token = this.$cookieStorage.get('user_token');
      this.$http.post({
        api: 'api/address/create',
        header: {
          Authorization: token
        },
        data: address
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
			  
            wx.showModal({
              title: '',
			  content:'新增收货地址成功',
              showCancel: false,
              success: res => {
                if (res.confirm) {
                  wx.navigateBack();
                }
              }
            });
          } else {
            wx.showToast({
              title: '新增收货地址失败',
              image: '../../../static/error.png',
              complete: err => {
                setTimeout(() => {
                  wx.navigateBack();
                }, 1600);
              }
            });
          }
        } else {
          wx.showToast({
            title: '请求错误',
            image: '../../../static/error.png',
            complete: err => {
              setTimeout(() => {
                wx.navigateBack();
              }, 1600);
            }
          });
        }

        this.setData({
          loading: false
        });
      }).catch(rej => {
        this.setData({
          loading: false
        });
      });
    },

    // 修改收货地址
    updateAddress(data) {
      var address = {
        id: data.id,
        accept_name: data.accept_name,
        mobile: data.mobile,
        province: data.province,
        city: data.city,
        area: data.area,
        address_name: data.address_name.join(" "),
        address: data.address,
        is_default: data.is_default ? 1 : 0
      };
      var token = this.$cookieStorage.get('user_token');
      this.$http.ajax({
        api: 'api/address/'+data.id,
        method: 'PUT',
        header: {
          Authorization: token
        },
        data: address
      }).then(res => {
          res = res.data;

          if (res.status) {
            wx.showModal({
              title: '',
              content: '修改收货地址成功',
              showCancel: false,
              success: res => {
                if (res.confirm) {
                  wx.navigateBack();
                }
              }
            });
          } else {
            wx.showToast({
              title: '修改收货地址失败',
              image: '../../../static/error.png',
              complete: err => {
                setTimeout(() => {
                  wx.navigateBack();
                }, 1600);
              }
            });
          }

        this.setData({
          loading: false
        });
      }).catch(rej => {
        this.setData({
          loading: false
        });
      });
    },

    // 删除收货地址
    removeAddress(id) {
      var token = this.$cookieStorage.get('user_token');
      this.$http.ajax({
        api: 'api/address/' + id,
        header: {
          Authorization: token
        },
        method: 'DELETE'
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            wx.showModal({
              title: '',
              content: '删除收货地址成功',
              showCancel: false,
              success: res => {
                if (res.confirm) {
                  wx.navigateBack();
                }
              }
            });
          } else {
            wx.showToast({
              title: '删除收货地址失败',
              image: '../../../static/error.png',
              complete: err => {
                setTimeout(() => {
                  wx.navigateBack();
                }, 1600);
              }
            });
          }
        } else {
          wx.showToast({
            title: '请求错误',
            image: '../../../static/error.png',
            complete: err => {
              setTimeout(() => {
                wx.navigateBack();
              }, 1600);
            }
          });
        }

        this.setData({
          deleteLoading: false
        });
      }).catch(rej => {
        this.setData({
          deleteLoading: false
        });
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  },
  computed: {},
  watch: {}
};
</script>
<style rel="stylesheet/less" lang="less" scoped>
    @import "add";
	.identify-address>textarea{
		border-color: #e5e5e5 !important;
	}
</style>
