<template>
  <box-content>
    <div class="title">
      {{ TITLE }}
    </div>
    <!-- 搜索框 -->
    <div class="search" style="position: relative">
      <el-form :inline="true" class="base-search-form">
        <!--文件类型-->
        <el-form-item
          :label="$t('trials:trialDocument:certificate:search:fileType')"
        >
          <el-select
            v-model="searchData.Type"
            style="width: 100px"
            placeholder=""
            clearable
          >
            <el-option
              v-for="item in $d.CertificateFileType"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!--文件名称-->
        <el-form-item
          :label="$t('trials:trialDocument:certificate:search:name')"
        >
          <el-input
            v-model="searchData.FileName"
            style="width: 100px"
            clearable
          />
        </el-form-item>
        <!--阅片人-->
        <el-form-item
          :label="$t('trials:trialDocument:certificate:search:viewer')"
        >
          <el-select
            v-model="searchData.DoctorId"
            style="width: 100px"
            placeholder=""
            clearable
          >
            <el-option
              v-for="item in doctorList"
              :key="item.Id"
              :label="item.FullName"
              :value="item.Id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label="
            $t('trials:trialDocument:certificate:search:isAuthorizedView')
          "
          v-if="isManage && !viewStatus"
        >
          <el-select
            v-if="!viewStatus"
            v-model="searchData.IsAuthorizedView"
            style="width: 100px"
            placeholder=""
            clearable
          >
            <el-option
              v-for="item in $d.YesOrNo"
              :key="item.id"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleSearch">
            {{ $t('common:button:search') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-refresh-left"
            @click="handleReset"
          >
            {{ $t('common:button:reset') }}
          </el-button>
        </el-form-item>
        <el-form-item v-if="isManage && !viewStatus">
          <el-button
            type="primary"
            :disabled="selectTable.length <= 0"
            v-if="hasAccredit && isManage && !viewStatus"
            @click.stop="auth"
          >
            {{ $t('trials:trialDocument:certificate:button:accredit') }}
          </el-button>
          <el-button
            type="primary"
            v-if="hasAdd && isManage && !viewStatus"
            @click.stop="handleAdd"
          >
            {{ $t('trials:trialDocument:certificate:button:add') }}
          </el-button>
          <el-button
            type="primary"
            v-if="hasEdit && isManage && !viewStatus"
            @click.stop="openFile(false)"
          >
            {{ $t('trials:trialDocument:certificate:button:uploadFile') }}
          </el-button>
          <el-button
            type="primary"
            v-if="hasEdit && isManage && !viewStatus"
            @click.stop="openFile(true)"
          >
            {{ $t('trials:trialDocument:certificate:button:uploadFolder') }}
          </el-button>
          <el-button
            type="primary"
            icon="el-icon-bottom"
            :disabled="selectTable.length <= 0"
            v-if="hasDownLoad && isManage && !viewStatus"
            @click.stop="downLoad"
          >
            {{ $t('trials:trialDocument:certificate:button:downLoadFile') }}
          </el-button>
          <el-button
            type="primary"
            :disabled="selectTable.length <= 0"
            v-if="hasDel && isManage && !viewStatus"
            @click.stop="handleDel"
          >
            {{ $t('trials:trialDocument:certificate:button:del') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      v-loading="loading"
      v-adaptive="{ bottomOffset: 75 }"
      :data="list"
      stripe
      height="100"
      style="width: 100%"
      @sort-change="handleSortByColumn"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
        v-if="isManage && !viewStatus"
      />
      <el-table-column type="index" v-else />

      <!--文件类型-->
      <el-table-column
        prop="type"
        :label="$t('trials:trialDocument:certificate:table:fileType')"
        show-overflow-tooltip
        sortable="custom"
      >
        <template slot-scope="scope">
          <span>{{ $fd('CertificateFileType', scope.row.Type) }}</span>
        </template>
      </el-table-column>

      <!--文件名称-->
      <el-table-column
        prop="FileName"
        :label="$t('trials:trialDocument:certificate:table:FileName')"
        show-overflow-tooltip
        sortable="custom"
      />
      <!--阅片人-->
      <el-table-column
        prop="UserName"
        :label="$t('trials:trialDocument:certificate:table:viewer')"
        show-overflow-tooltip
        sortable="custom"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.UserName }} ({{ scope.row.FullName }})</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="IsAuthorizedView"
        :label="$t('trials:trialDocument:certificate:table:isAuthorizedView')"
        show-overflow-tooltip
        sortable="custom"
        v-if="isManage && !viewStatus"
      >
        <template slot-scope="scope">
          <el-switch
            :disabled="!scope.row.DoctorId"
            v-if="isManage && !viewStatus && hasEdit"
            v-model="scope.row.IsAuthorizedView"
            @change="(val) => auth(false, scope.row, val)"
            :active-value="true"
            :inactive-value="false"
            :active-text="$fd('YesOrNo', true)"
            :inactive-text="$fd('YesOrNo', false)"
          >
          </el-switch>
          <span v-else>{{ $fd('YesOrNo', scope.row.IsAuthorizedView) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="UpdateTime"
        :label="$t('trials:trialDocument:certificate:table:updateTime')"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        prop="CreateTime"
        :label="$t('trials:trialDocument:certificate:table:createTime')"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column :label="$t('common:action:action')" width="200">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-view"
            :title="$t('common:button:view')"
            circle
            @click.stop="preview(scope.row)"
          />
          <el-button
            v-if="hasEdit && isManage && !viewStatus"
            icon="el-icon-edit-outline"
            :title="$t('common:button:edit')"
            circle
            @click.stop="handleEdit(scope.row)"
          />
          <el-button
            v-if="hasDownLoad && isManage && !viewStatus"
            icon="el-icon-download"
            :title="$t('trials:trialDocument:certificate:button:downLoadFile')"
            circle
            @click.stop="downLoad(scope.row, 'file')"
          />
          <el-button
            v-if="hasDel && isManage && !viewStatus"
            icon="el-icon-delete"
            :title="$t('trials:trialDocument:certificate:button:delete')"
            circle
            @click.stop="handleDel(scope.row, false)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      class="page"
      :total="total"
      :page.sync="searchData.PageIndex"
      :limit.sync="searchData.PageSize"
      @pagination="getList"
    />
    <upload-files
      :config="config"
      :faccept="faccept"
      :uploadPath="uploadPath"
      :limitLength="limitLength"
      v-if="config.visible"
      @close="close"
      @uplaodFile="uplaodFile"
    />
    <certificate-form
      :ArchiveTypeEnum="ArchiveTypeEnum"
      :config="update_config"
      :data="selectData"
      :doctorList="doctorList"
      v-if="update_config.visible"
      @close="updateClose"
      @getList="getList"
    />
  </box-content>
</template>
<script>
import {
  getTrialAttachments,
  setAuthorizedViewC,
  saveTrialAttachments,
  getTrialDoctorListC,
  deleteAttachment,
} from '@/api/dictionary'
import { downLoadFile } from '@/utils/stream.js'
import { deepClone } from '@/utils/index.js'
import Pagination from '@/components/Pagination'
import BoxContent from '@/components/BoxContent'
import uploadFiles from '../../uploadFiles.vue'
import certificateForm from './form.vue'
const searchDataDefault = () => {
  return {
    IsAuthorizedView: null,
    FileName: null,
    DoctorId: null,
    Type: null,
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: 'UserName',
  }
}
export default {
  name: 'certificate',
  components: { BoxContent, Pagination, uploadFiles, certificateForm },
  props: {
    viewStatus: {
      type: Boolean,
      default: true,
    },
    ArchiveTypeEnum: {
      type: Number,
      default: 0,
    },
    Id: {
      type: String,
      default: '',
    },
    rowData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      selectTable: [],
      config: {
        visible: false,
        showClose: true,
        width: '800px',
        title: '',
        appendToBody: false,
        isFolder: false,
      },
      selectData: {},
      uploadPath: null,
      faccept: ['.pdf'],
      limitLength: 0,

      update_config: {
        visible: false,
        showClose: true,
        width: '600px',
        title: '',
        appendToBody: false,
        status: 'add',
        upload: null,
      },
      doctorList: [],
    }
  },
  methods: {
    // 新增列表数据
    async uplaodFile(list) {
      console.log(list, 'list')
      try {
        if (!list || list.length <= 0) return false
        let arr = []
        list.forEach((item) => {
          let obj = {
            TrialId: this.$route.query.trialId,
            FileName: item.FileName,
            Path: item.FilePath,
            FullPath: item.FilePath,
            type: '',
            DoctorId: null,
          }
          arr.push(obj)
        })
        this.loading = true
        let res = await saveTrialAttachments(arr)
        this.loading = false
        if (res.IsSuccess) {
          this.getList()
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 新增
    handleAdd() {
      this.selectData = {}
      this.update_config.title = `${this.$t(
        'trials:trialDocument:certificate:form:title:add'
      )}
          -
      ${this.isEN ? this.rowData.Name : this.rowData.NameCN}`
      this.update_config.status = 'add'
      this.update_config.upload = null
      this.update_config.visible = true
    },
    // 编辑
    handleEdit(row) {
      this.selectData = deepClone(row)
      this.update_config.title = `${this.$t(
        'trials:trialDocument:certificate:form:title:edit'
      )}
          -
      ${this.isEN ? this.rowData.Name : this.rowData.NameCN}`
      this.update_config.status = 'edit'
      this.update_config.upload = null
      this.update_config.visible = true
    },
    // 下载
    async downLoad(row, type = 'zip') {
      try {
        if (type === 'file') {
          return await downLoadFile(
            this.OSSclientConfig.basePath + row.Path,
            row.FileName
          )
        }
        let { files, name } = this.formatDownloadFile()
        let res = await downLoadFile(files, name, type)
        // if (res && this.downloadId) {
        //   this.downloadImageSuccess()
        // }
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化下载文件路径
    formatDownloadFile() {
      let files = [],
        name = `${this.TITLE}_${new Date().getTime()}.zip`

      this.selectTable.forEach((item) => {
        let obj = {
          name: `${item.UserName} (${item.LastName}_${
            item.FirstName
          })/${this.$fd(
            'CertificateFileType',
            item.Type
          )}_${item.FileName.substring(
            0,
            item.FileName.lastIndexOf('.')
          )}__${new Date().getTime()}${item.FileName.substring(
            item.FileName.lastIndexOf('.')
          ).toLocaleLowerCase()}`,
          url: this.OSSclientConfig.basePath + item.Path,
        }
        files.push(obj)
      })

      return { files, name }
    },
    // 授权
    async auth(isArray = true, row, IsAuthorizedView) {
      try {
        let data = {}
        if (isArray) {
          let flag = this.selectTable.some((item) => !item.DoctorId)
          if (flag)
            return this.$message.warning(
              this.$t('trials:trialDocument:certificate:message:hsaNoDoctorId')
            )
          data = {
            Ids: this.selectTable.map((item) => item.Id),
            IsAuthorizedView: true,
          }
        } else {
          data = {
            Ids: [row.Id],
            IsAuthorizedView,
          }
        }
        this.loading = true
        let res = await setAuthorizedViewC(data)
        this.loading = false
        if (res.IsSuccess) {
          this.$t('trials:trialDocument:certificate:message:authSuccessfully')
          if (isArray) {
            this.getList()
          }
        }
      } catch (err) {
        this.loading = false
        if (!isArray) {
          row.IsAuthorizedView = !row.IsAuthorizedView
        }
        console.log(err)
      }
    },
    // 删除列表数据
    handleDel(row, isArray = true) {
      this.$confirm(
        this.$t('trials:trialDocument:certificate:message:deleteMessage'),
        {
          type: 'warning',
          distinguishCancelAndClose: true,
        }
      )
        .then(() => {
          this.loading = true
          let data = {}
          if (isArray) {
            data.Ids = this.selectTable.map((item) => item.Id)
          } else {
            data.Ids = [row.Id]
          }
          deleteAttachment(data)
            .then((res) => {
              this.loading = false
              if (res.IsSuccess) {
                this.getList()
                this.$message.success(
                  this.$t('common:message:deletedSuccessfully')
                )
              }
            })
            .catch((err) => {
              this.loading = false
              console.log(err)
            })
        })
        .catch((err) => {
          this.loading = false
          console.log(err)
        })
    },
    // 获取医生列表
    async getTrialDoctorList() {
      try {
        let data = {
          TrialId: this.$route.query.trialId,
        }
        let res = await getTrialDoctorListC(data)
        if (res.IsSuccess) {
          this.doctorList = res.Result
        }
      } catch (err) {
        console.log(err)
      }
    },
    async getList() {
      try {
        if (!this.Id) return false
        // this.searchData.TrialFileTypeId = this.Id
        this.searchData.TrialId = this.$route.query.trialId
        if (this.viewStatus) {
          this.searchData.IsAuthorizedView = true
        }
        this.loading = true
        let res = await getTrialAttachments(this.searchData)
        this.loading = false
        if (res.IsSuccess) {
          this.list = res.Result.CurrentPageData
          this.total = res.Result.TotalCount
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
    },
    // 排序
    handleSortByColumn(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.searchData.PageIndex = 1
      this.getList()
    },
    handleSelectionChange(val) {
      this.selectTable = val
    },
    // 预览
    preview(row) {
      if (!row.Path) return false
      this.$preview({
        path: row.FilePath || row.fullPath || row.Path,
        type: 'pdf',
        title: row.FileName,
      })
    },
    close() {
      this.config.visible = false
      // this.selectData = {}
      // this.selectKey = null
      this.faccept = ['.pdf']
      this.limitLength = 0
    },
    updateClose() {
      this.update_config.visible = false
    },
    fileSizeFormatter(size) {
      if (!size) return
      return (size / Math.pow(1024, 2)).toFixed(3) + 'MB'
    },
    openFile(isFolder = false) {
      this.selectData = {}
      this.faccept = ['.pdf']
      this.limitLength = 0
      this.config.title = this.$t(
        'trials:trialDocument:certificate:form:title:uploadFile'
      )
      this.config.visible = true
      this.config.isFolder = isFolder
    },
  },
  watch: {
    Id: {
      handler() {
        this.getList()
      },
      immediate: true,
    },
  },
  created() {
    let typeArr = ['', 'Report', 'Doc', 'Record', 'Reviewer', 'Template']
    let types = typeArr[this.ArchiveTypeEnum]
    this.uploadPath = `/${this.$route.query.trialId}/Document/${types}`
    this.getTrialDoctorList()
  },
  computed: {
    isEN() {
      return this.$i18n.locale !== 'zh'
    },
    isInspect() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:inspect',
      ])
    },
    isManage() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:manage',
      ])
    },
    hasAdd() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:add',
      ])
    },
    hasEdit() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:edit',
      ])
    },
    hasDel() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:del',
      ])
    },
    hasDownLoad() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:downLoad',
      ])
    },
    hasAccredit() {
      return this.hasPermi([
        'trials:trials-panel:trial-summary:trial-document:accredit',
      ])
    },
    TITLE() {
      return `${this.$fd('ArchiveType', this.ArchiveTypeEnum)} — ${
        this.isEN ? this.rowData.Name : this.rowData.NameCN
      }`
    },
  },
}
</script>
  <style lang="scss" scoped>
.title {
  line-height: 40px;
  font-weight: bold;
  margin-bottom: 10px;
}
.fileName {
  display: inline-block;
  max-width: calc(100% - 60px);
  white-space: nowrap; /* 文本不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis;
}
.fileBtnBox {
  display: inline-block;
  width: 50px;
  i {
    cursor: pointer;
    color: #409eff;
    margin-right: 3px;
    &:last-child {
      margin: 0;
    }
  }
}
</style>