<template>
  <div class="needSignSys-wrapper">
    <el-row>
      <el-col :span="12">
        <!-- 待签署的系统文件 -->
        <h3>{{ $t('trials:workbench:title:trialDocSigned') }}</h3>
      </el-col>
      <el-col :span="12" style="text-align:right;">
        <h3>
          <Pagination class="page" :total="total" :page.sync="listQuery.pageIndex" :limit.sync="listQuery.pageSize" layout="total, sizes, prev, pager, next" :background="false" style="display: inline-block;" @pagination="getList" />
          <el-button icon="el-icon-refresh-left" size="small" circle :title="$t('common:button:reset')" @click="handleReset" />
        </h3>
      </el-col>
    </el-row>
    <!--  -->
    <el-table
      ref="needSignSysList"
      v-loading="listLoading"
      :data="list"
      :show-header="true"
      v-adaptive="{bottomOffset:45}"
      height="100"
      @sort-change="handleSortByColumn"
      :default-sort ="{prop: 'ConfirmTime', order: 'descending'}"
    >
      <el-table-column type="index" width="40" />
      <!-- 项目编号 -->
      <el-table-column
        :label="$t('trials:workbench:table:trialId')"
        prop="TrialCode"
        show-overflow-tooltip
        sortable="custom"
      />
      <!-- 试验名称 -->
      <el-table-column
        :label="$t('trials:workbench:table:experimentName')"
        prop="ExperimentName"
        show-overflow-tooltip
        sortable="custom"
      />
      <!-- 研究方案号 -->
      <el-table-column
        :label="$t('trials:workbench:table:researchNo')"
        prop="ResearchProgramNo"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        :label="$t('trials:sysDocBeSigned:table:fileType')"
        prop="FileType"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        :label="$t('trials:sysDocBeSigned:table:fileName')"
        prop="Name"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        :label="$t('trials:sysDocBeSigned:table:CreateTime')"
        prop="CreateTime"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        :label="$t('trials:sysDocBeSigned:table:ConfirmTime')"
        prop="ConfirmTime"
        show-overflow-tooltip
        sortable="custom"
      />
      <el-table-column
        :label="$t('common:action:action')"
        width="140"
      >
        <template slot-scope="scope">
          <el-button
            icon="el-icon-view"
            circle
            :title="$t('trials:self-attachment:action:preview')"
            @click="handlePreview(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>

    <!-- 预览/签署文件 -->
    <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') }}
        </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" @closeDialog="closeSignDialog" />
    </el-dialog>
  </div>
</template>
<script>
import { getWaitSignSysDocList, setSystemDocFirstViewTime, getTrialSignDocumentList  } from '@/api/trials'
import Pagination from '@/components/Pagination'
import PreviewFile from '@/components/PreviewFile/index'
import SignForm from '@/views/trials/trials-panel/attachments/self-attachment/components/SignForm'
const searchDataDefault = () => {
  return {
    IsSigned: true,
    pageIndex: 1,
    pageSize: 20,
    asc: false,
    sortField: 'ConfirmTime'
  }
}
export default {
  name: 'NeedSignSysDoc',
  components: { Pagination, PreviewFile, SignForm },
  data() {
    return {
      listQuery: searchDataDefault(),
      listLoading: false,
      list: [],
      total: 0,
      previewVisible: false,
      signVisible: false,
      currentMinMinutes: 0,
      duration: 0,
      timer: null,
      btnLoading: false,
      fileName: '',
      currentPath: '',
      currentType: '',
      currentIsConfirm: false,
      currentUser: zzSessionStorage.getItem('userName'),
      currentRow: {}
    }
  },
  mounted() {
    this.getList()
  },
  destroyed() {
    if (this.timer) {
      this.stopTimer()
    }
  },
  methods: {
    // 预览
    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
    },
    getList() {
      getTrialSignDocumentList(this.listQuery).then(res => {
        this.listLoading = false
        this.total = res.Result.TotalCount
        this.list = res.Result.CurrentPageData
      }).catch(() => { this.listLoading = false })
    },
    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('.'))
      this.listLoading = true
      setSystemDocFirstViewTime(row.Id).then(res => {
        this.listLoading = false
        this.previewVisible = true
        const _this = this
        setTimeout(() => {
          _this.initTimer()
        }, 1000)
      }).catch(() => {
        this.listLoading = false
      })
    },
    // 排序
    handleSortByColumn(column) {
      if (column.order === 'ascending') {
        this.listQuery.asc = true
      } else {
        this.listQuery.asc = false
      }
      this.listQuery.sortField = column.prop
      this.getList()
    },
    handleReset() {
      this.listQuery = searchDataDefault()
      this.getList()
      this.$nextTick(() => {
        this.$refs.needSignSysList.clearSort()
      })
    },
    // 签名
    handleConfirm() {
      this.signVisible = true
    },
    // 关闭签名弹窗
    closeSignDialog(isSave) {
      this.signVisible = false
      if (isSave) {
        this.currentIsConfirm = true
        this.getList()
        this.$emit('refreshStats')
      }
    },
    // 初始化计时器,清除上一次的数据
    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
    }
  }
}
</script>

<style lang="scss" scoped>
.needSignSys-wrapper{
  height: 100%;
}

</style>
