<template>
  <el-form
    ref="sysTemplateFrom"
    v-loading="loading"
    :model="form"
    label-width="90px"
    size="small"
    :rules="rules"
    class="upload-temporary-file"
  >
    <div class="base-dialog-body">
      <el-form-item label="Code" prop="Code">
        <el-input :maxLength="$inputMax" v-model="form.Code" />
      </el-form-item>
      <el-form-item label="业务场景: " prop="BusinessScenarioEnum">
        <el-select
          v-model="form.BusinessScenarioEnum"
          style="width:100%;"
          size="small"
          filterable
        >
          <el-option
            v-for="item of $d.Common_File_BusinessScenario"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="文件: ">
        <div class="upload-container">
          <el-upload
            class="upload-demo"
            action
            accept=".xls,.xlsx,.doc,.docx"
            :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.FileTypeEnum || !form.BusinessScenarioEnum"
          >
            <el-button size="small" type="primary" :disabled="!form.FileTypeEnum || !form.BusinessScenarioEnum" :loading="btnLoading">Select</el-button>
            <span
              slot="tip"
              style="margin-left:10px;"
              class="el-upload__tip"
            >
              (must be in xlsx/xls/doc/docx format)
            </span>
          </el-upload>
        </div>
      </el-form-item>
      <el-form-item label="阅片标准: " prop="CriterionTypeEnum">
        <el-select
          v-model="form.CriterionTypeEnum"
          style="width:100%;"
          size="small"
          filterable
        >
          <el-option
            v-for="item of $d.CriterionType"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </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>
      <el-form-item label="描述">
        <el-input :maxLength="$inputMax"
          v-model="form.Description"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 4}"
          placeholder="请输入内容"
        />
      </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.FileTypeEnum || !form.BusinessScenarioEnum" :loading="saveBtnLoading" @click="handleSave">Save</el-button>
      </el-form-item>
    </div>
  </el-form>
</template>
<script>
import { addOrUpdateCommonDocument, uploadCommonDoc } from '@/api/dictionary'
import { getBasicDataSelects } from '@/api/dictionary/dictionary'
export default {
  name: 'TemplateForm',
  props: {
    data: {
      type: Object,
      default() { return {} }
    }
  },

  data() {
    return {
      form: {
        Id: '',
        Code: '',
        FileTypeEnum: null,
        BusinessScenarioEnum: null,
        CriterionTypeEnum: null,
        Name: '',
        Path: '',
        Description: '',
        IsDeleted: false
      },
      rules: {
        Code: [{ required: true, message: '请注明', trigger: ['blur'] }],
        CriterionTypeEnum: [{ required: true, message: 'Please select', trigger: ['blur'] }],
        BusinessScenarioEnum: [{ required: true, message: 'Please select', trigger: ['blur'] }]
      },
      fileList: [],
      btnLoading: false,
      saveBtnLoading: false,
      loading: false,
      dictionaryList: {}
    }
  },
  mounted() {
    this.initForm()
  },
  methods: {
    async initForm() {
      await this.getDicData()
      if (Object.keys(this.data).length > 0) {
        if (this.data.Path) {
          this.fileList = [
            {
              name: this.data.Name,
              path: this.data.Path,
              type: this.data.Type
            }
          ]
        }
        for (const k in this.form) {
          if (this.data.hasOwnProperty(k)) {
            this.form[k] = this.data[k]
          }
        }
      }
    },
    // 获取文件类型下拉框
    getDicData() {
      this.loading = true
      getBasicDataSelects(['Common_File_ModuleType', 'Common_File_Type']).then(res => {
        this.dictionaryList = { ...res.Result }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    beforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        this.fileList = []
        return true
      } else {
        this.$message.error('必须是word/excel格式')

        return false
      }
    },
    handleUploadFile(param) {
      this.btnLoading = true
      uploadCommonDoc(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
      })
    },
    handleSave() {
      this.$refs.sysTemplateFrom.validate(valid => {
        if (!valid) return
        if (!this.form.Name) {
          this.$message.error('Please select file.')
          return
        }
        this.saveBtnLoading = true
        addOrUpdateCommonDocument(this.form).then(res => {
          this.saveBtnLoading = false
          this.$emit('closeDialog')
          this.$emit('getList')
          this.$message.success('Uploaded successfully')
        }).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(`Upload is currently limited to 1 file`)
    },
    checkFileSuffix(fileName) {
      var typeArr = ['xls', 'xlsx', 'doc', 'docx']
      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: #00d1b2;
    font-size: 13px;
  }
  .account_item_clear{
    .el-tag__close{
      display: none !important;
    }
  }
}
</style>
