<template>
  <div class="curriculum">
    <div class="title">{{ $t('curriculumVitae:curriculum:title') }}</div>
    <div class="fileBox">
      <div class="file_title">
        {{ $t('curriculumVitae:curriculum:fileTitle:CN') }}
      </div>
      <template v-if="resumeListCN.length > 0">
        <div class="file" v-for="item in resumeListCN" :key="item.Id">
          <div class="name" :title="item.FileName">{{ item.FileName }}</div>
          <i
            class="el-icon-download"
            :title="$t('common:button:download')"
            @click.stop="handlePreview(item)"
          />
          <i
            class="el-icon-delete"
            :title="$t('common:button:delete')"
            @click.stop="handleRemoveFile(item)"
          />
          <i
            :class="{ 'el-icon-circle-check': true, disable: item.IsOfficial }"
            :title="$t('common:button:default')"
            @click.stop="handleSetOfiical(item)"
          />
        </div>
      </template>
      <div class="noData" v-else>{{ $t('curriculumVitae:noData') }}</div>
      <div class="file_title">
        {{ $t('curriculumVitae:curriculum:fileTitle:EN') }}
      </div>
      <template v-if="resumeListEN.length > 0">
        <div class="file" v-for="item in resumeListEN" :key="item.FileName">
          <div class="name" :title="item.FileName">{{ item.FileName }}</div>
          <i
            class="el-icon-download"
            :title="$t('common:button:download')"
            @click.stop="handlePreview(item)"
          />
          <i
            class="el-icon-delete"
            :title="$t('common:button:delete')"
            @click.stop="handleRemoveFile(item)"
          />
        </div>
      </template>
      <div class="noData" v-else>{{ $t('curriculumVitae:noData') }}</div>
      <div class="btnBox" style="margin-top: 20px">
        <div class="uploadFile-container" style="margin-right: 10px">
          <el-upload
            class="upload-demo"
            :data="{ language: 1 }"
            action
            :show-file-list="false"
            :http-request="handleUploadFile"
            :file-list="resumeList"
            accept=".doc,.docx"
          >
            <el-button size="small" type="primary">
              {{ $t('curriculumVitae:curriculum:btn:uploadCN') }}
            </el-button>
          </el-upload>
        </div>
        <!-- <el-button
          type="text"
          @click.stop="handleDownload('Reviewer_resume_Template')"
        >
          {{ $t('common:button:downloadTpl') }}
        </el-button> -->
      </div>
      <div class="btnBox">
        <div class="uploadFile-container" style="margin-right: 10px">
          <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">
              {{ $t('curriculumVitae:curriculum:btn:uploadEN') }}
            </el-button>
          </el-upload>
        </div>
        <!-- <el-button
          type="text"
          @click.stop="handleDownload('Reviewer_resume_Template')"
        >
          {{ $t('common:button:downloadTpl') }}
        </el-button> -->
      </div>
    </div>
  </div>
</template>
<script>
import {
  getAttachmentByType,
  saveAttachments,
  deleteAttachment,
  setOfficial,
  setLanguageForResume,
} from '@/api/attachment'
import { DownloadCommonDoc } from '@/api/dictionary'
export default {
  name: 'curriculum',
  props: {
    reviewerId: {
      type: String,
      default: '',
    },
    isEN: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      resumeList: [],
      resumeListEN: [],
      resumeListCN: [],
      language: 0,
      dialogVisible: false,
      currentRow: {},
      repeat: false,
      isDisabled: false,
    }
  },
  watch: {
    reviewerId() {
      if (this.reviewerId) {
        this.getResumeList()
      }
    },
  },
  methods: {
    handleDownload(code) {
      this.loading = true
      DownloadCommonDoc(code)
        .then((data) => {
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    getResumeList() {
      this.loading = true
      getAttachmentByType(this.reviewerId, '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(
            this.$t('curriculumVitae:resume:message:existingResume'),
            {
              type: 'warning',
              distinguishCancelAndClose: true,
            }
          )
            .then(() => {
              // 重名覆盖
              this.repeat = true
              this.uploadFile(param.file, param.data.language)
            })
            .catch((action) => {})
        } else {
          this.uploadFile(param.file, param.data.language)
        }
      } else {
        this.$alert(this.$t('upload:rule:MUSTPDF'))
      }
    },
    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.reviewerId}/${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.reviewerId,
          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(
            this.$t('trials:uploadDicomList:table:Uploaded')
          )
        })
        .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) {
      if (row.IsOfficial) return false
      setOfficial(this.reviewerId, 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.reviewerId,
        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" scoped>
.file {
  width: 100%;
  display: flex;
  margin-bottom: 10px;
  .name {
    width: 70%;
    white-space: nowrap; /* 文本不会换行，会在同一行内继续，直到遇到<br>标签为止 */
    text-overflow: ellipsis; /* 当文本溢出包含它的容器时，显示省略号(...)来表示被截断的文本 */
    overflow: hidden; /* 隐藏溢出容器的文本 */
  }
  i {
    cursor: pointer;
    margin: 3px;
    color: #409eff;
  }
}
</style>