<template>
  <el-form
    ref="sysAttachmentFrom"
    v-loading="loading"
    :model="form"
    label-width="190px"
    size="small"
    :rules="rules"
    class="upload-temporary-file"
  >
    <div class="base-dialog-body">
      <el-form-item
        :label="$t('dictionary:signature:form:FileTypeId')"
        prop="FileTypeId"
      >
        <el-select
          v-model="form.FileTypeId"
          style="width: 100%"
          size="small"
          filterable
        >
          <el-option
            v-for="item of dictionaryList.Sys_Document"
            :key="item.Id"
            :label="item.Value"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('dictionary:signature:form:File')">
        <div class="upload-container">
          <el-upload
            class="upload-demo"
            action
            accept=".pdf"
            :before-upload="beforeUpload"
            :http-request="handleUploadFile"
            :on-preview="handlePreview"
            :on-remove="handleRemoveFile"
            :show-file-list="true"
            :file-list="fileList"
            :limit="1"
            :on-exceed="handleExceed"
            :disabled="form.Type === ''"
          >
            <el-button
              size="small"
              type="primary"
              :disabled="form.FileTypeId === ''"
              :loading="btnLoading"
              >{{ $t('common:button:check') }}</el-button
            >
            <span slot="tip" style="margin-left: 10px" class="el-upload__tip">
              ({{ $t('trials:signature:label:mustBepdf') }})
            </span>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item
        :label="$t('dictionary:signature:form:NeedConfirmedUserTypeIdList')"
        prop="NeedConfirmedUserTypeIdList"
      >
        <el-select
          v-model="form.NeedConfirmedUserTypeIdList"
          style="width: 100%"
          multiple
        >
          <el-option
            v-for="item of userTypeOptions"
            :key="item.Id"
            :label="item.UserTypeShortName"
            :value="item.Id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="$t('dictionary:signature:form:DocUserSignType')"
        prop="DocUserSignType"
      >
        <el-switch
          v-model="form.DocUserSignType"
          :active-value="1"
          :inactive-value="0"
        >
        </el-switch>
      </el-form-item>
      <el-form-item
        :label="$t('dictionary:signature:form:SignViewMinimumMinutes')"
        prop="SignViewMinimumMinutes"
      >
        <el-input-number
          v-model="form.SignViewMinimumMinutes"
          controls-position="right"
          :min="1"
          :max="50"
        />
      </el-form-item>
      <!-- <el-form-item v-if="form.Id !== ''" label="是否废除: ">
        <el-radio-group v-model="form.IsDeleted">
          <el-radio :label="true">是</el-radio>
          <el-radio :label="false">否</el-radio>
        </el-radio-group>
      </el-form-item> -->
    </div>
    <div class="base-dialog-footer" style="text-align: right; margin-top: 10px">
      <el-form-item style="text-align: right">
        <el-button
          size="small"
          type="primary"
          :disabled="form.FileTypeId === '' || form.Name === ''"
          :loading="saveBtnLoading"
          @click="handleSave"
          >{{ $t('common:button:save') }}</el-button
        >
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import { addOrUpdateSystemDocument } from '@/api/dictionary'
import { getTrialUserTypeList } from '@/api/trials'
import { getBasicDataSelects } from '@/api/dictionary/dictionary'
export default {
  props: {
    data: {
      type: Object,
      default() {
        return {}
      },
    },
  },

  data() {
    return {
      form: {
        Id: '',
        FileTypeId: '',
        Name: '',
        Path: '',
        IsDeleted: false,
        SignViewMinimumMinutes: null,
        DocUserSignType: 0,
      },
      rules: {
        FileTypeId: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur'],
          },
        ],
        SignViewMinimumMinutes: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['change'],
          },
        ],
        NeedConfirmedUserTypeIdList: [
          {
            required: true,
            message: this.$t('common:ruleMessage:select'),
            trigger: ['blur'],
          },
        ],
      },
      fileList: [],
      userTypeOptions: [],
      btnLoading: false,
      saveBtnLoading: false,
      loading: false,
      dictionaryList: {},
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    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,
              url: this.data.Path,
              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.SignViewMinimumMinutes = this.data.SignViewMinimumMinutes
        this.form.DocUserSignType = this.data.DocUserSignType
      }
      this.loading = false
    },
    // 获取文件类型下拉框
    getDicData() {
      getBasicDataSelects(['Sys_Document'])
        .then((res) => {
          this.dictionaryList = { ...res.Result }
        })
        .catch(() => {})
    },
    // 获取用户类型下拉数据
    getUserType() {
      getTrialUserTypeList()
        .then((res) => {
          this.userTypeOptions = res.Result
          if (this.form.Id) {
            this.form.NeedConfirmedUserTypeIdList =
              this.data.NeedConfirmedUserTypeIds
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    beforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        this.fileList = []
        return true
      } else {
        this.$alert(this.$t('trials:signature:label:mustBepdf'))

        return false
      }
    },
    async handleUploadFile(param) {
      this.loading = true
      var file = await this.fileToBlob(param.file)
      const res = await this.OSSclient.put(
        `/System/DocumentToSign/${param.file.name}${new Date().getTime()}`,
        file
      )
      this.fileList.push({
        name: param.file.name,
        path: this.$getObjectName(res.url),
        url: this.$getObjectName(res.url),
      })
      this.form.Path = this.$getObjectName(res.url)
      this.form.Name = param.file.name
      this.loading = false
    },
    handleSave() {
      this.$refs.sysAttachmentFrom.validate((valid) => {
        if (!valid) return
        if (!this.form.Name) {
          this.$alert(this.$t('trials:signature:message:selectFile'))
          return
        }
        this.saveBtnLoading = true
        addOrUpdateSystemDocument(this.form)
          .then((res) => {
            this.saveBtnLoading = false
            this.$emit('closeDialog')
            this.$emit('getList')
            this.$message.success(this.$t('common:message:updatedSuccessfully'))
          })
          .catch(() => {
            this.saveBtnLoading = false
          })
      })
    },
    handleRemoveFile() {
      this.fileList = []
      this.form.Path = ''
      this.form.Name = ''
    },
    handlePreview(file) {
      if (file.fullPath) {
        window.open(file.fullPath, '_blank')
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(this.$t('upload:rule:maxFile1'))
    },
    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>
