<template>
  <view class="dt-page">
    <view class="container">
      <view class="item">
        <view class="main">
          <text>姓　　名：</text>
          <view class="inputView">
            <input v-model="nameValue" placeholder="请输入姓名" placeholder-class="placeInput" />
          </view>
        </view>
        <view class="line"></view>
      </view>
      <view class="item">
        <view class="main">
          <text>手机号码：</text>
          <view class="inputView">
            <input type="number" v-model="phoneValue" placeholder="请输入手机号码" placeholder-class="placeInput" maxlength="11" />
          </view>
        </view>
        <view class="line"></view>
      </view>

      
      <picker mode="multiSelector"
        @change="onMultiPickerChange"
        @columnchange="onMultiPickerColumnChange"
        range-key="name"
        :value="regionIndex"
        :range="regionList">

        <view class="item">
          <view class="main">
            <text>所在地区：</text>
            <view class="inputView">
              <input :value="areaValue" disabled="false" placeholder="请选择所在地区" placeholder-class="placeInput" />
              <image class="arrow" src="http://139.9.103.171:1888/img/image/arrow.png" mode="widthFix"></image>
            </view>
          </view>
          <view class="line"></view>
        </view>
      </picker>
      
      <view class="item">
        <view class="main">
          <text>详细地址：</text>
          <view class="inputView">
            <input v-model="descValue" placeholder="请输入详细地址" placeholder-class="placeInput" />
          </view>
        </view>
		<view class="line"></view>
      </view>
	  <view class="item" v-if="isPromoter">
	    <view class="main">
	      <text>代理地址：</text>
	      <switch :checked="isAgent" color="#59a5f0" style="transform:scale(0.7)" @change="switchChange" />
	    </view>
	  </view>
    </view>
    <button @tap="tapSave" class="button theme-bg">保存</button>
  </view>
</template>
<script>
export default {
  data() {
    return {
      regionIndex:[],
      regionList:[],
      areaMap:{},

      areaId:0,
      // customItem: "",
      nameValue: "",
      phoneValue: "",
      areaValue: "",
      descValue: "",
      isDefaultAdd: false,
      addNew: false,
      itemObj: {},
      memberId: 0,
	  isAgent:false,
	  isPromoter:false
    };
  },
  methods: {
	  onLoadPage(){
		if(this.$auth.isPromoter()){
			this.isPromoter = true;
		}  
	  },
    switchChange(e){
		this.isAgent = e.detail.value;
	},
    // 整体变化响应
    onMultiPickerChange(e){
      console.log(103,e)
      let regionIndex = this.regionIndex.slice(0)
      let regionList = this.regionList.slice(0)

      let pItem = regionList[0][regionIndex[0]]
      let cItem = regionList[1][regionIndex[1]]
      let aItem = regionList[2][regionIndex[2]]
      
      this.areaId = aItem.id

      
      this.areaValue = this.$util.uniqueArray([
        pItem.name,
        cItem.name,
        aItem.name
        ]).join('-')
      
    },
    // 列变化响应
    onMultiPickerColumnChange(e){
      console.log(107,e.detail)
      let {column, value} = e.detail
      let regionIndex = this.regionIndex.slice(0)

      if(column==2){// 区变化
        regionIndex[2] = value
        this.regionIndex = regionIndex
        return 
      }
      let regionList = this.regionList.slice(0)
      if(column==0){ // 省份变化
        let pList = regionList[0]
        let pItem = pList[value]
        if(pItem.addresses.length==0){// 只有省份
          regionList[1] = [pItem]
          regionList[2] = [pItem]
        }else{
          if(pItem.addresses[0].addresses.length==0){// 只有城市和区
            regionList[1] = [pItem]
            regionList[2] = pItem.addresses
          }else{// 正常省市区
            regionList[1] = pItem.addresses
            regionList[2] = pItem.addresses[0].addresses
          }
        }
        regionIndex = [value,0,0]
      }else if(column==1){ // 城市变化
        let cList = regionList[1]
        regionList[2] = cList[value].addresses
        regionIndex = [regionIndex[0],value,0]
      }
      this.regionIndex = regionIndex
      this.regionList = regionList
    },
    tapSave() {
      if (this.nameValue == "") {
        this.$dialog.alert({ content: "名字不能为空" });
        return;
      }
      if (this.phoneValue == "") {
        this.$dialog.alert({ content: "手机号码不能为空" });
        return;
      }
      if (!this.checkMobile(this.phoneValue)) {
        this.$dialog.alert({ content: "手机号码有误" });
        return;
      }
      if (this.areaValue == "") {
        this.$dialog.alert({ content: "所在地区不能为空" });
        return;
      }
      if (this.descValue == "") {
        this.$dialog.success({ content: "详细地址不能为空" });
        return;
      }
      if (this.addNew == true) {
        this.addAddress();
      } else {
        this.addAddress(this.itemObj);
      }
    },
    checkMobile(phoneStr) {
      if (phoneStr.length < 11) {
        return false;
      } else if (!/^1[3|4|5|6|7|8][0-9]\d{4,8}$/.test(phoneStr)) {
        return false;
      } else {
        return true;
      }
    },
    // 添加、修改
    async addAddress(item) {
      let toastText = '保存成功'
      let params = {
        _isShowLoading:true,
        _loadingText:'添加中...',
        consignee: this.nameValue,
        phone: this.phoneValue,
        // address: this.areaValue+'-'+this.descValue,
        address: this.descValue,
        isDefault: false,
        areaId: parseInt(this.areaId),
		isAgent:this.isAgent
        // areaName:this.areaValue,
      }
      if(item && item.id){
        params.id = item.id
        params.isDefault = item.isDefault
        params._loadingText = '更新中...'
        toastText = '修改成功'
      }
	  if(this.isAgent){
		  let resp = await this.$api.addAgentAddress(params);
	  }else{
		  let resp = await this.$api.addAddress(params);
	  }
		
      this.$dialog.success(toastText, () => {
        this.$util.refreshPage(["pages/address_list"]);
        uni.navigateBack({
          delta: 1
        })
      });
    },
    findAreaIndex(){

    },
    async qeuryAreaList(){
      let resp = await this.$api.areaList()
      let regionList = []
      regionList[0] = resp
      if(this.addNew){
        if(resp[0].addresses.length==0){// 只有省份
          regionList[1] = [resp[0]]
          regionList[2] = [resp[0]]
        }else{
          if(resp[0].addresses[0].addresses.length==0){// 只有城市和区
            regionList[1] = [resp[0]]
            regionList[2] = resp[0].addresses
          }else{// 正常省市区
            regionList[1] = resp[0].addresses
            regionList[2] = resp[0].addresses[0].addresses
          }
        }
        this.regionIndex = [0,0,0]
      }else{
        let regionIndex = []
        let areaIds = this.itemObj.areaIds.slice(0)
        let pid = areaIds[0]
        let cid = areaIds[1]
        let aid = areaIds[2]
        
        let provinceItem = {}
        let pidx = 0, cidx = 0, aidx = 0;
        for(let i=0,pitem; pitem = resp[i];i++){
          if(pitem.id == pid){
            provinceItem = pitem
            pidx = i
            break;
          }
        }
        
        if(areaIds.length==1){// 只有省
          regionList[1] = [provinceItem]
          regionList[2] = [provinceItem]
          regionIndex = [pidx,0,0]
          this.areaId = pid
        }else if(areaIds.length==2){// 只有市、区
          regionList[1] = [provinceItem]
          regionList[2] = provinceItem.addresses
          for(let j=0,citem;citem = regionList[2][j];j++){
            if(citem==cid){
              cidx = j
              break;
            }
          }
          regionIndex = [pidx,0,cidx]
          this.areaId = cid
        }else{// 省、市、区
          let cityItem = {}
          regionList[1] = provinceItem.addresses
          for(let j=0,citem;citem = regionList[1][j];j++){
            if(citem.id==cid){
              cityItem = citem
              cidx = j
              break;
            }
          }
          // console.log(252,cityItem)
          regionList[2] = cityItem.addresses
          for(let k=0,aitem;aitem = regionList[2][k];k++){
            if(aitem==aid){
              aidx = k
              break;
            }
          }
          regionIndex = [pidx,cidx,aidx]
          this.areaId = aid
        }
        this.regionIndex = regionIndex
      }
      this.regionList = regionList
    },
    onLoadPage(options) {
	  wx.hideShareMenu();
      this.qeuryAreaList()
      this.memberId = this.$auth.getMemberId();
      this.addNew = options.addNew;
      if (options.addNew == "1") {
        this.addNew = true;
      } else {
        let objStr = options.item;
        let itemObj = JSON.parse(objStr);
        this.nameValue = itemObj.consignee;
        this.phoneValue = itemObj.phone;
        this.descValue = itemObj.address
        this.areaValue = itemObj.areaName
        this.isDefaultAdd = itemObj.isDefault;
		this.isAgent = itemObj.isAgent;
        this.itemObj = itemObj
        this.addNew = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.dt-page{
  background-color:#f2f2f2;
  min-height:100vh;
}
.container {
  background: white;
}
.item {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  padding: 0 30upx;
  font-size: 28upx;
  height: 90upx;
  .main {
    display: flex;
    flex-direction: row;
    align-items: center;
    height: 90upx;
    
    text {
      width: 25%;
      color:#666666;
    }
    .inputView {
      position:relative;
      display:flex;
      align-items: center;
      width: 80%;
      input {
        flex:1;
        color:#333333;
      }
      .arrow {
        width:14upx;
        height:24upx;
      }
    }
  }
  .line {
    height: 1.5upx;
    background: rgb(238, 238, 238);
  }
}

.placeInput {
  color: rgb(204, 204, 204);
  font-size: 26upx;
}
.button {
  margin: 60upx 30upx 0 30upx;
  background-color: $base;
  color: white;
  height: 90upx;
  line-height: 90upx;
  font-size: 30upx;
}
</style>
