<template>
<view id="order-apply">
    <view class="title">选择类型</view>
    <view class="content">
       <text>服务类型</text>
        <picker :value="selectedIndex" :range="list"  @change="change" range-key="name">
            <!--<view class="picker">{{list[selectedIndex]}}</view>-->
            <input type="text" placeholder="选择售后服务类型" disabled :value="list[selectedIndex].name"></input>
        </picker>
    </view>
    <view class="title">退款信息</view>
    <view class="list">
         <view class="list-detail">
             <text>申请数量</text>
              <view class="num">
                  <view class="subtraction" @tap="plus">+</view>
                  <view class="text-number">{{applyNum}}</view>
                  <view class="plus" @tap="minus">-</view> 
              </view>
             <!--<input type="range" />-->
         </view>
        <view class="content">
            <text>退换原因</text>
            <picker :value="reasonIndex" :range="reason" range-key="name" @change="changeCause" mode = selector>
                <!--<view class="picker">{{list[selectedIndex]}}</view>-->
                <input type="text" placeholder="选择退换原因" disabled :value="reason[reasonIndex].name"></input>
            </picker>
        </view>
        <view class="list-detail">
            <text>退款金额</text>
            <view class="right"><input type="text" @input="changeValue" :value="amount" :placeholder="'最多可退' + availableAmount + '元'"></input></view>

        </view>
    </view>
    <view class="title">
         问题描述 
    </view>
    <view class="text-area">
        <textarea @input="changeDetail" :value="qestionDetail" contenteditable="true"></textarea>
    </view>
    <view class="title">
        上传凭证
    </view>
    <view class="content btn-box">
        <view class="imgContainer" v-for="(img, index) in imgList" :key="index">
            <image :src="img"></image>
            <view class="delete" :data-index="index" @tap="deleteImg">X</view>
        </view>
         <view class="append" @tap="selectImage" v-if="imgList.length<5">
               +
         </view>
    </view>
    <view class="submit" :style="'background: ' + config.mainColor" @tap="submitApplication">
        提交
    </view>
</view>

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

export default {
  data() {
    return {
      list: [{
		  name:'',
		  value:''
	  }],
      // 最大的申请数量
      maxNum: "",
      selectedIndex:0,
      // 申请数量
      applyNum: 1,
      // 退款金额
      amount: "",
      // 问题描述
      qestionDetail: "",
      // 可退的金额
      availableAmount: "",
      reason: [{
		  name:'',
		  value:''
	  }],
      reasonIndex:0,
      imgList: [],
      order_id: "",
      order_item_id: "",
      good: {
        money: "",
        number: ""
      },
      config: ''
    };
  },

  onLoad(e) {
    // 第三方平台配置颜色
    var config = this.$cookieStorage.get('globalConfig') || '';
    this.setData({
      config: config
    });
    var id = e.id,
        no = e.no;
    this.setData({
      order_id: no,
      order_item_id: id
    });
    pageLogin(getUrl(), () => {
      this.queryRefundBaseInfo(id);
      this.queryCauseList();
    });
  },

  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);
    //     }
    // });
  },
  methods: {
    changeValue(e) {
      let amount = e.detail.value;

      if (!amount) {
        amount = '';
      } else if (/\S*$/.test(amount)) {
        amount = amount.replace(/[^\d\.]|^\./g, '').replace(/\.{2}/g, '.').replace(/^([1-9]\d*|0)(\.\d{1,2})(\.|\d{1})?$/, '$1$2').replace(/^0\d{1}/g, '0');
      }

      if (Number(amount) > this.availableAmount) {
        amount = this.availableAmount;
      }

      this.setData({
        amount: amount
      });
    },

    changeDetail(e) {
      var str = e.detail.value;

      if (e.detail.value.length > 150) {
        wx.showModal({
          title: '提示',
          content: '超出字数限制'
        });
        str = str.slice(0, 150);
      }

      this.setData({
        qestionDetail: str
      });
    },

    setAmount(i) {
      this.setData({
        availableAmount: (this.good.money / this.good.number * i).toFixed(2)
      });
    },

    change(e) {
     console.log(e);
      // 修改选中项文案
      this.setData({
        selectedIndex: e.detail.value
      });
	  console.log('this.selectedIndex',this.selectedIndex)
    },
    changeCause: function (e) {
      this.setData({
        reasonIndex: e.detail.value
      });
    },
    getValue: function (e) {
      console.log(e.detail.value);
    },

    deleteImg(e) {
      var i = e.currentTarget.dataset.index;
      var arr = this.imgList;
      arr.splice(i, 1);
      this.setData({
        imgList: arr
      });
    },

    selectImage() {
      uni.chooseImage({
        count: 1,
		 sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		 sourceType: ['album'], //从相册选择
        success: res => {
          var tempFilePaths = res.tempFilePaths;
          var token = this.$cookieStorage.get('user_token');
          /* this.$http.uploadFile({
            header: {
              'content-type': 'multipart/form-data',
              Authorization: token
            },
            api: 'api/users/upload/avatar',
            //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            name: 'avatar_file'
          }).then(res => {
            var result = JSON.parse(res.data);
            var arr = this.imgList;
            arr.push(result.data.url); // this.imgList.push();

            this.setData({
              imgList: arr
            });
          }); */
		  uni.uploadFile({
		  	header: {
		  		Authorization: token
		  	},
		  	url: config.GLOBAL.baseUrl + 'api/users/upload/avatar',
		  	filePath: tempFilePaths[0],
		  	fileType: 'image',
		  	name: 'avatar_file',
		  	success: res => {
		  		var result = JSON.parse(res.data);
		  		var arr = this.imgList;
		  		arr.push(result.data.url); // this.imgList.push();
		  		
		  		this.setData({
		  		  imgList: arr
		  		});
		  	}
		  })
        }
      });
    },

    submitApplication() {
      var applyItem = {
        order_no: this.order_id,
        order_item_id: parseInt(this.order_item_id),
        quantity: parseInt(this.applyNum),
        images: this.imgList,
        amount: parseFloat(this.amount),
        content: this.qestionDetail,
        type: this.list[this.selectedIndex].value,
        reason:this.reason[this.reasonIndex].value
      },
          message = null;
      if (!is.has(applyItem.type)) {
        message = "请选择售后类型";
      } else if (!is.has(applyItem.reason)) {
        message = '请填写退换原因';
      } else if (!is.has(applyItem.amount)) {
        message = '请填写退款金额';
      } 

/* else if (!is.has(applyItem.content)) {
        message = "请输入问题描述";
      } */
      if (message) {
        wx.showModal({
          title: '提示',
          content: message,
          showCancel: false
        });
      } else {
        applyItem.type = parseInt(applyItem.type);
        this.applyretreat(applyItem);
      }
    },

    applyretreat(data) {
      wx.showLoading({
        mask: true,
        title: '正在申请'
      });
      this.$http.post({
        api: "api/refund/apply",
        data: data,
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        }
      }).then(res => {
        if (res.statusCode == 200) {
          res = res.data;

          if (res.status) {
            wx.showToast({
              title: "申请成功请等待审核",
              duration: 1500,
              success: () => {
                setTimeout(() => {
                  wx.redirectTo({
                    url: '/pages/afterSales/detail/detail?no=' + res.data.refund_no
                  });
                }, 1500);
              }
            });
          } else {
            wx.showModal({
              content: res.message || '申请失败',
              showCancel: false
            });
          }

          wx.hideLoading();
        } else {
          wx.showModal({
            content: '申请失败',
            showCancel: false
          });
          wx.hideLoading();
        }
      });
    },

    plus() {
      var num = this.applyNum;
      num++;
      if (num > this.maxNum) return;
      this.setData({
        applyNum: num
      });
      this.setAmount(num);
    },

    minus() {
      var num = this.applyNum;
      if (num <= 1) return;
      num--;
      this.setData({
        applyNum: num
      });
      this.setAmount(num);
    },

    queryRefundBaseInfo(id) {
      this.$http.get({
        api: "api/refund/base_info",
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        },
        data: {
          order_item_id: id
        }
      }).then(res => {
        var store = res.data.data;
        var meta = res.data.meta.type;
        var list = [];
        meta.forEach(v => {
          list.push({
            name: v.value,
            value: String(v.key)
          });
        });
        /*var list=[{
            name: meta[0].value,
            value: meta[0].key
        }];*/

        this.setData({
          'good.money': store.total / 100,
          'good.number': store.quantity,
          availableAmount: (store.total / 100 / store.quantity).toFixed(2),
          maxNum: store.quantity,
          list: list
        });
      });
    },

    queryServiceList(status, distribution_status) {
      this.$http.get({
        api: 'api/users/BankAccount/show-bank',
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        }
      }).then(res => {
        res = res.data;
      });
    },

    queryCauseList(type = 'order_refund_reason') {
      this.$http.get({
        api: 'api/system/settings',
        header: {
          Authorization: this.$cookieStorage.get('user_token')
        },
        data: {
          type: type
        }
      }).then(res => {
        res = res.data;
        var list = [];
        res.data.forEach(v => {
          if (v.is_enabled != 0) {
            list.push({
              name: v.value,
              value: String(v.key)
            });
          }
        });
        this.setData({
          reason: list
        });
      });
    },

    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">
    @import "apply";
</style>
