<template>
  <BaseContainer>
    <template slot="search-container">
      <el-form :inline="true" size="small">
        <el-form-item :label="$t('dictionary:signature:search:FileTypeId')">
          <el-select v-model="searchData.FileTypeId" style="width: 150px">
            <el-option
              v-for="item of dict.type.Sys_Document"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dictionary:signature:search:Name')">
          <el-input v-model="searchData.Name" style="width: 130px" clearable />
        </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>
      <el-button
        type="primary"
        icon="el-icon-plus"
        style="margin-left: auto"
        size="small"
        @click="handleAdd"
      >
        {{ $t('common:button:new') }}
      </el-button>
    </template>
    <template slot="main-container">
      <el-table
        v-adaptive="{ bottomOffset: 60 }"
        v-loading="loading"
        :data="list"
        stripe
        height="100"
        @sort-change="handleSortByColumn"
      >
        <el-table-column type="index" width="40" />
        <el-table-column
          prop="FileType"
          :label="$t('dictionary:signature:table:FileType')"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="Name"
          :label="$t('dictionary:signature:table:Name')"
          show-overflow-tooltip
          sortable="custom"
        />

        <el-table-column
          prop="SignViewMinimumMinutes"
          :label="$t('dictionary:signature:table:SignViewMinimumMinutes')"
          show-overflow-tooltip
          sortable="custom"
        />
        <el-table-column
          prop="NeedConfirmedUserTypes"
          :label="$t('dictionary:signature:table:NeedConfirmedUserTypes')"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{
              scope.row.NeedConfirmedUserTypes
                ? scope.row.NeedConfirmedUserTypes.join(', ')
                : ''
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="IsDeleted"
          :label="$t('dictionary:signature:table:IsDeleted')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsDeleted" type="danger">{{
              $fd('TrainingStatus', scope.row.IsDeleted)
            }}</el-tag>
            <el-tag v-else type="primary">{{
              $fd('TrainingStatus', scope.row.IsDeleted)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="DocUserSignType"
          :label="$t('dictionary:signature:table:DocUserSignType')"
          show-overflow-tooltip
          sortable="custom"
        >
          <template slot-scope="scope">
            {{ $fd('ReadingYesOrNo', Number(scope.row.DocUserSignType)) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="CreateTime"
          :label="$t('dictionary:signature:table:CreateTime')"
          show-overflow-tooltip
          sortable="custom"
        />

        <el-table-column :label="$t('common:action:action')">
          <template slot-scope="scope">
            <el-button type="text" @click="handlePreview(scope.row)">
              {{ $t('common:button:preview') }}
            </el-button>
            <el-button type="text" @click="handleEdit(scope.row)">
              {{ $t('common:button:edit') }}
            </el-button>
            <el-button
              :disabled="scope.row.IsDeleted"
              type="text"
              @click="handleRepeal(scope.row)"
            >
              {{ $t('common:button:revoke') }}
            </el-button>
            <el-button type="text" @click="handleDelete(scope.row)">
              {{ $t('common:button:delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination
        class="page"
        :total="total"
        :page.sync="searchData.PageIndex"
        :limit.sync="searchData.PageSize"
        @pagination="getList"
      />

      <!-- 新增/编辑 -->
      <el-dialog
        v-if="editVisible"
        :visible.sync="editVisible"
        :close-on-click-modal="false"
        :title="title"
        width="600px"
        custom-class="base-dialog-wrapper"
      >
        <TemplateForm
          :data="currentRow"
          @closeDialog="closeDialog"
          @getList="getList"
        />
      </el-dialog>

      <!-- 预览文件 -->
      <el-dialog
        v-if="previewVisible"
        :visible.sync="previewVisible"
        :title="$t('common:button:preview')"
        :fullscreen="true"
        append-to-body
        custom-class="base-dialog-wrapper"
      >
        <div
          class="base-modal-body"
          style="border: 2px solid #ccc; padding: 10px"
        >
          <PreviewFile
            v-if="previewVisible"
            :file-path="currentPath"
            :file-type="currentType"
          />
        </div>
      </el-dialog>
    </template>
  </BaseContainer>
</template>
<script>
import { getSystemDocumentList, deleteSystemDocument } from '@/api/dictionary'
import { userAbandonDoc } from '@/api/trials'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import TemplateForm from './TemplateForm'
import PreviewFile from '@/components/PreviewFile/index'
const searchDataDefault = () => {
  return {
    FileTypeId: '',
    Name: '',
    PageIndex: 1,
    PageSize: 20,
  }
}
export default {
  name: 'SignatureTemplate',
  components: { BaseContainer, Pagination, TemplateForm, PreviewFile },
  dicts: ['Sys_Document'],
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      currentRow: {},
      currentPath: '',
      currentType: '',
      editVisible: false,
      previewVisible: false,
      title: '',
      loading: false,
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 获取系统文件数据
    getList() {
      this.loading = true
      getSystemDocumentList(this.searchData)
        .then((res) => {
          this.loading = false
          const { CurrentPageData, TotalCount } = res.Result
          CurrentPageData.forEach((item) => {
            item.NeedConfirmedUserTypes = []
            item.NeedConfirmedUserTypeIds = []
            item.NeedConfirmedUserTypeList.forEach((i) => {
              item.NeedConfirmedUserTypes.push(i.UserTypeShortName)
              item.NeedConfirmedUserTypeIds.push(i.NeedConfirmUserTypeId)
            })
          })
          this.list = CurrentPageData
          this.total = TotalCount
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 新增
    handleAdd() {
      this.title = 'Add'
      this.currentRow = {}
      this.editVisible = true
    },
    // 预览
    handlePreview(row) {
      const { Name, FullFilePath } = row
      this.currentPath = FullFilePath
      this.currentType = row.Name
        ? Name.substring(Name.lastIndexOf('.') + 1).toLocaleLowerCase()
        : ''
      this.previewVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.title = 'Edit'
      this.currentRow = { ...row }
      this.editVisible = true
    },
    // 废除
    handleRepeal(row) {
      this.$confirm(this.$t('dictionary:signature:confirm:delFile'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          this.loading = true
          userAbandonDoc(row.Id, true)
            .then((res) => {
              this.loading = false
              if (res.IsSuccess) {
                this.getList()
                this.$message.success(
                  this.$t('common:message:savedSuccessfully')
                )
              }
            })
            .catch(() => {
              this.loading = false
            })
        })
        .catch(() => {})
    },
    // 删除
    handleDelete(row) {
      this.$confirm(this.$t('trials:staffResearch:message:confirmDel'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      }).then(() => {
        this.loading = true
        deleteSystemDocument(row.Id)
          .then((res) => {
            this.loading = false
            if (res.IsSuccess) {
              this.list.splice(
                this.list.findIndex((item) => item.Id === row.Id),
                1
              )
              this.$message.success(
                this.$t('common:message:deletedSuccessfully')
              )
            }
          })
          .catch(() => {
            this.loading = false
          })
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.editVisible = false
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.getList()
      this.$nextTick(() => {
        this.$refs.SysAttachmentList.clearSort()
      })
    },
    // 查询
    handleSearch() {
      this.searchData.PageIndex = 1
      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()
    },
  },
}
</script>
