<template>
  <Page class="page-rnr-person-file" title="文件信息">
    <template #slot-title>
      <span>{{ currentFlow }}/{{ totalFlow }}</span>
      <span>文件信息</span>
    </template>
    <template #slot-before-main>
      <div class="page-rnr-person-file-tip">文件类型为图片文件，允许支持的照片格式包括bmp、jpg/jpeg、png，小于500K。</div>
    </template>
    <div v-if="personRnr.isConsigner" class="page-rnr-main-card" >
      <ErrorWrap :error-message="inputError.attorneyLetterPic" :error="!!inputError.attorneyLetterPic">
        <van-cell id="attorneyLetterPic" :required="true" title="个人授权书" class="van-field">
          <template #label>
            <BridgeUpload v-model="attorneyLetterPic">
              <div class="page-rnr-main-card-upload-normal">
                <div class="icon-upload-camera" />
              </div>
            </BridgeUpload>
          </template>
        </van-cell>
      </ErrorWrap>
    </div>
    <div v-if="personRnr.customerType == 1" class="page-rnr-main-card">
      <ErrorWrap :error-message="inputError.purchaseContractPic" :error="!!inputError.purchaseContractPic">
        <van-cell id="purchaseContractPic" :required="true" title="购车合同" class="van-field">
          <template #label>
            <BridgeUpload v-model="formData.purchaseContractPic">
              <div class="page-rnr-main-card-upload-normal">
                <div class="icon-upload-camera" />
              </div>
            </BridgeUpload>
          </template>
        </van-cell>
      </ErrorWrap>
    </div>
    <div v-if="personRnr.customerType == 1" class="page-rnr-main-card">
      <ErrorWrap :error-message="inputError.purchaseInvoicePic" :error="!!inputError.purchaseInvoicePic">
        <van-cell id="purchaseInvoicePic" :required="true" title="购车发票或行驶本之一" class="van-field">
          <template #label>
            <BridgeUpload v-model="formData.purchaseInvoicePic">
              <div class="page-rnr-main-card-upload-normal">
                <div class="icon-upload-camera" />
              </div>
            </BridgeUpload>
          </template>
        </van-cell>
      </ErrorWrap>
    </div>
    <div v-if="personRnr.customerType == 1" class="page-rnr-main-card">
      <ErrorWrap :error-message="inputError.transferCertificatePic" :error="!!inputError.transferCertificatePic">
        <van-cell id="contractPic" :required="true" title="过户证明" class="van-field">
          <template #label>
            <BridgeUpload v-model="formData.transferCertificatePic">
              <div class="page-rnr-main-card-upload-normal">
                <div class="icon-upload-camera" />
              </div>
            </BridgeUpload>
          </template>
        </van-cell>
      </ErrorWrap>
    </div>
    <template #slot-operation>
      <van-button type="primary" class="page-rnr-main-btn-before" round color="linear-gradient(120deg, #EDF3FF 0%, #E9F0FF 97%)" @click="handleToBefore">上一步</van-button>
      <van-button :disabled="btnDisable" type="primary" class="page-rnr-main-btn-next" round color="linear-gradient(120deg, #4F4CFB 0%, #376FF4 97%)" @click="handleToNext">下一步</van-button>
    </template>
  </Page>
</template>

<script>
import Page from '@/components/Page'
import ErrorWrap from '@/components/ErrorWrap'
import BridgeUpload from '@/components/BridgeUpload'
import { fileUpload } from '@/api/rnr'
import { Toast } from 'vant'
import { validate } from '@/utils/validate'
import { SET_PERSON_FILE, SET_PERSON_CONSIGNER_CARD } from '@/store/modules/rnr'
import { mapGetters } from 'vuex'
import flowMixin from '@/minxin/flow'

export default {
  name: 'RnrPersonCard',
  components: { Page, BridgeUpload, ErrorWrap },
  mixins: [flowMixin],
  data() {
    return {
      inputError: {},
      countTime: 59,
      isSend: false,
      showSms: false,
      attorneyLetterPic: [],
      formData: {
        purchaseContractPic: [],
        purchaseInvoicePic: [],
        transferCertificatePic: []
      }
    }
  },
  computed: {
    ...mapGetters(['personRnr']),
    /**
     * 按钮是否禁用
     */
    btnDisable() {
      // 如果当前是二手车
      if (+this.personRnr.customerType === 1) {
        const { transferCertificatePic, purchaseContractPic, purchaseInvoicePic } = this.formData
        return transferCertificatePic.length === 0 || purchaseContractPic.length === 0 || purchaseInvoicePic.length === 0
      }
      // 如果当前是代办，且没有上传个人委托人信息
      return this.personRnr.isConsigner && this.attorneyLetterPic.length === 0
    }
  },
  methods: {
    /**
     * 删除文件
     */
    handleDeleteFile(files, { index }, key) {
      this.formData[key].splice(index, 1)
    },

    /**
     * 上传文件
     * @param origin 源文件
     * @param key 字段key
     */
    handleUploadFile(origin, key) {
      // 获取当前文件
      let files = origin
      // 如果当前不是数组，则将其变成数组
      if (!(files instanceof Array)) {
        files = [files]
      }
      // 将文件的uuid都展示在界面上
      files.forEach(async file => {
        // 文件可访问路径和文件的uuid
        const { uuid } = await fileUpload({ file: file.content })
        // 将文件id保存在照片中
        this.formData[key].push(uuid)
        // 开始校验上传字段
        this.validate([key])
      })
    },

    /**
     * 调到到下一页：签名页
     */
    async handleToNext() {
      // 校验字段
      let validKey = []
      // 如果当前是代办
      if (this.personRnr.isConsigner) {
        validKey.push('attorneyLetterPic')
      }
      // 客户类型是二手车
      if (+this.personRnr.customerType === 1) {
        validKey = validKey.concat(['purchaseContractPic', 'purchaseInvoicePic', 'transferCertificatePic'])
      }
      // 校验不通过的字段
      const failField = this.validate(validKey)
      // 如果当前校验失败
      if (failField) {
        return
      }
      // 如果当前是委托人，则上传委托人
      if (this.personRnr.isConsigner) {
        this.$store.commit(`rnr/${SET_PERSON_CONSIGNER_CARD}`, {
          attorneyLetterPic: this.attorneyLetterPic
        })
      }
      // 将当前数据保存到store中
      this.$store.commit(`rnr/${SET_PERSON_FILE}`, this.formData)
      // 跳转页面
      this.routerToNextPage('RnrPersonNotification')
    },

    /**
     * 校验用户输入
     */
    validate(ruleKeys) {
      // 错误的字段，错误的信息
      const [failField, failMessage] = validate(this.formData, ruleKeys)
      // 如果当前有错误信息
      ruleKeys.forEach(key => {
        this.$set(this.inputError, key, failField === key ? failMessage : '')
      })
      return failField
    },

    /**
     * 跳转到上一页
     */
    handleToBefore() {
      // 回退到上个页面
      this.$router.back()
    },

    /**
     * 图片超过最大限制
     */
    handleOverSize() {
      Toast('选择的图片超过最大限制，请重新选择')
    }
  }
}
</script>

<style lang="scss">
.page-rnr-person-file {
  .page-rnr-main {
    margin-top: 0px;
  }
  .page-rnr-main-fixed-btn-group {
    display: flex;
    justify-content: space-between;
    .page-rnr-main-btn-before {
      color: #242424 !important;
      flex: 1;
      height: 96px;
    }
    .page-rnr-main-btn-next {
      flex: 2;
      margin-left: 40px;
      height: 96px;
    }
  }
  .icon-upload-camera {
    background-image: url(../../../assets/rnr/ico_camera.png);
    background-size: 100% 100%;
    position: absolute;
    width: 80px;
    height: 80px;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  .page-rnr-main-card-upload-normal {
    background-image: url(../../../assets/rnr/ico_pic.png);
    background-color: #F7F8FA;
    background-size: 196px 196px;
    background-repeat: no-repeat;
    background-position: center;
    border-radius: 8px;
    width: 196px;
    height: 196px;
  }
  .page-rnr-main-btn {
    font-size: 32px !important;
    &.disabled {
      color: #CACACA !important;
    }
  }
  .van-cell__label {
    .page-rnr-flex {
      display: flex;
      justify-content: space-between;
    }
  }
  .page-rnr-person-file-tip {
    font-size: 24px;
    color: rgba(255, 255, 255, 0.6);
    font-weight: 400;
    padding: 14px 48px 18px;
  }
}
</style>
