<template>
  <div class="freight">
    <cr-form :show-error-message="false" @submit="onSubmit" @failed="onFailed">
      <cr-field
        v-model="remark"
        :disabled="true"
        name="remark"
        label="退款原因"
        placeholder="请填写退款原因"
      />
      <cr-field
        v-model.trim="amount"
        type="number"
        name="amount"
        label="退款金额"
        placeholder="请输入运费金额"
        :rules="[{ required: true, message: '请正确输入运费金额，保留两位小数', pattern }]"
      >
        <template v-slot:button>
          <cr-button class="btn-yuan" type="default" size="mini">￥</cr-button>
        </template>
      </cr-field>
      <p class="freight-account">{{ refundFreightFeePaymentName }}</p>
      <cr-field
        v-model="payee"
        name="payee"
        label="账户姓名"
        placeholder="请输入收款账户姓名"
        :rules="[{ required: true, message: '请输入收款账户姓名' }]"
      />
      <cr-field
        v-model.trim="receiptAccount"
        type="account"
        name="receiptAccount"
        label="账户帐号"
        placeholder="请输入收款账户帐号"
        :rules="[{ required: true, message: '请输入收款账户帐号' }]"
      />
      <p class="freight-voucher">上传凭证<span>（最多6张）</span></p>
      <div class="freight-uploader">
        <cr-uploader
          v-model="orderList"
          :before-read="
            file => {
              asyncRead(file);
            }
          "
          max-number="6"
        />
      </div>
      <div class="freight-submit">
        <cr-button block shape="circle" type="primary" native-type="submit">提交</cr-button>
      </div>
    </cr-form>
  </div>
</template>
<script>
import { upload } from 'qiniu-js';
import orderApi from '@/api/order.api';
import config from '../../config/index';
import localStorage from '@/service/localStorage.service';
export default {
  name: 'RefundFreight',
  data() {
    return {
      amount: '',
      payee: '',
      remark: '退运费',
      orderList: [],
      maxLimit: 9,
      receiptAccount: '',
      pattern: /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/,
      refundFreightFeePaymentName: ''
    };
  },
  mounted() {
    this.getToken();
    this.refundFreightFeePaymentName = this.$route.query.refundFreightFeePaymentName || '';
  },
  methods: {
    async onSubmit(values) {
      if (this.amount < 0) {
        this.$toast.fail('金额不能小于0');
        return;
      }
      if (this.amount && this.payee && this.receiptAccount && this.orderList) {
        let urls = [];
        this.orderList.map(item => {
          urls.push(item.url);
        });
        // 缺少 退款金额
        const params = {
          serviceNo: this.$route.params.id,
          ...values,
          proofList: urls
        };
        Reflect.deleteProperty(params, 'remark');
        const [res] = await orderApi.refundFreight(params);
        if (res) {
          this.$router.replace({
            name: 'refundFreightSuccess',
            query: {
              vccToken: localStorage.get('vccToken'),
              orderNo: this.$route.query.orderNo,
              orderSkuId: this.$route.query.orderSkuId
            }
          });
        }
      }
    },
    onFailed(errorInfo) {
      console.log('failed', errorInfo);
    },
    getToken() {
      orderApi.getQiniuToken().then(res => {
        this.token = res[0].token;
      });
    },
    asyncRead(file) {
      const that = this;
      let idx = that.orderList.length;
      if (file.length + idx >= +this.maxLimit) {
        file = file.splice(0, this.maxLimit - idx);
      }
      for (let key of file) {
        const observable = upload(key, null, this.token);
        const observer = {
          next() {
            that.orderList[idx] = {
              status: 'uploading'
            };
            that.orderList = [...that.orderList];
          },
          error(err) {
            console.log(err);
          },
          complete({ hash }) {
            const fileLink = config.qiniuHost + '/' + hash;
            console.log(fileLink, 'fileLink');
            that.orderList[idx] = {
              url: fileLink,
              isImage: true,
              status: 'done'
            };
            that.orderList = JSON.parse(JSON.stringify([...that.orderList]));
            console.log(that.orderList);
            idx = idx + 1;
          }
        };
        observable.subscribe(observer); // 上传开始
      }
      return;
    }
  }
};
</script>
<style lang="less" scoped>
.freight {
  /deep/ .cr-field--control {
    input:disabled,
    input[disabled] {
      color: #333;
      opacity: 1;
      -webkit-text-fill-color: #333; // ios 和 安卓9.0 必须添加此属性，才会生效
      -webkit-opacity: 1;
    }
  }
  .btn-yuan {
    border: none;
  }
  &-account {
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #333333;
    background-color: #fff;
    margin-top: 12px;
    padding: 17px 20px 10px 12px;
  }
  &-voucher {
    font-size: 14px;
    font-family: SourceHanSansCN-Regular, SourceHanSansCN;
    font-weight: 400;
    color: #333333;
    padding: 20px 0px 13px 12px;
    background-color: #fff;
    margin-top: 12px;
    span {
      color: #999999;
    }
  }
  &-uploader {
    background-color: #fff;
    padding-left: 12px;
  }
  &-submit {
    padding: 20px 10px;
    background-color: #fff;
    position: fixed;
    bottom: 0px;
    width: 355px;
  }
}
</style>
