<template>
  <box-content>
    <div class="title">
      {{ TITLE }}
    </div>
    <el-form :inline="true" class="base-search-form topForm">
      <el-form-item :label="$t('trials:trialDocument:fileRecord:form:isConfirmRecord')"
        v-if="isManage && hasEdit && !viewStatus">
        <el-radio-group v-model="DATA.IsConfirmRecord" :disabled="rowBtnStatus === 'edit'">
          <el-radio :label="item.value" v-for="item in $d.YesOrNo" :key="item.id">{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('trials:trialDocument:fileRecord:form:isEnable')"
        v-if="isManage && hasEdit && !viewStatus">
        <el-radio-group v-model="DATA.IsEnable" :disabled="rowBtnStatus === 'edit'">
          <el-radio :label="item.value" v-for="item in $d.YesOrNo" :key="item.id">{{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="isManage && hasEdit && !viewStatus">
        <el-button type="primary" @click="rowBtnStatus = 'save'" v-if="rowBtnStatus === 'edit'">
          {{ $t('common:button:edit') }}
        </el-button>
        <el-button type="primary" :loading="rowBtnLoading" @click="saveRowData" v-if="rowBtnStatus === 'save'">
          {{ $t('common:button:save') }}
        </el-button>
      </el-form-item>
    </el-form>
    <div class="line" v-if="!viewStatus"></div>
    <!-- 搜索框 -->
    <div class="search" style="position: relative">
      <el-form :inline="true" class="base-search-form">
        <el-form-item :label="$t('trials:trialDocument:fileRecord:search:name')">
          <el-input v-model="searchData.FileName" style="width: 100px" clearable />
        </el-form-item>
        <el-form-item :label="$t('trials:trialDocument:fileRecord: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:fileRecord:button:accredit') }}
          </el-button>
          <el-button type="primary" v-if="hasEdit && isManage && !viewStatus" @click.stop="openFile(false)">
            {{ $t('trials:trialDocument:fileRecord:button:uploadFile') }}
          </el-button>
          <el-button type="primary" v-if="hasEdit && isManage && !viewStatus" @click.stop="openFile(true)">
            {{ $t('trials:trialDocument:fileRecord: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:fileRecord:button:downLoadFile') }}
          </el-button>
          <el-button type="primary" v-if="hasDel && isManage && !viewStatus" :disabled="selectTable.length <= 0"
            @click.stop="delList">
            {{ $t('trials:trialDocument:fileRecord: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="FileName" :label="$t('trials:trialDocument:fileRecord:table:name')" show-overflow-tooltip
        sortable="custom">
        <template slot-scope="scope">
          <div v-if="
            scope.row.TrialFileRecord &&
            scope.row.TrialFileRecord.TrialFileTypeId
          " style="display: flex; align-items: center">
            <span class="fileName">{{
              scope.row.TrialFileRecord.FileName
            }}</span>
            <div v-if="isManage && !viewStatus" class="fileBtnBox">
              <i class="el-icon-view" @click.stop="preview(scope.row.TrialFileRecord)" />
              <i class="el-icon-download" v-if="hasDownLoad"
                @click.stop="downLoad(false, scope.row.TrialFileRecord, 'file')" />
              <i class="el-icon-delete" v-if="hasDel" @click.stop="delFile(scope.row, 'Trial')" />
            </div>
          </div>
          <i v-else-if="isManage && !viewStatus && hasEdit" class="el-icon-upload2"
            style="cursor: pointer; color: #409eff" @click.stop="upload(scope.row, 'Trial', ['.pdf'])" />
        </template>
      </el-table-column>
      <el-table-column prop="fileType" :label="$t('trials:trialDocument:fileRecord:table:fileType')"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.TrialFileRecord">{{
            scope.row.TrialFileRecord.FileFormat
          }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="fileType" :label="$t('trials:trialDocument:fileRecord:table:fileSize')"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="scope.row.TrialFileRecord">{{
            scope.row.TrialFileRecord.FileSize
              ? fileSizeFormatter(scope.row.TrialFileRecord.FileSize)
              : ''
          }}</span>
        </template>
      </el-table-column>
      <!--历史记录-->
      <el-table-column prop="HistoryFileRecord" :label="$t('trials:trialDocument:fileRecord:table:historyFileRecord')"
        show-overflow-tooltip v-if="isManage && !viewStatus">
        <template slot-scope="scope">
          <el-button type="text" @click.stop="openHistory(scope.row)">
            {{ scope.row.HistoryCount }}
            <i class="el-icon-upload2" />
          </el-button>
        </template>
      </el-table-column>

      <el-table-column prop="IsAuthorizedView" :label="$t('trials:trialDocument:fileRecord:table:isAuthorizedView')"
        show-overflow-tooltip sortable="custom" v-if="isManage && !viewStatus">
        <template slot-scope="scope">
          <el-switch :disabled="!scope.row.TrialFileRecord" 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:fileRecord:table:updateTime')"
        show-overflow-tooltip sortable="custom" />
      <el-table-column prop="CreateTime" :label="$t('trials:trialDocument:fileRecord: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 :disabled="!scope.row.TrialFileRecord || !scope.row.TrialFileRecord.FilePath
            " @click.stop="preview(scope.row.TrialFileRecord)" />
          <el-button v-if="hasDownLoad && isManage && !viewStatus" icon="el-icon-download"
            :title="$t('trials:trialDocument:fileRecord:button:downLoadFile')" circle :disabled="!scope.row.TrialFileRecord || !scope.row.TrialFileRecord.FilePath
              " @click.stop="downLoad(false, scope.row.TrialFileRecord, 'file')" />
          <el-button v-if="hasDel && isManage && !viewStatus" icon="el-icon-delete"
            :title="$t('trials:trialDocument:fileRecord:button:delete')" circle @click.stop="handleDel(scope.row)" />
        </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" />
    <history-file-list :config="file_config" :rowData="fileData" :uploadPath="uploadPath" @getList="getList" />
  </box-content>
</template>
<script>
import {
  addOrUpdateTrialFileType,
  getTrialNormalRecordList,
  deleteTrialNormalRecord,
  authorizedTTrialNormalRecord,
  addOrUpdateTrialNormalRecord,
  batchAddTrialNormalRecord,
  deleteTrialNormalRecordList,
} 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 historyFileList from '../historyFileList.vue'
const searchDataDefault = () => {
  return {
    IsAuthorizedView: null,
    FileName: null,
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: 'FileName',
  }
}
export default {
  name: 'fileRecord',
  components: { BoxContent, Pagination, uploadFiles, historyFileList },
  props: {
    viewStatus: {
      type: Boolean,
      default: true,
    },
    ArchiveTypeEnum: {
      type: Number,
      default: 0,
    },
    Id: {
      type: String,
      default: '',
    },
    rowData: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      rowBtnStatus: 'edit', // edit 编辑 save 保存
      rowBtnLoading: false,
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      selectTable: [],
      config: {
        visible: false,
        showClose: true,
        width: '800px',
        title: '',
        appendToBody: false,
        isFolder: false,
      },
      selectData: {},
      selectKey: null,
      uploadPath: null,
      faccept: ['.pdf'],
      limitLength: 0,

      DATA: {},

      fileData: {},
      file_config: {
        visible: false,
        title: this.$t('trials:trialDocument:historyFileList:title'),
        width: '800px',
      }

    }
  },
  methods: {
    openHistory(row) {
      this.fileData = {
        Name: row.TrialFileRecord ? row.TrialFileRecord.FileName : '',
        Id: row.Id,
        TrialFileTypeId: this.rowData.Id
      }
      this.file_config.visible = true
    },
    // 新增列表数据
    async uplaodFile(list) {
      console.log(list, 'list')
      try {
        if (!list || list.length <= 0) return false
        if (this.selectKey) {
          this.selectData[`${this.selectKey}FileRecord`] = list[0]
          this.loading = true
          let res = await addOrUpdateTrialNormalRecord(this.selectData)
          this.loading = false
          if (res.IsSuccess) {
            this.getList()
          }
          return false
        }
        let arr = []
        list.forEach((item) => {
          let obj = {
            TrialId: this.$route.query.trialId,
            TrialFileTypeId: this.Id,
            IsAuthorizedView: true,
            TrialFileRecord: item,
            HistoryFileRecord: null,
          }
          arr.push(obj)
        })
        this.loading = true
        let res = await batchAddTrialNormalRecord({
          TrialNormalRecordList: arr,
        })
        this.loading = false
        if (res.IsSuccess) {
          this.getList()
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 上传单个文件
    upload(row, key, faccept = []) {
      this.faccept = faccept
      this.selectData = deepClone(row)
      this.config.title = this.$t(
        'trials:trialDocument:fileRecord:form:title:uploadFile'
      )
      this.limitLength = 1
      this.selectKey = key
      this.config.visible = true
      this.config.isFolder = false
    },
    // 删除文件
    async delFile(row, key) {
      try {
        let confirm = await this.$confirm(
          this.$t('trials:trialDocument:fileRecord:message:deleteFile'),
          {
            type: 'warning',
            distinguishCancelAndClose: true,
          }
        )
        if (confirm !== 'confirm') return false
        let data = deepClone(row)
        data[`${key}FileRecord`] = null
        if (key === 'Trial') {
          data.IsAuthorizedView = false
        }
        this.loading = true
        let res = await addOrUpdateTrialNormalRecord(data)
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:deletedSuccessfully'))
          this.getList()
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 下载
    async downLoad(isArray = true, row, type = 'zip') {
      try {
        if (type === 'file') {
          return await downLoadFile(
            this.OSSclientConfig.basePath + row.FilePath,
            row.FileName
          )
        }
        let { files, name } = this.formatDownloadFile(isArray, row)
        let res = await downLoadFile(files, name, type)
        // if (res && this.downloadId) {
        //   this.downloadImageSuccess()
        // }
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化下载文件路径
    formatDownloadFile(isArray = true, row) {
      let files = [],
        name = `${this.TITLE}_${new Date().getTime()}.zip`,
        arr = ['Trial', 'History']
      if (!isArray) {
        name = `${row.Name}_${row.Version}_${new Date().getTime()}.zip`
        arr.forEach((key) => {
          if (row[`${key}FileRecord`] && row[`${key}FileRecord`].FilePath) {
            let obj = {
              name: `${row[`${key}FileRecord`].FileName.substring(
                0,
                row[`${key}FileRecord`].FileName.lastIndexOf('.')
              )}__${row.Version}${row[`${key}FileRecord`].FileName.substring(
                row[`${key}FileRecord`].FileName.lastIndexOf('.')
              ).toLocaleLowerCase()}`,
              url:
                this.OSSclientConfig.basePath +
                row[`${key}FileRecord`].FilePath,
            }
            files.push(obj)
          }
        })
      } else {
        this.selectTable.forEach((item) => {
          arr.forEach((key) => {
            if (item[`${key}FileRecord`] && item[`${key}FileRecord`].FilePath) {
              let obj = {
                name: `${item[`${key}FileRecord`].FileName.substring(
                  0,
                  item[`${key}FileRecord`].FileName.lastIndexOf('.')
                )}__${new Date().getTime()}${item[
                  `${key}FileRecord`
                ].FileName.substring(
                  item[`${key}FileRecord`].FileName.lastIndexOf('.')
                ).toLocaleLowerCase()}`,
                url:
                  this.OSSclientConfig.basePath +
                  item[`${key}FileRecord`].FilePath,
              }
              files.push(obj)
            }
          })
        })
      }
      return { files, name }
    },
    // 授权
    async auth(isArray = true, row, IsAuthorizedView) {
      try {
        let data = {}
        if (isArray) {
          data = {
            Ids: this.selectTable.map((item) => item.Id),
            IsAuthorizedView: true,
          }
        } else {
          data = {
            Ids: [row.Id],
            IsAuthorizedView,
          }
        }
        this.loading = true
        let res = await authorizedTTrialNormalRecord(data)
        this.loading = false
        if (res.IsSuccess) {
          this.$t('trials:trialDocument:fileRecord:message:authSuccessfully')
          if (isArray) {
            this.getList()
          }
        }
      } catch (err) {
        this.loading = false
        if (!isArray) {
          row.IsAuthorizedView = !row.IsAuthorizedView
        }
        console.log(err)
      }
    },
    // 删除列表数据
    handleDel(row) {
      this.$confirm(
        this.$t('trials:trialDocument:fileRecord:message:deleteMessage'),
        {
          type: 'warning',
          distinguishCancelAndClose: true,
        }
      )
        .then(() => {
          this.loading = true
          deleteTrialNormalRecord(row.Id)
            .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)
        })
    },
    // 批量删除列表数据
    delList() {
      this.$confirm(
        this.$t('trials:trialDocument:fileRecord:message:deleteMessage'),
        {
          type: 'warning',
          distinguishCancelAndClose: true,
        }
      )
        .then(() => {
          let data = {
            Ids: this.selectTable.map((item) => item.Id),
          }
          this.loading = true
          deleteTrialNormalRecordList(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 getList() {
      try {
        if (!this.Id) return false
        if (this.viewStatus) {
          this.searchData.IsAuthorizedView = true
        }
        this.searchData.TrialFileTypeId = this.Id
        this.searchData.TrialId = this.$route.query.trialId
        this.loading = true
        let res = await getTrialNormalRecordList(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
    },
    // 保存菜单数据
    async saveRowData() {
      try {
        this.rowBtnLoading = true
        let res = await addOrUpdateTrialFileType(this.DATA)
        this.rowBtnLoading = false
        if (res.IsSuccess) {
          this.rowBtnStatus = 'edit'
          this.$emit('getMenu')
          this.$message.success(this.$t('common:message:savedSuccessfully'))
        }
      } catch (err) {
        console.log(err)
        this.rowBtnLoading = false
      }
    },
    // 预览
    preview(row) {
      if (!row.FilePath) return false
      this.$preview({
        path: row.FilePath || row.fullPath,
        type: 'pdf',
        title: row.FileName,
      })
    },
    close() {
      this.config.visible = false
      // this.selectData = {}
      // this.selectKey = null
      this.faccept = ['.pdf']
      this.limitLength = 0
    },
    fileSizeFormatter(size) {
      if (!size) return
      return (size / Math.pow(1024, 2)).toFixed(3) + 'MB'
    },
    openFile(isFolder = false) {
      this.selectData = {}
      this.selectKey = null
      this.faccept = ['.pdf']
      this.limitLength = 0
      this.config.title = this.$t(
        'trials:trialDocument:fileRecord:form:title:uploadFile'
      )
      this.config.visible = true
      this.config.isFolder = isFolder
    },
  },
  watch: {
    Id: {
      handler() {
        this.rowBtnStatus = 'edit'
        this.getList()
      },
      immediate: true,
    },
    'rowData': {
      handler() {
        this.DATA = Object.assign({}, this.rowData)
      },
      immediate: true,
      deep: true
    },
  },
  created() {
    let typeArr = ['', 'Report', 'Doc', 'Record', 'Reviewer', 'Template']
    let types = typeArr[this.ArchiveTypeEnum]
    this.uploadPath = `/${this.$route.query.trialId}/Document/${types}`
  },
  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;
  margin-right: 3px;
}

.fileBtnBox {
  display: inline-block;
  width: 50px;

  i {
    cursor: pointer;
    color: #409eff;
    margin-right: 3px;

    &:last-child {
      margin: 0;
    }
  }
}
</style>