<template>
  <div v-loading="loading" class="resumes-container">
    <div class="resume-content">
      <p>{{ $t('system:Resumes:title: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'">{{ $t('system:GcpCertificate:upload:Upload') }}</el-button>
          </el-upload>
        </div>
      </div>

      <p>{{ $t('system:tip:file:docx') }}</p>
    </div>
    <div class="resumeTbl">
      <el-table :data="resumeListEN" size="small">
        <el-table-column type="index" width="40" />
        <el-table-column prop="FileName" :label="$t('system:Resumes:table:Resume')" width="180" show-overflow-tooltip />
        <el-table-column prop="CreateTime" :label="$t('system:Resumes:table:Upload Time')" width="150" show-overflow-tooltip />
        <el-table-column
          prop="IsOfficial"
          :label="$t('system:Resumes:table:Official')"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.IsOfficial === true?'Yes':'No' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="Language"
          :label="$t('system:Resumes:table: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="$t('common:action:action')" width="400">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handlePreview(scope.row)">{{ $t('common:button:download') }}</el-button>
            <el-button type="text" size="small" :disabled="$route.query.ReviewStatus === '1'" @click="handleRemoveFile(scope.row)">{{ $t('common:button:delete') }}</el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.IsOfficial || $route.query.ReviewStatus === '1'"
              @click="handleSetOfiical(scope.row)"
            >{{ $t('system:Resumes:button:Set as Official') }}</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <div class="resume-content" style="margin-top:10px;">
      <p>{{ $t('system:Resumes:title:ResumeCN') }}</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'">{{ $t('system:GcpCertificate:upload:Upload') }}</el-button>
          </el-upload>
        </div>
      </div>
      <p>{{ $t('system:tip:file: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="$t('system:Resumes:table:Resume')" width="180" show-overflow-tooltip />
        <el-table-column prop="CreateTime" :label="$t('system:Resumes:table:Upload Time')" width="150" show-overflow-tooltip />
        <el-table-column
          prop="IsOfficial"
          :label="$t('system:Resumes:table:Official')"
          width="100"
        >
          <template slot-scope="scope">
            {{ scope.row.IsOfficial === true?'Yes':'No' }}
          </template>
        </el-table-column>
        <el-table-column
          prop="Language"
          :label="$t('system:Resumes:table: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="$t('common:action:action')" width="400">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handlePreview(scope.row)">{{ $t('common:button:download') }}</el-button>
            <el-button type="text" size="small" :disabled="$route.query.ReviewStatus === '1'" @click="handleRemoveFile(scope.row)">{{ $t('common:button:delete') }}</el-button>
            <el-button
              type="text"
              size="small"
              :disabled="scope.row.IsOfficial || $route.query.ReviewStatus === '1'"
              @click="handleSetOfiical(scope.row)"
            >{{ $t('system:Resumes:button: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() {
    if(!this.doctorId) return
    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.$alert(`Must be in ${this.accept} format`)
      }
    },
    async uploadFile(file, language) {
      this.isDisabled = true
      var fileName = file.name
      var files = this.resumeList
      file = await this.fileToBlob(file)
      let res = await this.OSSclient.put(`/SystemData/reviewer/Resume/${this.doctorId}/${fileName}`, file)
      if (this.repeat) {
        const index = files.findIndex((item, index) => {
          return item.FileName === fileName
        })
        files[index].Path = this.$getObjectName(res.url)
        files[index].FullPath = this.$getObjectName(res.url)
        files[index].ReUpload = true
        files[index].Language = language
      } else {
        const fileData = {
          DoctorId: this.doctorId,
          Type: 'Resume',
          Path: this.$getObjectName(res.url),
          FullPath: this.$getObjectName(res.url),
          FileName: fileName,
          Language: language
        }
        files.push(fileData)
      }
      this.saveUploadFiles(files)
    },
    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(this.OSSclientConfig.basePath + row.FullPath, '_blank')
      }
    },
    handleRemoveFile(row) {
      this.$confirm(this.$t('trials:uploadedDicoms:message:deleteMes'), {
        type: 'warning',
        distinguishCancelAndClose: true,

      }).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: this.$t('common:message:deletedSuccessfully'),
                type: 'success'
              })
            }
          })
      })
        .catch(action => {})
    },
    handleSetOfiical(row) {
      setOfficial(this.doctorId, row.Id, row.Language).then(res => {
        if (res.IsSuccess) {
          this.getResumeList()
          this.$message({
            message: 'Saved successfully!',
            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: 'Saved successfully!',
            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: #428bca;
      font-size: 14px;
    }
    .upload-content {
      float: left;
    }

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

</style>
