<template>
  <div class="refund">
    <cr-form>
      <cr-cell
        v-model="form.reasonText"
        title="退款原因"
        is-link
        :class="['required', 'cell-height', { noempty: form.reasonText !== '请选择' }]"
        @click="openReasonOptions"
      />
      <cr-field
        v-model="form.amount"
        label="退款金额"
        readonly
        error
        class="amount field-height fontS"
        required
        :error-message="`不可修改，最多${form.amount}`"
      />
      <cr-field
        v-model="form.mark"
        label="退款说明"
        type="textarea"
        placeholder="请输入退款说明（最多200字）"
        rows="1"
        autosize
        required
        :show-word-limit="false"
        :max-length="200"
        class="cell-height fontS"
      />
      <cr-field
        v-model="form.phone"
        type="phone"
        label="联系电话"
        placeholder="请输入联系电话"
        :formatter="phone"
        :max-length="11"
        required
        class="cell-height fontS"
      />
      <cr-cell title="上传凭证" class="upload-cell">
        <template #label>
          <cr-uploader
            v-model="fileList"
            :before-read="
              file => {
                asyncRead(file);
              }
            "
            max-number="6"
          />
        </template>
      </cr-cell>
      <cr-popup
        v-model="reasonPop"
        closeable
        round
        position="bottom"
        close-icon="https://xyqbui.lkbang.net/close.png"
        :style="{ height: '320px' }"
      >
        <div class="popDiv">
          <p class="popTitle">请选择原因</p>
          <cr-radio-group v-model="choiceReason" direction="vertical">
            <cr-radio v-for="(value, key) in reasonArr" :key="key" :name="key">{{
              value
            }}</cr-radio>
          </cr-radio-group>
          <cr-button shape="circle" type="primary" class="popBtn" @click="submitPop">
            确认
          </cr-button>
        </div>
      </cr-popup>
      <div class="subDiv">
        <cr-button shape="circle" type="primary" class="subBtn" @click="submit">提交申请</cr-button>
      </div>
    </cr-form>
  </div>
</template>
<script>
import { upload } from 'qiniu-js'; // 换为按需引入，可减少一部分的代码，如果有问题，换回官网引用方式
import config from '@/config/index';
import orderApi from '@/api/order.api';
import localStorage from '@/service/localStorage.service';
export default {
  data() {
    return {
      reasonPop: false,
      form: {
        reasonText: '请选择',
        mark: '',
        phone: null,
        amount: '¥',
        reason: ''
      },
      fileList: [],
      choiceReason: '',
      maxLimit: 3,
      reasonArr: {
        1: '未按承诺时间发货',
        4: '多拍/拍错/不想要',
        5: '其他原因'
      },
      rules: [
        { key: 'reason', message: '请填写退款原因' },
        {
          key: 'mark',
          message: '请填写退款说明'
        },
        {
          key: 'phone',
          message: '请填写联系电话'
        }
      ],
      token: null,
      orderNo: null
    };
  },
  computed: {},
  mounted() {
    this.getToken();
    this.orderNo = this.$route.query.orderNo;
    this.form.amount += this.$route.query.refundAmount;
  },
  methods: {
    openReasonOptions() {
      this.reasonPop = true;
      this.choiceReason = this.form.reason;
    },
    asyncRead(file) {
      const that = this;
      let idx = that.fileList.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.fileList[idx] = {
              status: 'uploading'
            };
            that.fileList = [...that.fileList];
          },
          error(err) {
            console.log(err);
          },
          complete({ hash }) {
            const fileLink = config.qiniuHost + '/' + hash;
            that.fileList[idx] = {
              url: fileLink,
              isImage: true,
              status: 'done'
            };
            that.fileList = JSON.parse(JSON.stringify([...that.fileList]));
            idx = idx + 1;
          }
        };
        observable.subscribe(observer); // 上传开始
      }
      return;
    },
    submit() {
      if (this.check()) {
        const { reason, phone, mark } = this.form;
        const params = {
          amount: +this.$route.query.refundAmount,
          proofs: this.fileList.map(item => item.url),
          orderNo: this.orderNo,
          reason: +reason,
          phone,
          mark
        };
        orderApi.refundKepler(params).then(() => {
          this.$router.replace({
            path: '/orderDetail',
            query: { orderNo: this.orderNo, vccToken: localStorage.get('vccToken') }
          });
        });
      }
    },
    check() {
      let flag = true;
      for (let arr of this.rules) {
        const { key, message } = arr;
        const error = (errorM = message) => {
          this.$toast(errorM);
          flag = false;
        };
        if (!this.form[key] || this.form[key] === '请选择') {
          error();
          break;
        }
        if (key === 'phone' && this.form[key].length !== 11) {
          error('请正确输入联系电话');
          break;
        }
      }
      return flag;
    },
    submitPop() {
      this.form.reasonText = this.reasonArr[this.choiceReason];
      this.form.reason = this.choiceReason;
      this.reasonPop = false;
    },
    phone(value) {
      // 不严谨的正则
      return value.replace(/[^\d]/g, '');
    },
    getToken() {
      orderApi.getQiniuToken().then(res => {
        this.token = res[0].token;
      });
    }
  }
};
</script>
<style lang="less" scoped>
.refund {
  font-size: 15px;
  /deep/ .cr-popup--close {
    top: 15px;
    right: 20px;
  }
  /deep/ .upload .cr-icon--clear {
    font-size: 18px;
  }
  .amount {
    @{deep} .cr-field--error-message {
      color: @gray-4;
    }
  }
  .required @{deep}.cr-cell__title:before {
    position: absolute;
    left: 8px;
    content: '*';
    color: #ee0a24;
    font-size: 14px;
  }
  @{deep} .cr-cell {
    .fontS;
  }
  @{deep}.cr-cell__title {
    color: @gray-5;
  }
  @{deep} .cr-cell__value {
    color: @gray-3;
  }
  .noempty {
    @{deep} .cr-cell__value {
      color: @gray-5;
    }
  }
  .popDiv {
    padding: 5px 20px;
    .popTitle {
      font-size: 16px;
      font-weight: bold;
      width: 100%;
      text-align: center;
      line-height: 40px;
    }
    line-height: 60px;
  }
  .popBtn {
    width: 100%;
  }
  .upload-cell {
    width: 100%;
    height: 159px;
    box-sizing: border-box;
    padding: 20px;
    @{deep} .cr-cell__value {
      //只使用了cell的label,为了图省事直接吧value隐藏了
      display: none;
    }
    .upload {
      margin-top: 10px;
      width: 100%;
      .uploadImg {
        height: 85px;
        width: 85px;
        background-color: @white;
      }
      @{deep} .cr-uploader--preview {
        width: 85px;
        height: 85px;
      }
    }
  }
  .subDiv {
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
    .subBtn {
      margin-top: 56px;
      width: 100%;
    }
  }
  .cell-height {
    padding-top: 16.5px;
    padding-bottom: 16.5px;
  }
  .field-height {
    height: 70px;
  }
  .fontS {
    font-size: 14px;
  }
}
</style>
