<template>
  <!-- 申请的表单 换货2,退货3  -->
  <view class="dt-page">
    
    <view class="comp-list-item">
      <view class="left-item">
        <text>售后类型</text>
      </view>
      <view class="right-item">{{loadOptions.saleType==2?'申请换货':'申请退货'}}</view>
    </view>
	<!-- <view class="comp-list-item" @tap="showSaleType">
	  <view class="left-item">
	    <text>售后类型</text>
	  </view>
	  <view class="right-item">
	    <input :value="saleTypeLabel" type="text" placeholder="请选择售后类型" disabled/>
	  </view>
	</view> -->
    <view class="comp-list-item">
      <view class="left-item">
        <text>订单编号</text>
      </view>
      <!-- <view class="right-item">{{ loadOptions.orderSn|defaultValue('无') }}</view> -->
      <view class="right-item">{{ orderSn|defaultValue('无') }}</view>
    </view>
    <view class="item-margin"></view>
    <block v-if="loadOptions.saleType==2">
      <view class="comp-list-item">
        <view class="left-item">
          <text>收货人</text>
        </view>
        <view class="right-item">
          <input v-model="formData.receiver" type="text" placeholder="请填写收货人姓名">
        </view>
      </view>
      <view class="comp-list-item">
        <view class="left-item">
          <text>地区</text>
        </view>
        <picker mode="multiSelector"
          @change="onMultiPickerChange"
          @columnchange="onMultiPickerColumnChange"
          range-key="name"
          :value="regionIndex"
          :range="regionList">

          <view class="right-item">
            <input v-model="formData.area" type="text" placeholder="请选择您收货的地区" disabled/>
            <image src="http://139.9.103.171:1888/img/image/arrow.png"></image>
          </view>
        </picker>
      </view>

      <view class="comp-list-item">
        <view class="left-item">
          <text>详细地址</text>
        </view>
        <view class="right-item">
          <input v-model="formData.detail" type="text" placeholder="请输入详细地址" />
        </view>
      </view>
      <view class="comp-list-item">
        <view class="left-item">
          <text>联系电话</text>
        </view>
        <view class="right-item">
          <input v-model="formData.phone" type="text" maxlength="11" placeholder="请填写联系电话" />
        </view>
      </view>

      <view class="item-margin"></view>
      <view class="comp-list-item form-block">
        <view class="left-item">
          <text>售后原因</text>
        </view>
        <view class="right-item">
          <textarea v-model="formData.reason" maxlength="-1" class="reason" placeholder="请输入您售后的原因"></textarea>
        </view>
      </view>
    </block>
    <block v-else>
      <view class="comp-list-item">
        <view class="left-item">
          <text>退货方式</text>
        </view>
        <view class="right-item">在线支付</view>
      </view>
      <view class="item-margin"></view>
      <view class="comp-list-item form-block">
        <view class="left-item">
          <text>售后原因</text>
        </view>
        <view class="right-item">
          <textarea v-model="formData2.reason" maxlength="-1" class="reason" placeholder="请输入您售后的原因"></textarea>
        </view>
      </view>
    </block>
    
    
    <FootToolbar bgColor="#fff">
      <view slot="main" class="btn-voucher-wrap">
        <button @tap="tapSubmit" class="dt-btn-submit btn-voucher" hover-class="button-hover-scale">提交售后申请</button>
      </view>
    </FootToolbar>
	<FootSaleType ref="footSaleType"
	  :dataList.sync="saleTypeList"
	  @choose="onChoose" />
  </view>
</template>
<script>
import FootToolbar from '../comps/foot_toolbar.vue'
import FootSaleType from '../comps/foot_sale_type.vue'
export default {
  components:{
    FootToolbar,
	FootSaleType
  },
  data(){
    return {
      formData:{
        receiver:'',      // 收货人
        area:'',          // 收货地址
        detail:'',        // 详细地址
        phone:'',        // 联系电话
        reason:'',        // 售后原因
      },
      formRules:{
        receiver:[{
          required:true,
          message:'请输入收货人'
        }],
        area:[{
          required:true,
          message:'请选择地址'
        }],
        detail:[{
          required:true,
          message:'请输入详细地址'
        }],
        phone:[{
          required:true,
          message:'请输入联系电话'
        },{
          type:'mobile',
          message:'手机号码有误！'
        }],
        reason:[{
          required:true,
          message:'请输入退货原因'
        }],
      },

      formData2:{
        reason:'',        // 售后原因
      },
      formRules2:{
        reason:[{
          required:true,
          message:'请输入售后原因'
        }]
      },
      areaId:0,
      areaValue:'',
      regionIndex:[],
      regionList:[],
      orderItems:{},
      orderSn:'',
	  saleTypeList:[
	    { label:'申请换货',value:2, checked:false },
	    { label:'申请退货',value:3, checked:true }
	  ],
	  saleTypeLabel:'申请退货'
    }
  },
  methods:{
    showSaleType(){
      this.$refs.footSaleType.show(this.formData.saleType)
    },
	onChoose(curCheck){
	  this.loadOptions.saleType = curCheck.value
	  this.saleTypeLabel = curCheck.label
	},
    // 整体变化响应
    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.formData.area = 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
    },
    
    tapSubmit(){
      if(this.loadOptions.saleType==2){
        if(!this.validate(this.formRules,this.formData)){
          return
        }
        this.exchange()
        
      }else{
        if(!this.validate(this.formRules2,this.formData2)){
          return
        }
        this.refund()
      }
    },
    // 申请售后，换货
    async exchange(){
      let resp = await this.$api.applyAfterSale({
        type: 2,
        sn: this.loadOptions.orderSn,
        consignee: this.formData.receiver,
        area: this.formData.area,
        address: this.formData.detail,
        phone: this.formData.phone,
        reason: this.formData.reason,
        orderItems: this.loadOptions.orderItems || {},
      })
      this.$dialog.success('申请成功', () => {
        this.$util.refreshPage(['pages/mine','pages/mine_order_list'])
        uni.navigateBack({
          delta:4
        })
      })
    },
    // 申请售后，退款
    async refund(){
      let resp = await this.$api.applyAfterSale({
        type: 3,
        // sn: this.loadOptions.orderSn,
        sn: this.orderSn,
        method: 'ONLINE',
        reason: this.formData2.reason,
        // orderItems: this.loadOptions.orderItems || {},
        orderItems: this.orderItems
      })
      this.$dialog.success('申请成功', () => {
        this.$util.refreshPage(['pages/mine','pages/mine_order_list'])
        uni.navigateBack({
          delta:2
        })
      })
    },
    
    async qeuryAreaList(){
      let resp = await this.$api.areaList()
      let regionList = []
      regionList[0] = resp
      if(true){
        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
    },
    async queryDataList() {
      let resp = await this.$api.getOrderAfterSaleInfo({
        _isShowLoading: true,
        orderId: this.loadOptions.orderId
      })
      if(Array.isArray(resp)){
        this.orderItems = {}
        for (let item of resp) {
        	if(item.store.id == this.$global.server.storeId){
				for (let orderItem of item.orderItems) {
					if(orderItem.allowApplyAftersalesQuantity > 0){
						this.orderItems[orderItem.id] = orderItem.allowApplyAftersalesQuantity;
					}
				}
				this.orderSn = item.sn
        	}
        }
      }
	  if(JSON.stringify(this.orderItems)=="{}"){
		   this.$dialog.alert({
		  	content:'当前商品已申请售后',
		  	confirmText: '确定',
		  	success: (res) => {
		  		if (res.confirm) {
		  			this.$util.refreshPage(['pages/mine','pages/mine_order_list'])
		  			uni.navigateBack({
		  			  delta:2
		  			})
		  		}
		  	}
		  })
	  }
    },
    onLoadPage(options){
	  wx.hideShareMenu();
      if(this.isLoad){
        // if(options.orderItems){
        //   let orderItems = JSON.parse(options.orderItems)
        //   this.loadOptions.orderItems = orderItems
        // }
        
        // if(options.saleType==2){// 换货
        //   this.formData.reason = options.reason
        //   this.qeuryAreaList()
        // }else{// 退货
        //   this.formData2.reason = options.reason
        // }
        this.loadOptions.saleType = 3 // 默认 退货
        this.queryDataList()
      }
    },
  }
}
</script>

<style lang="scss" scoped>
.dt-page{
  min-height:100vh;
  background-color:#f2f2f2;
  .comp-list-item {
    position: relative;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 0 30upx;
    color: #353535;
    justify-content: space-between;
    margin-top: 0;
    min-height: 90upx;
    border-bottom: 2upx solid #f2f2f2;
    background: #fff;

    .left-item {
      display: flex;
      align-items: center;
      text {
        max-height: 100%;
        overflow: hidden;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        text-overflow: ellipsis;
      }
    }
    .right-item {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      width:50vw;
      min-height:90upx;
      
      text {
        color: #999999;
      }
      image {
        margin-left: 20upx;
        width: 13upx;
        height: 24upx;
      }
      .reason{
        width:100%;
        min-height:200upx;
        padding-bottom:30upx;
        box-sizing:border-box;
      }
    }
  }
  .form-block{
      flex-wrap:wrap;
      .left-item{
        width:100%;
        line-height:1;
        padding:30upx 0;
      }
      .right-item{
        flex-wrap:wrap;
        width:100%;
        .choose-item{
          padding-left:16upx;
          width:100%;
          display:flex;
          align-items: center;
          line-height:60upx;
          .lable{
            padding-left:10upx;
          }
        }
        .choose-item:last-child{
          padding-bottom:20upx;
        }
      }
    }
  .item-margin{
    width:100%;
    height:20upx;
  }
  
  .hidden{
    opacity:0;
  }
  input{
    text-align: right;
  }

  .btn-voucher-wrap{
    display:flex;
    justify-content: center;
    align-items: center;
    width:100vw;
    height:110upx;
    background-color:#fff;
    .btn-voucher{
      width:690upx;
      height:80upx;
      line-height:80upx;
      color:#fff;
      background-color:$dt-color-primary; 
      font-size: 30upx;
    }
  }
}
</style>