<template>
  <div class="agreement">
    <div class="title">{{ $t('curriculumVitae:agreement:title') }}</div>
    <div class="fileBox">
      <div class="file_title">
        {{ $t('curriculumVitae:agreement:fileTitle') }}
      </div>
      <template v-if="sowList && sowList.length > 0">
        <div class="file" v-for="item in sowList" :key="item.Id">
          <div class="name" :title="item.FileName">{{ item.FileName }}</div>
          <i
            class="el-icon-view"
            :title="$t('common:button:preview')"
            @click.stop="handlePreview3(item)"
          />
          <i
            class="el-icon-edit"
            :title="$t('common:button:edit')"
            v-if="item.IsIRUpload || isPM"
            @click="
              handleEditCol(item, 0, $t('trials:enrolledReviews:message:SOW'))
            "
          />
          <i
            class="el-icon-delete"
            v-if="item.IsIRUpload || isPM"
            :title="$t('common:button:delete')"
            @click="handleRemoveFile3(item)"
          />
        </div>
      </template>
      <div class="noData" v-else>{{ $t('curriculumVitae:noData') }}</div>
      <div class="btnBox" style="margin-top: 10px">
        <el-button
          type="primary"
          size="small"
          @click.stop="addCol(0, $t('trials:enrolledReviews:message:SOW'))"
        >
          {{ $t('curriculumVitae:agreement:btn:upload') }}
        </el-button>
        <el-button
          type="text"
          @click.stop="handleDownload('Reviewer_SOW_Template')"
        >
          {{ $t('common:button:downloadTpl') }}
        </el-button>
      </div>
      <template v-if="!isPM">
        <template v-if="CounselorFiles">
          <div class="file_title">
            {{ $t('curriculumVitae:agreement:Counselor') }}
          </div>
          <div class="file" v-for="item in CounselorFiles" :key="item.Id">
            <div class="name" :title="item.FileName">{{ item.FileName }}</div>
            <i
              class="el-icon-view"
              :title="$t('common:button:preview')"
              @click.stop="preview(item)"
            />
          </div>
        </template>
        <template v-if="ackSowList && ackSowList.length > 0">
          <div class="file_title">
            {{ $t('curriculumVitae:agreement:confirmation') }}
          </div>
          <div class="file" v-for="item in ackSowList" :key="item.Id">
            <div class="name" :title="item.FileName">{{ item.FileName }}</div>
            <i
              class="el-icon-view"
              :title="$t('common:button:preview')"
              @click.stop="handlePreview3(item)"
            />
          </div>
        </template>
      </template>
      <template v-else>
        <div class="file_title">
          {{ $t('curriculumVitae:agreement:Counselor') }}
        </div>
        <template v-if="agreementList && agreementList.length > 0">
          <div class="file" v-for="item in agreementList" :key="item.Id">
            <div class="name" :title="item.FileName">{{ item.FileName }}</div>
            <i
              class="el-icon-view"
              :title="$t('common:button:preview')"
              @click.stop="handlePreview3(item)"
            />
            <i
              class="el-icon-delete"
              :title="$t('common:button:delete')"
              @click="handleRemoveFile(item)"
            />
          </div>
        </template>
        <div class="noData" v-else>{{ $t('curriculumVitae:noData') }}</div>
        <div class="btnBox" style="margin-top: 10px">
          <div class="resume-content">
            <div class="upload-content">
              <upload-files
                ref="uploadAgreement"
                :doctor-id="reviewerId"
                type="Consultant Agreement"
                accept=".pdf"
                @getFileList="getFileList"
              />
            </div>
            <!-- <p>{{ $t('system:tip:file:pdf') }}</p> -->
          </div>
        </div>
        <div class="file_title">
          {{ $t('curriculumVitae:agreement:confirmation') }}
        </div>
        <template v-if="ackSowList && ackSowList.length > 0">
          <div class="file" v-for="item in ackSowList" :key="item.Id">
            <div class="name" :title="item.FileName">{{ item.FileName }}</div>
            <i
              class="el-icon-view"
              :title="$t('common:button:preview')"
              @click.stop="handlePreview3(item)"
            />
            <i
              class="el-icon-edit"
              :title="$t('common:button:edit')"
              @click="
                handleEditCol(item, 1, $t('trials:enrolledReviews:message:SOW'))
              "
            />
            <i
              class="el-icon-delete"
              :title="$t('common:button:delete')"
              @click="handleRemoveFile3(item)"
            />
          </div>
        </template>
        <div class="noData" v-else>{{ $t('curriculumVitae:noData') }}</div>
        <div class="btnBox" style="margin-top: 10px">
          <el-button
            type="primary"
            size="small"
            @click.stop="addCol(1, $t('trials:enrolledReviews:message:SOW'))"
          >
            {{ $t('curriculumVitae:agreement:btn:uploadconfirmation') }}
          </el-button>
        </div>
      </template>
    </div>
    <BaseModel :config="model_cfg">
      <template slot="dialog-body">
        <el-form
          ref="DictionaryTypeConfigForm"
          :model="form"
          :rules="rules"
          label-width="120px"
          size="small"
        >
          <el-form-item
            :label="$t('system:Agreements:label:Criterion Type')"
            prop="CriterionType"
          >
            <el-select v-model="form.CriterionType">
              <el-option
                v-for="item of $d.CriterionType"
                :key="item.id"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            :label="$t('system:Agreements:label:File')"
            prop="FilePath"
          >
            <el-upload
              class="upload-demo"
              action
              :before-upload="beforeUpload"
              :http-request="handleUploadFile"
              :on-preview="handlePreview2"
              :on-remove="handleRemoveFile2"
              :show-file-list="true"
              :limit="1"
              :accept="accept"
              :file-list="fileList"
            >
              <el-button
                size="small"
                type="primary"
                :disabled="fileList.length > 0"
                >{{ $t('common:button:upload') }}</el-button
              >
              <span>{{ $t('system:tip:file:pdf') }}</span>
            </el-upload>
          </el-form-item>
          <el-form-item :label="$t('system:Agreements:label:Remark')">
            <el-input
              v-model="form.Remark"
              type="textarea"
              :autosize="{ minRows: 2, maxRows: 4 }"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('system:Agreements:label:Is Enable')">
            <el-switch
              v-model="form.IsEnable"
              :active-value="true"
              :inactive-value="false"
            />
          </el-form-item>
        </el-form>
      </template>
      <template slot="dialog-footer">
        <el-button
          :disabled="btnLoading"
          size="small"
          type="primary"
          @click="handleCancle"
        >
          {{ $t('common:button:cancel') }}
        </el-button>
        <el-button
          size="small"
          type="primary"
          :loading="btnLoading"
          @click="handleSave"
        >
          {{ $t('common:button:save') }}
        </el-button>
      </template>
    </BaseModel>
  </div>
</template>
<script>
import { DownloadCommonDoc } from '@/api/dictionary'
import {
  addDoctorCriterionFile,
  deleteDoctorCriterionFile,
  getDoctorCriterionFile,
} from '@/api/reviewers'
import BaseModel from '@/components/BaseModel'
import UploadFiles from '@/components/UploadFiles'
export default {
  name: 'agreement',
  components: {
    BaseModel,
    UploadFiles,
  },
  props: {
    DATA: {
      type: Array,
      default: () => {
        return []
      },
    },
    reviewerId: {
      type: String,
      default: '',
    },
    isEN: {
      type: Boolean,
      default: false,
    },
    isPM: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      faccept: ['.pdf'],
      loading: false,
      agreementList: [],
      sowList: [],
      ackSowList: [],
      loading: false,
      isOpen: false,
      btnLoading: false,
      model_cfg: {
        visible: false,
        showClose: true,
        width: '600px',
        title: '',
        appendToBody: true,
      },
      form: {
        Remark: null,
        FileType: null,
        FileName: null,
        FilePath: null,
        DoctorId: null,
        CriterionType: null,
        IsEnable: false,
      },
      rules: {
        CriterionType: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur'],
          },
        ],
        FilePath: [
          {
            required: true,
            message: this.$t('common:ruleMessage:specify'),
            trigger: ['blur'],
          },
        ],
      },
      fileList: [],
      accept: '.pdf',
    }
  },
  watch: {
    reviewerId() {
      if (this.reviewerId) {
        this.initSowList()
      }
    },
  },
  computed: {
    CounselorFiles() {
      if (!this.DATA || this.DATA.length <= 0) return false
      return this.DATA.filter(
        (item) => item.Type && item.Type.indexOf('Consultant Agreement') >= 0
      )
    },
  },
  methods: {
    handleRemoveFile(row) {
      this.$refs.uploadAgreement.handleDeleteFile(row)
    },
    getFileList(fileList) {
      this.agreementList = fileList
    },
    preview(row) {
      this.$preview({
        path: row.Path || row.FullPath,
        type: 'pdf',
        title: row.FileName,
      })
    },
    handleDownload(code) {
      this.loading = true
      DownloadCommonDoc(code)
        .then((data) => {
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleEditCol(row, fileType, title) {
      this.model_cfg.visible = true
      this.form = Object.assign({}, row)
      this.fileList[0] = { name: row.FileName, path: row.FilePath }
      this.form.FileType = fileType
      this.model_cfg.title = title
    },
    handleRemoveFile3(row) {
      this.$confirm(
        this.$t('dictionary:attachment:export:confirm:delete')
      ).then(() => {
        deleteDoctorCriterionFile({
          Id: row.Id,
        }).then(() => {
          this.initSowList()
          this.$message.success(this.$t('common:message:deletedSuccessfully'))
        })
      })
    },
    handleRemoveFile2() {
      this.form.FileName = null
      this.form.FilePath = null
      this.fileList = []
    },
    beforeUpload(row) {
      if (this.fileList.length > 0) {
        // this.$alert('最多只能传一个附件')
        this.$alert(this.$t('upload:rule:maxFile1'))
        return
      }
      if (!this.checkFileSuffix(row.name)) {
        this.$message.warning(this.$t('upload:rule:MUSTPDF'))
        return false
      }
    },
    checkFileSuffix(fileName) {
      var index = fileName.lastIndexOf('.')
      var suffix = fileName.substring(index + 1, fileName.length)
      return (
        this.accept.toLocaleLowerCase().search(suffix.toLocaleLowerCase()) === 1
      )
    },
    handlePreview3(row) {
      return this.$preview({
        path: row.FilePath || row.Path || row.FullPath,
        type: 'pdf',
        title: row.FileName,
      })
      if (row.FilePath) {
        window.open(this.OSSclientConfig.basePath + row.FilePath, '_blank')
      }
    },
    handlePreview2(row, r2) {
      return this.$preview({
        path: row.FullPath,
        type: 'pdf',
        title: row.FileName,
      })
      if (row.fullPath) {
        window.open(this.OSSclientConfig.basePath + row.fullPath, '_blank')
      }
    },
    async handleUploadFile(param) {
      this.btnLoading = true
      var fileName = param.file.name
      let file = await this.fileToBlob(param.file)
      let res = await this.OSSclient.put(
        `/SystemData/reviewer/${
          this.form.FileType === 0 ? '既往阅片情况声明' : '入项资格确认书'
        }/${this.reviewerId}/${fileName}`,
        file
      )
      this.form.FileName = param.file.name
      this.form.FilePath = this.$getObjectName(res.url)
      this.fileList[0] = {
        name: this.$getObjectName(res.url),
        path: this.$getObjectName(res.url),
        fullPath: this.$getObjectName(res.url),
        url: res.url,
      }
      this.btnLoading = false
    },
    handleCancle() {
      this.model_cfg.visible = false
    },
    handleSave() {
      this.$refs['DictionaryTypeConfigForm'].validate((valid) => {
        if (!valid) return
        this.form.DoctorId = this.reviewerId
        this.form.CriterionName = this.$fd(
          'CriterionType',
          this.form.CriterionType
        )
        if (!this.isPM) {
          this.form.IsIRUpload = true
        }
        addDoctorCriterionFile(this.form).then((res) => {
          this.$message.success(this.$t('common:message:addedSuccessfully'))
          this.initSowList()
          this.handleCancle()
        })
      })
    },
    addCol(fileType, title) {
      this.model_cfg.visible = true
      this.form = {
        Remark: null,
        FileType: null,
        FileName: null,
        FilePath: null,
        DoctorId: null,
        CriterionType: null,
        IsEnable: false,
      }
      this.handleRemoveFile2()
      this.form.FileType = fileType
      this.model_cfg.title = title
    },
    initSowList() {
      if (!this.reviewerId) return
      getDoctorCriterionFile({
        fileType: 0,
        DoctorId: this.reviewerId,
      }).then((res) => {
        this.sowList = res.Result
      })
      getDoctorCriterionFile({
        fileType: 1,
        DoctorId: this.reviewerId,
      }).then((res) => {
        this.ackSowList = res.Result
      })
    },
  },
}
</script>
<style lang="scss" scoped>
</style>