<template>
  <box-content>
    <div class="title">
      {{ TITLE }}
    </div>
    <el-form :inline="true" class="base-search-form topForm">
      <el-form-item :label="$t('trials:trialDocument:reportDoc:form:firstFinalDate')">
        <el-date-picker :disabled="!isManage || rowBtnStatus === 'edit'" v-model="DATA.FirstFinalDate" type="date"
          value-format="yyyy-MM-dd" format="yyyy-MM-dd" placeholder="">
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('trials:trialDocument:reportDoc: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:reportDoc: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"></div>
    <!-- 搜索框 -->
    <div class="search" style="position: relative">
      <el-form :inline="true" class="base-search-form">
        <el-form-item :label="$t('trials:trialDocument:reportDoc:search:name')">
          <el-input v-model="searchData.Name" style="width: 100px" clearable />
        </el-form-item>
        <el-form-item :label="$t('trials:trialDocument:reportDoc:search:version')">
          <el-input v-model="searchData.Version" style="width: 100px" clearable />
        </el-form-item>
        <el-form-item :label="$t('trials:trialDocument:reportDoc: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:reportDoc:button:accredit') }}
          </el-button>
          <el-button type="primary" v-if="hasAdd && isManage && !viewStatus" @click.stop="handleAdd">
            {{ $t('trials:trialDocument:reportDoc:button:add') }}
          </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:reportDoc:button:downLoadFile') }}
          </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="Name" :label="$t('trials:trialDocument:reportDoc:table:name')" sortable="custom"
        show-overflow-tooltip />
      <el-table-column prop="Version" :label="$t('trials:trialDocument:reportDoc:table:version')" show-overflow-tooltip
        sortable="custom" />
      <!--定稿PDF-->
      <el-table-column prop="PDFFileRecord" :label="$t('trials:trialDocument:reportDoc:table:pdfFileRecord')"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <div v-if="
            scope.row.PDFFileRecord && scope.row.PDFFileRecord.TrialFileTypeId
          " style="display: flex; align-items: center">
            <span class="fileName">{{ scope.row.PDFFileRecord.FileName }}</span>
            <div v-if="isManage && !viewStatus" class="fileBtnBox">
              <i class="el-icon-view" @click.stop="preview(scope.row.PDFFileRecord)" />
              <i class="el-icon-download" v-if="hasDownLoad"
                @click.stop="downLoad(false, scope.row.PDFFileRecord, 'file')" />
              <i class="el-icon-delete" v-if="hasDel" @click.stop="delFile(scope.row, 'PDF')" />
            </div>
          </div>
          <i v-else-if="isManage && !viewStatus && hasEdit" class="el-icon-upload2"
            style="cursor: pointer; color: #409eff" @click.stop="upload(scope.row, 'PDF')" />
        </template>
      </el-table-column>
      <!--定稿WORD-->
      <el-table-column prop="WordFileRecord" :label="$t('trials:trialDocument:reportDoc:table:wordFileRecord')"
        show-overflow-tooltip v-if="isManage && !viewStatus">
        <template slot-scope="scope">
          <div v-if="
            scope.row.WordFileRecord &&
            scope.row.WordFileRecord.TrialFileTypeId
          " style="display: flex; align-items: center">
            <span class="fileName">{{
              scope.row.WordFileRecord.FileName
            }}</span>
            <div v-if="isManage && !viewStatus" class="fileBtnBox">
              <i class="el-icon-download" v-if="hasDownLoad"
                @click.stop="downLoad(false, scope.row.WordFileRecord, 'file')" />
              <i class="el-icon-delete" v-if="hasDel" @click.stop="delFile(scope.row, 'Word')" />
            </div>
          </div>
          <i v-else-if="isManage && !viewStatus && hasEdit" class="el-icon-upload2"
            style="cursor: pointer; color: #409eff" @click.stop="upload(scope.row, 'Word')" />
        </template>
      </el-table-column>
      <!--签字页-->
      <el-table-column prop="SignFileRecord" :label="$t('trials:trialDocument:reportDoc:table:signFileRecord')"
        show-overflow-tooltip v-if="isManage && !viewStatus">
        <template slot-scope="scope">
          <div v-if="
            scope.row.SignFileRecord &&
            scope.row.SignFileRecord.TrialFileTypeId
          " style="display: flex; align-items: center">
            <span class="fileName">{{
              scope.row.SignFileRecord.FileName
            }}</span>
            <div v-if="isManage && !viewStatus" class="fileBtnBox">
              <i class="el-icon-view" @click.stop="preview(scope.row.SignFileRecord)" />
              <i class="el-icon-download" v-if="hasDownLoad"
                @click.stop="downLoad(false, scope.row.SignFileRecord, 'file')" />
              <i class="el-icon-delete" v-if="hasDel" @click.stop="delFile(scope.row, 'Sign')" />
            </div>
          </div>
          <i v-else-if="isManage && !viewStatus && hasEdit" class="el-icon-upload2"
            style="cursor: pointer; color: #409eff" @click.stop="upload(scope.row, 'Sign')" />
        </template>
      </el-table-column>
      <!--历史记录-->
      <el-table-column prop="HistoryFileRecord" :label="$t('trials:trialDocument:reportDoc: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:reportDoc:table:isAuthorizedView')"
        show-overflow-tooltip sortable="custom" v-if="isManage && !viewStatus">
        <template slot-scope="scope">
          <el-switch 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:reportDoc:table:updateTime')"
        show-overflow-tooltip sortable="custom" />
      <el-table-column prop="CreateTime" :label="$t('trials:trialDocument:reportDoc: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.PDFFileRecord || !scope.row.PDFFileRecord.FilePath
            " @click.stop="preview(scope.row.PDFFileRecord)" />
          <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:reportDoc:button:download')" circle
            @click.stop="downLoad(false, scope.row)" />
          <el-button v-if="hasDel && isManage && !viewStatus" icon="el-icon-delete"
            :title="$t('trials:trialDocument:reportDoc: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" />
    <reportDoc-form :ArchiveTypeEnum="ArchiveTypeEnum" :rowData="rowData" :config="config" :data="selectData"
      v-if="config.visible" @close="close" @getList="getList" />
    <history-file-list :config="file_config" :rowData="fileData" :uploadPath="uploadPath" @getList="getList" />
  </box-content>
</template>
<script>
import {
  addOrUpdateTrialFileType,
  getTrialFinalRecordList,
  deleteTrialFinalRecord,
  authorizedTrialFinalRecord,
  addOrUpdateTrialFinalRecord,
} 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 reportDocForm from './form.vue'
import historyFileList from '../historyFileList.vue'
const searchDataDefault = () => {
  return {
    IsAuthorizedView: null,
    Name: null,
    Version: null,
    PageIndex: 1,
    PageSize: 20,
    Asc: false,
    SortField: null,
  }
}
export default {
  name: 'reportDoc',
  components: { BoxContent, Pagination, reportDocForm, 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: '600px',
        title: '',
        appendToBody: false,
        status: 'add',
        upload: null,
      },
      selectData: {},
      DATA: {},

      fileData: {},
      file_config: {
        visible: false,
        title: this.$t('trials:trialDocument:historyFileList:title'),
        width: '800px',
      },
      uploadPath: null
    }
  },
  created() {
    let typeArr = ['', 'Report', 'Doc', 'Record', 'Reviewer', 'Template']
    let types = typeArr[this.ArchiveTypeEnum]
    this.uploadPath = `/${this.$route.query.trialId}/Document/${types}`
  },
  methods: {
    openHistory(row) {
      this.fileData = {
        Name: row.Name,
        Id: row.Id,
        TrialFileTypeId: this.rowData.Id
      }
      this.file_config.visible = true
    },
    // 上传单个文件
    upload(row, key) {
      this.selectData = deepClone(row)
      this.config.title = `${this.$t(
        'trials:trialDocument:reportDoc:form:title:upload'
      )}
        -
    ${this.isEN ? this.rowData.Name : this.rowData.NameCN}`
      this.config.status = 'edit'
      this.config.upload = key
      this.config.visible = true
    },
    // 新增
    handleAdd() {
      this.selectData = {}
      this.config.title = `${this.$t(
        'trials:trialDocument:reportDoc:form:title:add'
      )}
        -
    ${this.isEN ? this.rowData.Name : this.rowData.NameCN}`
      this.config.status = 'add'
      this.config.upload = null
      this.config.visible = true
    },
    // 编辑
    handleEdit(row) {
      this.selectData = deepClone(row)
      this.config.title = `${this.$t(
        'trials:trialDocument:reportDoc:form:title:edit'
      )}
        -
    ${this.isEN ? this.rowData.Name : this.rowData.NameCN}`
      this.config.status = 'edit'
      this.config.upload = null
      this.config.visible = true
    },
    // 删除文件
    async delFile(row, key) {
      try {
        let confirm = await this.$confirm(
          this.$t('trials:trialDocument:reportDoc:message:deleteFile'),
          {
            type: 'warning',
            distinguishCancelAndClose: true,
          }
        )
        if (confirm !== 'confirm') return false
        let data = deepClone(row)
        data[`${key}FileRecord`] = null
        this.loading = true
        let res = await addOrUpdateTrialFinalRecord(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 = ['PDF', 'Word', 'Sign', '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.Name}_${item.Version}/${item[
                  `${key}FileRecord`
                ].FileName.substring(
                  0,
                  item[`${key}FileRecord`].FileName.lastIndexOf('.')
                )}__${item.Version}${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 authorizedTrialFinalRecord(data)
        this.loading = false
        if (res.IsSuccess) {
          this.$t('trials:trialDocument:reportDoc: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:reportDoc:message:deleteMessage'),
        {
          type: 'warning',
          distinguishCancelAndClose: true,
        }
      )
        .then(() => {
          this.loading = true
          deleteTrialFinalRecord(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)
        })
    },
    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 getTrialFinalRecordList(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
    },
  },
  watch: {
    Id: {
      handler() {
        this.rowBtnStatus = 'edit'
        this.getList()
      },
      immediate: true,
    },
    'rowData': {
      handler() {
        this.DATA = Object.assign({}, this.rowData)
      },
      immediate: true,
      deep: true
    },
  },
  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>