<template>
  <BaseContainer>
    <!-- 搜索框 -->
    <template slot="search-container">
      <el-form :inline="true">
        <!-- 文件类型 -->
        <el-form-item :label="$t('trials:self-attachment:table:fileType')">
          <el-select
            v-model="searchData.FileTypeId"
            style="width:150px;"
          >
            <el-option
              v-for="item of typeOptions"
              :key="item.FileTypeId"
              :label="item.FileType"
              :value="item.FileTypeId"
            />
          </el-select>
        </el-form-item>
        <!-- 文件名称 -->
        <el-form-item :label="$t('trials:self-attachment:table:fileName')">
          <el-input v-model="searchData.Name" style="width:120px;" />
        </el-form-item>
        <!-- 是否签署 -->
        <el-form-item :label="$t('trials:self-attachment:table:isSign')">
          <el-select v-model="searchData.IsSign" clearable style="width:120px;">
            <el-option v-for="item of $d.YesOrNo" v-if="item.raw.ValueCN !== '无'" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <!-- 查询 -->
          <el-button icon="el-icon-search" type="primary" @click="handleSearch">
            {{ $t('common:button:search') }}
          </el-button>
          <!-- 重置 -->
          <el-button icon="el-icon-refresh-left" type="primary" @click="handleReset">
            {{ $t('common:button:reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>

    <template slot="main-container">
      <!-- 系统文件列表 -->
      <el-table
        ref="TrialAttachments"
        v-loading="loading"
        v-adaptive="{bottomOffset:60}"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" width="40" />
        <!-- 文件类型 -->
        <el-table-column
          prop="FileType"
          :label="$t('trials:self-attachment:table:fileType')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 文件名称 -->
        <el-table-column
          prop="Name"
          :label="$t('trials:self-attachment:table:fileName')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 是否废除 -->
        <el-table-column
          prop="IsDeleted"
          :label="$t('trials:self-attachment:table:isDeleted')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsDeleted" type="danger">{{ $fd('YesOrNo', scope.row.IsDeleted) }}</el-tag>
            <el-tag v-else type="primary">{{ $fd('YesOrNo', scope.row.IsDeleted) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 上传时间 -->
        <el-table-column
          prop="CreateTime"
          :label="$t('trials:self-attachment:table:uploadTime')"
          show-overflow-tooltip
          sortable="custom"
        />
        <!-- 是否签署 -->
        <el-table-column
          prop="ConfirmTime"
          :label="$t('trials:self-attachment:table:isSign')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsConfirmed" type="primary">{{ $fd('YesOrNo', scope.row.IsConfirmed) }}</el-tag>
            <el-tag v-else type="danger">{{ $fd('YesOrNo', scope.row.IsConfirmed) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 签署时间 -->
        <el-table-column
          prop="ConfirmTime"
          :label="$t('trials:self-attachment:table:signTime')"
          show-overflow-tooltip
          sortable="custom"
        />

        <el-table-column :label="$t('common:action:action')">
          <template slot-scope="scope">
            <!-- 预览 -->
            <el-button
              icon="el-icon-view"
              circle
              :title="$t('trials:self-attachment:action:preview')"
              @click="handlePreview(scope.row)"
            />
            <!-- 签署 -->
            <el-button
              icon="el-icon-edit-outline"
              circle
              :disabled="!!scope.row.ConfirmTime"
              :title="$t('trials:self-attachment:action:sign')"
              @click="handleSign(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize" @pagination="getList" />
    </template>

    <!-- 预览文件 -->
    <el-dialog
      v-if="previewVisible"
      :visible.sync="previewVisible"
      :title="title"
      :fullscreen="true"
      append-to-body
      custom-class="base-dialog-wrapper"
    >
      <span v-if="!currentIsConfirm" style="position: fixed;right: 75px;top: 14px;">
        <span style="color:red;margin-right:10px;">
          <!-- 请仔细阅读文件，并签名确认 -->
          {{ $t('common:message:signTip') }}
          <span v-show="duration < currentMinMinutes * 60">{{ `(${currentMinMinutes * 60 - duration}s)` }}</span>
        </span>
        <!-- 签署 -->
        <el-button
          size="small"
          type="primary"
          :disabled="timer !== null || duration === 0"
          :loading="btnLoading"
          @click="handleConfirm"
        >
          {{ $t('common:button:sign') }}
          <!-- {{ duration >= currentMinMinutes * 60?'确认':`确认(${currentMinMinutes * 60 - duration}s)` }} -->
        </el-button>
      </span>

      <div class="base-modal-body" style="border:2px solid #ccc;padding: 10px">
        <PreviewFile v-if="previewVisible" :file-path="currentPath" :file-type="currentType" @getList="getList" />
      </div>
    </el-dialog>

    <!-- 签名弹框 -->
    <el-dialog
      v-if="signVisible"
      :visible.sync="signVisible"
      :close-on-click-modal="false"
      width="600px"
      append-to-body
    >
      <div slot="title">
        <span style="font-size:18px;">{{ $t('common:dialogTitle:sign') }}</span>
        <span style="font-size:12px;margin-left:5px">{{ `(${$t('common:label:sign')}${ currentUser })` }}</span>
      </div>
      <SignForm :is-system-doc="currentRow.IsSystemDoc" :document-id="currentRow.Id" :file-name="fileName" :trial-id="trialId" @closeDialog="closeSignDialog" />
    </el-dialog>
  </BaseContainer>
</template>
<script>
import { getUserDocumentList, setFirstViewDocumentTime, getTrialDocAndSystemDocType, getNextUnSignDocument } from '@/api/trials'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import PreviewFile from '@/components/PreviewFile/index'
import SignForm from './components/SignForm'
import store from '@/store'
const searchDataDefault = () => {
  return {
    FileTypeId: '',
    Name: '',
    SortField: '',
    IsSign: null,
    Asc: false,
    PageIndex: 1,
    PageSize: 20
  }
}
export default {
  name: 'TrialAttachments',
  components: { BaseContainer, Pagination, PreviewFile, SignForm },
  data() {
    return {
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      currentRow: {},
      currentPath: '',
      currentType: '',
      currentIsConfirm: false,
      currentMinMinutes: 0,
      title: '',
      duration: 0,
      timer: null,
      previewVisible: false,
      btnLoading: false,
      signVisible: false,
      fileName: '',
      currentUser: zzSessionStorage.getItem('userName'),
      typeOptions: [],
      trialId: this.$route.query.trialId
    }
  },
  mounted() {
    this.trialId = this.$route.query.trialId
    this.getTypeOptions()
    if (this.$route.query.isSign) {
      this.searchData.IsSign = JSON.parse(this.$route.query.isSign)
    }
    this.getList()
  },
  destroyed() {
    if (this.timer) {
      this.stopTimer()
    }
  },
  methods: {
    // 获取系统文件数据
    getList() {
      this.loading = true
      this.searchData.TrialId = this.trialId
      getUserDocumentList(this.searchData).then(async res => {
        this.loading = false
        this.list = res.Result.CurrentPageData
        this.total = res.Result.TotalCount
        var total = res.OtherInfo.NeedSignCount
        await store.dispatch('user/setTotalNeedSignTrialDocCount', total)
      }).catch(() => {
        this.loading = false
      })
    },
    // 获取文件类型下拉数据
    getTypeOptions() {
      getTrialDocAndSystemDocType(this.trialId).then(res => {
        this.typeOptions = res.Result
      })
    },
    // 预览
    handlePreview(row) {
      this.currentRow = { ...row }
      const { Name, FullFilePath, SignViewMinimumMinutes } = row
      this.currentPath = FullFilePath
      this.currentType = row.Name ? Name.substring(Name.lastIndexOf('.') + 1).toLocaleLowerCase() : ''
      this.currentMinMinutes = SignViewMinimumMinutes
      this.currentIsConfirm = true
      this.title = Name
      this.previewVisible = true
    },
    // 签署
    handleSign(row) {
      this.currentRow = { ...row }
      const { Name, FullFilePath, SignViewMinimumMinutes } = row
      this.currentPath = FullFilePath
      this.currentType = row.Name ? Name.substring(Name.lastIndexOf('.') + 1).toLocaleLowerCase() : ''
      this.currentMinMinutes = SignViewMinimumMinutes
      this.currentIsConfirm = false
      this.title = Name
      this.fileName = Name.slice(0, Name.lastIndexOf('.'))
      const trialId = this.trialId
      this.loading = true
      setFirstViewDocumentTime(trialId, row.Id, row.IsSystemDoc).then(res => {
        this.loading = false
        this.previewVisible = true
        const _this = this
        setTimeout(() => {
          _this.initTimer()
        }, 1000)
      }).catch(() => {
        this.loading = false
      })
    },
    // 初始化计时器,清除上一次的数据
    initTimer() {
      if (this.currentMinMinutes > 0 && !this.currentIsConfirm) {
        this.duration = 0
        if (this.timer) {
          this.stopTimer()
        }
        this.startTimer()
      }
    },
    // 开启计时器
    startTimer() {
      this.timer = setInterval(() => {
        this.duration++
        if (this.duration >= this.currentMinMinutes * 60) {
          this.stopTimer()
        }
      }, 1000)
    },
    // 清楚计时器
    stopTimer() {
      clearInterval(this.timer)
      this.timer = null
    },
    // 签名
    handleConfirm() {
      this.signVisible = true
    },
    // 关闭签名弹窗
    closeSignDialog(isSave) {
      this.signVisible = false
      if (isSave) {
        this.$confirm('是否进入下一个签署文档？').then(res => {
          getNextUnSignDocument({
            TrialId: this.trialId
          }).then(res => {
            this.handleSign(res.Result)
          })
        }).catch(() => {
          this.currentIsConfirm = true
        })
        this.getList()
      }
    },

    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
      this.$nextTick(() => {
        this.$refs.TrialAttachments.clearSort()
      })
    },
    // 查询
    handleSearch() {
      this.getList()
    },
    // 排序
    handleSortByColumn(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.getList()
    }
  }
}
</script>
