<template>
  <div v-loading="loading" class="resumes-container">
    <div class="resume-content">
      <p>Resume</p>
      <div class="upload-content">
        <!-- <upload-files ref="uploadResume" :doctor-id="doctorId" :data-list="resumeList" :language="2" btn-name="Upload(English)" type="Resume" accept=".doc, .docx" @getFileList="getFileList" /> -->
        <div class="uploadFile-container">
          <el-upload
            class="upload-demo"
            :data="{language:2}"
            action
            :show-file-list="false"
            :http-request="handleUploadFile"
            :file-list="resumeList"
            accept=".doc,.docx"
          >
            <el-button size="small" type="primary" :disabled="isDisabled || $route.query.ReviewStatus === '1'">Upload</el-button>
          </el-upload>
        </div>
      </div>

      <p>(must be in doc,docx format)</p>
    </div>
    <div class="resumeTbl">
      <el-table :data="resumeListEN" size="small">
        <el-table-column type="index" width="40" />
        <el-table-column prop="FileName" label="Resume" width="180" show-overflow-tooltip />
        <el-table-column prop="CreateTime" label="Upload Time" width="150" show-overflow-tooltip />
        <el-table-column
          prop="IsOfficial"
          label="Official"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.IsOfficial === true?'Yes':'No' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="Language"
          label="Language"
          width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.Language===1?'中文':'English' }}
            <!-- <el-button size="small" type="text" @click="handleLanguageClick(scope.row)">{{ scope.row.Language===1?'CH':scope.row.Language===2?'EN':'Setting' }}</el-button> -->
          </template>
        </el-table-column>
        <el-table-column label="Action" width="400">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handlePreview(scope.row)">Download</el-button>
            <el-button type="text" size="small" :disabled="$route.query.ReviewStatus === '1'" @click="handleRemoveFile(scope.row)">Delete</el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.IsOfficial || $route.query.ReviewStatus === '1'"
              @click="handleSetOfiical(scope.row)"
            >Set as Official</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="resume-content" style="margin-top:10px;">
      <p>中文简历</p>
      <div class="upload-content">
        <div class="uploadFile-container">
          <el-upload
            :data="{language:1}"
            class="upload-demo"
            action
            :show-file-list="false"
            :http-request="handleUploadFile"
            :file-list="resumeList"
            accept=".doc, .docx"
          >
            <el-button size="small" type="primary" :disabled="isDisabled || $route.query.ReviewStatus === '1'">上传</el-button>
          </el-upload>
        </div>
      </div>
      <p>(必须是 doc,docx 格式)</p>
    </div>
    <div class="resumeTbl">
      <el-table :data="resumeListCN" size="small">
        <el-table-column type="index" width="40" />
        <el-table-column prop="FileName" label="Resume" width="180" show-overflow-tooltip />
        <el-table-column prop="CreateTime" label="Upload Time" width="150" show-overflow-tooltip />
        <el-table-column
          prop="IsOfficial"
          label="Official"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.IsOfficial === true?'Yes':'No' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="Language"
          label="Language"
          width="100"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.Language===1?'中文':'English' }}
            <!-- <el-button size="small" type="text" @click="handleLanguageClick(scope.row)">{{ scope.row.Language===1?'CH':scope.row.Language===2?'EN':'Setting' }}</el-button> -->
          </template>
        </el-table-column>
        <el-table-column label="Action" width="400">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handlePreview(scope.row)">Download</el-button>
            <el-button type="text" size="small" :disabled="$route.query.ReviewStatus === '1'" @click="handleRemoveFile(scope.row)">Delete</el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.IsOfficial"
              @click="handleSetOfiical(scope.row)"
            >Set as Official</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      :title="$t('trials:seletctedReviews:title:language')"
      :visible.sync="dialogVisible"
      width="30%"
      size="small"
    >
      <span>Language: </span>
      <el-radio-group :disabled="$route.query.ReviewStatus === '1'" v-model="language">
        <el-radio :label="2">English</el-radio>
        <el-radio :label="1">中文</el-radio>
      </el-radio-group>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" :disabled="$route.query.ReviewStatus === '1'" @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" :disabled="$route.query.ReviewStatus === '1'" size="small" @click="setResumeLanguage">Ok</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { getAttachmentByType, uploadFile, saveAttachments, deleteAttachment, setOfficial, setLanguageForResume } from '@/api/attachment'
export default {
  props: {
    id: {
      type: String,
      default() {
        return ''
      }
    }
  },
  data() {
    return {
      doctorId: this.$route.query.Id,
      resumeList: [],
      resumeListEN: [],
      resumeListCN: [],
      language: 0,
      dialogVisible: false,
      currentRow: {},
      repeat: false,
      isDisabled: false,
      loading: false
    }
  },
  created() {
    this.getResumeList()
  },
  methods: {
    getResumeList() {
      this.loading = true
      getAttachmentByType(this.doctorId, 'Resume').then(res => {
        if (res.IsSuccess) {
          if (res.Result.length > 0) {
            this.resumeList = res.Result
            this.filterByLanguage()
          }
        }
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    handleUploadFile(param) {
      this.repeat = false
      // const fileName = param.file.name.substring(0, param.file.name.lastIndexOf('.'))
      // const extension = param.file.name.substring(param.file.name.lastIndexOf('.'))
      // 检测文件后缀名
      if (this.checkFileSuffix(param.file.name) > -1) {
        // 检测是否有重名文件
        const isRepeat = this.resumeList.some(item => item.FileName === param.file.name)
        if (isRepeat) {
          this.$confirm('Override the existing resume?', {
            type: 'warning',
            distinguishCancelAndClose: true,
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel'
          })
            .then(() => {
              // 重名覆盖
              this.repeat = true
              this.uploadFile(param.file, param.data.language)
            })
            .catch(action => {})
        } else {
          this.uploadFile(param.file, param.data.language)
        }
      } else {
        this.$message.error(`Must be in ${this.accept} format`)
      }
    },
    uploadFile(file, language) {
      this.isDisabled = true
      var files = this.resumeList
      uploadFile(file, 'Resume', this.doctorId).then(res => {
        if (this.repeat) {
          const index = files.findIndex((item, index) => {
            return item.FileName === file.name
          })
          files[index].Path = res.Result.FilePath
          files[index].FullPath = res.Result.FullFilePath
          files[index].ReUpload = true
          files[index].Language = language
        } else {
          const fileData = {
            DoctorId: this.doctorId,
            Type: 'Resume',
            Path: res.Result.FilePath,
            FullPath: res.Result.FullFilePath,
            FileName: file.name,
            Language: language
          }
          files.push(fileData)
        }
        this.saveUploadFiles(files)
      })
        .catch(() => {
          this.isDisabled = false
        })
    },
    saveUploadFiles(files) {
      saveAttachments(files).then(res => {
        this.resumeList = res.Result
        this.filterByLanguage()
        this.isDisabled = false
        this.$message.success('Uploaded successfully')
      }).catch(() => {
        this.isDisabled = false
      })
    },
    filterByLanguage() {
      this.resumeListEN = []
      this.resumeListCN = []
      this.resumeList.map(resume => {
        if (resume.Language === 2) {
          this.resumeListEN.push(resume)
        } else if (resume.Language === 1) {
          this.resumeListCN.push(resume)
        }
      })
    },
    checkFileSuffix(fileName) {
      const accept = '.doc, .docx'
      var index = fileName.lastIndexOf('.')
      var suffix = fileName.substring(index + 1, fileName.length).toLocaleLowerCase()
      return accept.search(suffix)
    },
    handlePreview(row) {
      if (row.FullPath) {
        window.open(row.FullPath, '_blank')
      }
    },
    handleRemoveFile(row) {
      this.$confirm('Sure to delete?', {
        type: 'warning',
        distinguishCancelAndClose: true,
        confirmButtonText: 'Ok',
        cancelButtonText: 'Cancel'
      }).then(() => {
        deleteAttachment(row.Id, row.Path)
          .then(res => {
            if (res.IsSuccess) {
              this.resumeList.splice(this.resumeList.findIndex(item => item.Id === row.Id), 1)
              this.filterByLanguage()
              this.$message({
                message: 'Deleted successfully!',
                type: 'success'
              })
            }
          })
      })
        .catch(action => {})
    },
    handleSetOfiical(row) {
      setOfficial(this.doctorId, row.Id, row.Language).then(res => {
        if (res.IsSuccess) {
          this.getResumeList()
          this.$message({
            message: this.$t('common:message:savedSuccessfully'),
            type: 'success'
          })
        }
      })
    },
    handleLanguageClick(row) {
      this.dialogVisible = true
      this.language = row.Language
      this.currentRow = row
    },
    setResumeLanguage() {
      setLanguageForResume(this.doctorId, this.currentRow.Id, this.language).then(res => {
        if (res.IsSuccess) {
          this.dialogVisible = false
          this.getResumeList()
          this.$message({
            message: this.$t('common:message:savedSuccessfully'),
            type: 'success'
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
.resumes-container{
  .resume-content{
    p {
      float: left;
      font-size: 13px;
      line-height: 30px;
      margin: 0 5px;
    }
    .uploadFile-container .el-upload--text {
      border: none;
      // width: 80px;
      // height: 30px;
    }
    .uploadFile-container .el-input--small {
      margin-bottom: 5px;
    }
    .uploadFile-container .el-icon-circle-check {
      color: #00d1b2;
      font-size: 14px;
    }
    .upload-content {
      float: left;
    }

  }
  .el-dialog__body{
    padding: 10px 20px;
  }
}

</style>
