<template>
  <el-form
    ref="trialAttachmentFrom"
    v-loading="loading"
    :model="form"
    label-width="240px"
    size="small"
    :rules="rules"
    class="upload-temporary-file"
  >
    <div class="base-dialog-body">
      <!-- 文件类型 -->
      <el-form-item :label="$t('trials:attachment:table:fileType')" prop="FileTypeId">
        <el-select
          v-model="form.FileTypeId"
          style="width:100%;"
          size="small"
        >
          <el-option
            v-for="item of dictionaryList.Trial_Document"
            :key="item.Id"
            :label="item.Value"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <!-- 文件 -->
      <el-form-item :label="$t('trials:attachment:form:file')">
        <div class="upload-container">
          <el-upload
            class="upload-demo"
            action
            accept=".pdf"
            :before-upload="beforeUpload"
            :http-request="handleUploadFile"
            :on-remove="handleRemoveFile"
            :show-file-list="true"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
            :disabled="form.FileTypeId === ''"
          >
            <el-button size="small" type="primary" :disabled="form.FileTypeId === ''">
              {{ $t('trials:attachment:button:select') }}
            </el-button>
            <span
              slot="tip"
              style="margin-left:10px;"
              class="el-upload__tip"
            >
              ({{ $t('trials:attachment:message:pdf') }})
            </span>
          </el-upload>
        </div>
      </el-form-item>
      <!-- 需要签署的用户类型 -->
      <el-form-item :label="$t('trials:attachment:table:userType')" prop="NeedConfirmedUserTypeIdList">
        <el-select
          v-model="form.NeedConfirmedUserTypeIdList"
          style="width:100%;"
          multiple
        >
          <el-option
            v-for="item of userTypeOptions"
            v-show="item.UserTypeEnum !== 4 && item.UserTypeEnum !== 3"
            :key="item.Id"
            :label="item.UserTypeShortName"
            :value="item.Id"
          >
            <span>{{ item.UserType }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 查看最短时间（分钟） -->
      <el-form-item :label="$t('trials:attachment:table:min')" prop="SignViewMinimumMinutes">
        <el-input-number
          v-model="form.SignViewMinimumMinutes"
          controls-position="right"
          :min="1"
          :max="50"
        />
      </el-form-item>
      <!-- 描述 -->
      <el-form-item :label="$t('trials:attachment:table:description')" prop="Description">
        <el-input
          v-model="form.Description"
          type="textarea"
          :autosize="{ minRows: 5, maxRows: 6}"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </div>
    <div class="base-dialog-footer" style="text-align:right;margin-top:10px;">
      <el-form-item style="text-align:right;">
        <!-- Save -->
        <el-button size="small" type="primary" :disabled="form.FileTypeId === '' || form.Name === ''" @click="handleSave">
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import { addOrUpdateTrialDocument, getTrialUserTypeList } from '@/api/trials'
import { getBasicDataSelects } from '@/api/dictionary/dictionary'
export default {
  name: 'TrialAttachmentFrom',
  props: {
    data: {
      type: Object,
      default() { return {} }
    }
  },

  data() {
    return {
      form: {
        Id: '',
        TrialId: '',
        FileTypeId: '',
        Name: '',
        Path: '',
        IsDeleted: false,
        SignViewMinimumMinutes: null,
        Description: '',
        NeedConfirmedUserTypeIdList: []
      },
      rules: {
        FileTypeId: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        SignViewMinimumMinutes: [{ required: true, message: this.$t('common:ruleMessage:specify'), trigger: ['change'] }],
        NeedConfirmedUserTypeIdList: [{ required: true, message: this.$t('common:ruleMessage:select'), trigger: ['blur', 'change'] }],
        Description: [{ max: 500, message: `${this.$t('common:ruleMessage:maxLength')} 500`, trigger: ['blur', 'change'] }]
      },
      fileList: [],
      userTypeOptions: [],
      btnLoading: false,
      saveBtnLoading: false,
      loading: false,
      dictionaryList: {}
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    // 保存
    handleSave() {
      this.$refs.trialAttachmentFrom.validate(valid => {
        if (!valid) return
        if (!this.form.Name) {
          this.$alert(this.$t('trials:attachment:message:selectFile'))
          return
        }
        this.loading = true
        this.form.TrialId = this.$route.query.trialId

        addOrUpdateTrialDocument(this.form).then(res => {
          this.loading = false
          this.$emit('closeDialog')
          this.$emit('getList')
          if (this.form.Id) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          } else {
            this.$message.success(this.$t('common:message:addedSuccessfully'))
          }
          // this.$message.success(this.$t('common:message:savedSuccessfully'))
        }).catch(() => {
          this.loading = false
        })
      })
    },
    async initForm() {
      this.loading = true
      await this.getDicData()
      await this.getUserType()
      if (Object.keys(this.data).length > 0) {
        if (this.data.Path) {
          this.fileList = [
            {
              name: this.data.Name,
              path: this.data.Path
            }
          ]
        }
        this.form.Id = this.data.Id
        this.form.FileTypeId = this.data.FileTypeId
        this.form.Name = this.data.Name
        this.form.Path = this.data.Path
        this.form.IsDeleted = this.data.IsDeleted
        this.form.Description = this.data.Description
        this.form.SignViewMinimumMinutes = this.data.SignViewMinimumMinutes
      }
      this.loading = false
    },
    // 获取文件类型下拉框数据
    getDicData() {
      getBasicDataSelects(['Trial_Document']).then(res => {
        this.dictionaryList = { ...res.Result }
      })
    },
    // 获取用户类型下拉数据
    getUserType() {
      getTrialUserTypeList().then(res => {
        this.userTypeOptions = res.Result
        if (this.form.Id) {
          this.form.NeedConfirmedUserTypeIdList = this.data.NeedConfirmedUserTypeeIds
        }
      }).catch(() => { this.loading = false })
    },
    handleViewableUserTypeChange(valArr) {
      this.form.NeedConfirmedUserTypeIdList = []
      this.needConfirmedUserTypeOptions = []
      valArr.forEach((val) => {
        const i = this.userTypeOptions.findIndex(userType => { return userType.Id === val })
        this.needConfirmedUserTypeOptions.push(this.userTypeOptions[i])
      })
    },
    // 检测文件类型是否符合要求
    beforeUpload(file) {
      if (this.checkFileSuffix(file.name)) {
        this.fileList = []
        return true
      } else {
        this.$alert(this.$t('trials:attachment:message:pdf'))

        return false
      }
    },
    // 上传文件
    async handleUploadFile(param) {
      this.loading = true
      var file = await this.fileToBlob(param.file)
      const trialId = this.$route.query.trialId
      const res = await this.OSSclient.put(`/${trialId}/DocamentToSign/${param.file.name}`, file)
      this.fileList.push({ name: param.file.name, path: this.$getObjectName(res.url) })
      this.form.Path = this.$getObjectName(res.url)
      this.form.Name = param.file.name
      this.loading = false

      // this.btnLoading = true
      // const trialId = this.$route.query.trialId
      // TrialID/DocamentToSign/
      // uploadTrialDoc(trialId, param.file).then(res => {
      //   this.btnLoading = false
      //   if (res.IsSuccess) {
      //     this.form.Path = res.Result.FilePath
      //     this.form.Name = param.file.name
      //     const file = { name: this.form.Name, path: this.form.Path }
      //     this.fileList.push(file)
      //   }
      // }).catch(() => {
      //   this.btnLoading = false
      // })
    },
    fileToBlob(file) {
      // 创建 FileReader 对象
      const reader = new FileReader()
      return new Promise(resolve => {
        // FileReader 添加 load 事件
        reader.addEventListener('load', (e) => {
          let blob
          if (typeof e.target.result === 'object') {
            blob = new Blob([e.target.result])
          } else {
            blob = e.target.result
          }
          resolve(blob)
        })
        // FileReader 以 ArrayBuffer 格式 读取 File 对象中数据
        reader.readAsArrayBuffer(file)
      })
    },
    // 移除
    handleRemoveFile() {
      this.fileList = []
      this.form.Path = ''
      this.form.Name = ''
    },
    handleExceed(files, fileList) {
      this.$message.warning(this.$t('trials:attachment:message:uploadFile'))
    },
    // 文件类型是否是pdf
    checkFileSuffix(fileName) {
      var typeArr = ['pdf']
      var extendName = fileName.substring(fileName.lastIndexOf('.') + 1).toLocaleLowerCase()
      if (typeArr.indexOf(extendName) !== -1) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>

<style lang="scss">
.upload-temporary-file{
  .upload-container .el-upload--text {
    border: none;
    width: 80px;
    height: 40px;
  }
  .upload-container .el-input--small {
    margin-bottom: 5px;
  }
  .upload-container .el-icon-circle-check {
    color: #428bca;
    font-size: 13px;
  }
  .account_item_clear{
    .el-tag__close{
      display: none !important;
    }
  }

}
</style>
