<template>
  <el-form ref="form" :rules="rules" :model="form" label-width="80px" label-position="top" size="small">
    <el-row :gutter="40">
      <el-col :span="24">
        <el-form-item :label="label" prop="fileList">
          <div class="device-wrap">
            <uploader v-if="mode === 'preview'" v-model="form.fileList" list-type="picture-card" mode="preview" />
            <uploader
              v-else
              ref="fileUpload"
              v-model="form.fileList"
              :data="postData"
              :action="upload.action"
              :before-upload="onUploadBefore"
              :limit="limit"
              :placeholder="placeholder"
              :accept="accept"
              :upload-type="uploadType"
              :sign-key="signKey"
              :attachment-url="attachmentUrl"
              list-type="picture-card"
              @on-error="onUploadError"
              @on-success="onUploadSuccess"
              @on-remove="onUploadRemove"
            />
            <i v-if="device.showTakePhoto && mode == 'upload'" class="icon-device-video" @click="showDialog = true" />
          </div>
        </el-form-item>
      </el-col>
    </el-row>
    <device-dialog :show.sync="showDialog" :data="form.fileList" :sign="sign" :attachment-url="attachmentUrl" :sign-key="signKey" :limit="limit" @getPhoto="getPhoto" />
  </el-form>
</template>
<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { postVinUpload } from '@/api/realname-enterprise'
import Uploader from '@/components/Uploader'
import deviceDialog from '@/components/Device/dialog'
export default {
  name: 'FileInfo',
  components: {
    Uploader,
    deviceDialog
  },
  props: {
    mode: {
      type: String,
      default: 'upload' // upload/preview
    },
    sign: {
      type: Boolean,
      default: false
    },
    limit: {
      type: Number,
      default: 5
    },
    label: {
      type: String,
      default: '文件信息'
    },
    placeholder: {
      type: String,
      default: '上传文件'
    },
    fileSize: {
      type: Number,
      default: 5
    },
    accept: {
      type: String,
      default: 'image/png,image/jpeg,image/jpg,application/pdf'
    },
    postData: {
      type: Object,
      default() {
        return {
          rootPath: '',
          path: ''
        }
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    },
    uploadType: {
      type: Array,
      default: undefined
    },
    signKey: {
      type: String,
      default: ''
    },
    attachmentUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    const checkFileList = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error(`请上传${this.label}`))
      } else {
        callback()
      }
    }
    return {
      showDialog: false,
      upload: {
        headers: {
          'Authorization': `bearer ${getToken()}`
        },
        action: postVinUpload
      },
      form: {
        fileList: []
      },
      rules: {
        fileList: [
          { required: true, validator: checkFileList, trigger: 'blur, change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['dict', 'device']),
    previewList() {
      if (this.mode === 'preview') {
        return this.form.fileList.map(item => {
          return item.accessUrl
        })
      }
      return []
    }
  },
  watch: {
    data() {
      this.updateInternalData()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.updateInternalData()
    },

    updateInternalData() {
      if (typeof this.data === 'object' && this.data !== null) {
        this.form.fileList = this.data.fileList || []
      } else {
        this.form.fileList = []
      }
    },

    /**
    * 获取图片
    * @time 2022-05-11 23:32:36
    */
    getPhoto(data) {
      this.form.fileList = data
    },

    /**
    * 凭证上传校验
    * @time 2022-04-11 09:16:44
    */
    onUploadBefore(file) {
      const accept = this.accept.split(',')
      const fileSize = file.size / 1024 / 1024 < this.fileSize
      if (!accept.includes(file.type)) {
        this.$message.error(`${this.label}格式不对`)
        return false
      }
      if (!fileSize) {
        this.$message.error(`${this.label}大小不能超过5MB!`)
        return false
      }
    },

    /**
    * 凭证上传成功
    * @time 2022-04-09 17:22:21
    */
    onUploadSuccess() {
      this.$nextTick(() => {
        this.$refs.form.validateField('fileList')
      })
    },

    /**
    * 凭证上传失败
    * @time 2022-04-09 17:22:21
    */
    onUploadError() {
      this.$message.error('文件上传失败')
      this.onUploadRemove()
    },

    /**
    * 移除上传凭证
    * @time 2022-04-09 17:22:21
    */
    onUploadRemove() {
      this.$nextTick(() => {
        this.$refs.form.validateField('fileList')
      })
    },

    /**
    * 获取当前模块数据
    * @time 2022-04-23 15:50:05
    */
    async validate() {
      try {
        await this.$refs.form.validate()
        return true
      } catch (e) {
        let temp = {
          anchor: () => {
            this.$refs.form.fields.filter(item => item.validateState === 'error')[0].$el.scrollIntoView(true)
            temp = null
          }
        }
        throw temp
      }
    },

    /**
    * 获取表单数据
    * @time 2022-04-23 18:02:02
    */
    getFormData() {
      return this.form
    },
    getPendingCacheData() {
      return this.form
    },

    /**
     * 清空校验值
     */
    clearValidate() {
      this.$refs.form.clearValidate()
    }
  }
}
</script>
