<template>
  <BaseContainer>
    <template slot="title-container">
      <el-row v-if="isSystem" style="width: 100%;">
        <el-col :span="12">
          <h3>{{ TITLE }}</h3>
        </el-col>
        <el-col :span="12" style="text-align:right;">
          <h3>
            <Pagination class="page" :total="total" :page.sync="searchData.pageIndex" :limit.sync="searchData.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>
    </template>
    <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" clearable>
            <el-option v-for="item of $d.Sys_Document" :key="item.id" :label="item.label" :value="item.id" />
          </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 :label="$t('dictionary:signature:search:DocLanguageType')">
          <el-select v-model="searchData.DocLanguageType" style="width: 150px" clearable>
            <el-option v-for="item of $d.DocLanguageType" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dictionary:signature:table:NeedConfirmedUserTypes')">
          <el-select v-model="searchData.UserTypeId" style="width: 150px" clearable>
            <el-option v-for="item of userTypeOptions" :key="item.Id" :label="item.UserTypeShortName"
              :value="item.Id" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dictionary:signature:table:IsDeleted')">
          <el-select v-model="searchData.IsDeleted" style="width: 150px" clearable>
            <el-option v-for="item of $d.TrainingStatus" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dictionary:signature:table:DocUserSignType')">
          <el-select v-model="searchData.DocUserSignType" style="width: 150px" clearable>
            <el-option v-for="item of $d.ReadingYesOrNo" :key="item.id" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('dictionary:signature:table:createTime')">
          <el-date-picker v-model="timeList" @change="changeTimeList" value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']" type="datetimerange">
          </el-date-picker>
        </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-button type="primary" size="small" @click="handleAdd">
            {{ $t('common:button:new') }}
          </el-button>
          <el-button type="primary" size="small" :disabled="multipleSelection.length <= 0"
            @click="publishSystemDocument(multipleSelection)">
            {{ $t('dictionary:signature:button:publish') }}
          </el-button>
          <el-button type="primary" size="small" :disabled="multipleSelection.length <= 0"
            @click="handleRepeal(multipleSelection)">
            {{ $t('common:button:revoke') }}
          </el-button>
        </el-form-item>
      </el-form>

    </template>
    <template slot="main-container">
      <el-table v-adaptive="{ bottomOffset: 60 }" v-loading="loading" :data="list" stripe height="100"
        @sort-change="handleSortByColumn" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="index" width="40" /> -->
        <el-table-column type="selection" width="55" :selectable="handleSelectable">
        </el-table-column>
        <el-table-column prop="FileType" :label="$t('dictionary:signature:table:FileType')" show-overflow-tooltip
          sortable="custom" min-width="120px" />
        <el-table-column prop="Name" :label="$t('dictionary:signature:table:Name')" show-overflow-tooltip
          sortable="custom" min-width="120px" />
        <el-table-column prop="AttachmentCount" :label="$t('dictionary:signature:table:AttachmentCount')"
          show-overflow-tooltip sortable="custom" min-width="150px">
          <template slot-scope="scope">
            <el-button type="text" @click.stop="openAttachment(scope.row, true)">
              {{ scope.row.AttachmentCount }}
              <i class="el-icon-upload2" />
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="DocLanguageType" :label="$t('dictionary:signature:table:DocLanguageType')"
          show-overflow-tooltip sortable="custom" min-width="120px">
          <template slot-scope="scope">
            <span>{{ $fd('DocLanguageType', scope.row.DocLanguageType) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="SignViewMinimumMinutes" :label="$t('dictionary:signature:table:SignViewMinimumMinutes')"
          show-overflow-tooltip sortable="custom" min-width="200px" />
        <el-table-column prop="CurrentStaffTrainDays" :label="$t('dictionary:signature:table:CurrentStaffTrainDays')"
          show-overflow-tooltip sortable="custom" min-width="200px" />
        <el-table-column prop="NewStaffTrainDays" :label="$t('dictionary:signature:table:NewStaffTrainDays')"
          show-overflow-tooltip sortable="custom" min-width="200px" />
        <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" min-width="120px">
          <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="IsPublish" :label="$t('dictionary:signature:table:IsPublish')" show-overflow-tooltip
          sortable="custom" min-width="120px">
          <template slot-scope="scope">
            <el-tag :type="scope.row.IsPublish ? 'primary' : 'danger'">{{
              $fd('AttachmentPublishStatus', scope.row.IsPublish)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="DocUserSignType" :label="$t('dictionary:signature:table:DocUserSignType')"
          show-overflow-tooltip sortable="custom" min-width="150px">
          <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" min-width="180px" />

        <el-table-column :label="$t('common:action:action')" min-width="240px" fixed="right">
          <template slot-scope="scope">
            <el-button circle icon="el-icon-view" @click="handlePreview(scope.row)"
              :title="$t('common:button:preview')">
            </el-button>
            <el-button circle icon="el-icon-edit-outline" :title="$t('common:button:edit')"
              @click="handleEdit(scope.row)">
            </el-button>
            <el-button :disabled="scope.row.IsPublish" circle icon="el-icon-position"
              :title="$t('dictionary:signature:button:publish')" @click="publishSystemDocument([scope.row])">
            </el-button>
            <el-button :disabled="scope.row.IsDeleted" circle icon="el-icon-close" :title="$t('common:button:revoke')"
              @click="handleRepeal([scope.row])">
            </el-button>
            <el-button circle icon="el-icon-delete" :title="$t('common:button:delete')"
              @click="handleDelete(scope.row)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination class="page" :total="total" :page.sync="searchData.PageIndex" :limit.sync="searchData.PageSize"
        @pagination="getList" v-if="!isSystem" />

      <!-- 新增/编辑 -->
      <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" v-if="editVisible" @getList="getList" />
      </el-dialog>
      <!--附件列表-->
      <attachmentList v-if="config.visible" :config="config" :rowData="currentRow" :SystemDocumentId="SystemDocumentId"
        @getList="getList" />
      <!-- 预览文件 -->
      <attachmentPreview :SystemDocumentId="SystemDocumentId" :visible.sync="perview_visible" :isView="true"
        v-if="perview_visible" />
      <el-dialog v-if="previewVisible" :visible.sync="previewVisible" :title="$t('common:button:preview')"
        :fullscreen="true" append-to-body custom-class="base-dialog-wrapper">
        <span style="position: fixed; left: 16px; top: 45px;cursor: pointer;font-size: 18px;color:#409EFF"
          @click.stop="openAttachment(currentRow)" v-if="currentRow.AttachmentCount">{{
            $t('trials:signRecords:table:AttachmentCount') }} ({{
            currentRow.AttachmentCount }})</span>
        <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, publishSystemDocument, outLineSystemDocument, getSystemDocumentAttachmentList } from '@/api/dictionary'
import { userAbandonDoc, getTrialUserTypeList } from '@/api/trials'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import TemplateForm from './TemplateForm'

import attachmentList from './attachmentList'
import PreviewFile from '@/components/PreviewFile/index'
import attachmentPreview from './attachmentPreview'
const searchDataDefault = () => {
  return {
    FileTypeId: '',
    BeginCreateTime: null,
    EndCreateTime: null,
    IsDeleted: null,
    DocUserSignType: null,
    UserTypeId: null,
    DocLanguageType: null,
    Name: '',
    PageIndex: 1,
    PageSize: 20,
  }
}
export default {
  name: 'SignatureTemplate',
  components: { BaseContainer, Pagination, TemplateForm, PreviewFile, attachmentList, attachmentPreview },
  dicts: ['Sys_Document'],
  props: {
    isSystem: {
      type: Boolean,
      default: false
    },
    TITLE: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      searchData: searchDataDefault(),
      list: [],
      total: 0,
      currentRow: {},
      currentPath: '',
      currentType: '',
      editVisible: false,
      previewVisible: false,
      title: '',
      loading: false,
      userTypeOptions: [],
      timeList: [],
      attachment_Visible: false,
      SystemDocumentId: null,
      config: {
        visible: false,
        title: this.$t('dictionary:signature:attachmentList:title'),
        width: '800px',
      },
      multipleSelection: [],
      perview_visible: false
    }
  },
  mounted() {
    this.getList()
    this.getUserType()
  },
  methods: {
    handleSelectable(row) {
      return !row.IsDeleted || !row.IsPublish
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 发布
    async publishSystemDocument(list) {
      try {
        let confirm = await this.$confirm(this.$t('dictionary:signature:confirm:publishFile'), {
          type: 'warning',
          distinguishCancelAndClose: true,
        })
        if (!confirm) return false
        let arr = list.filter(item => !item.IsPublish)
        if (arr.length <= 0) return this.getList()
        let data = {
          ids: arr.map(item => item.Id)
        }
        this.loading = true
        let res = await publishSystemDocument(data)
        this.loading = false
        if (res.IsSuccess) {
          this.getList()
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    openAttachment(row, isList = false) {
      this.SystemDocumentId = row.Id
      this.currentRow = { ...row }
      if (!isList) {
        this.perview_visible = true
      } else {
        this.config.visible = true
      }
    },
    changeTimeList() {
      if (this.timeList) {
        this.searchData.BeginCreateTime = this.timeList[0]
        this.searchData.EndCreateTime = this.timeList[1]
      } else {
        this.searchData.BeginCreateTime = null
        this.searchData.EndCreateTime = null
      }
    },
    // 获取用户类型下拉数据
    getUserType() {
      getTrialUserTypeList()
        .then((res) => {
          this.userTypeOptions = res.Result
        })
        .catch(() => {
          this.loading = false
        })
    },
    // 获取系统文件数据
    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 = this.$t('common:button:new')
      this.currentRow = {}
      this.editVisible = true
    },
    // 预览
    async handlePreview(row) {
      const { Name, FullFilePath } = row
      this.currentPath = FullFilePath
      this.currentType = row.Name
        ? Name.substring(Name.lastIndexOf('.') + 1).toLocaleLowerCase()
        : ''
      let searchData = {
        OffLine: false,
        PageIndex: 1,
        PageSize: 1000,
        Asc: false,
        SortField: null,
        SystemDocumentId: row.Id
      }
      this.currentRow = Object.assign({}, row)
      let res = await getSystemDocumentAttachmentList(searchData)
      this.currentRow.AttachmentCount = res.Result.CurrentPageData.length
      this.previewVisible = true
    },
    // 编辑
    handleEdit(row) {
      this.title = this.$t('common:action:edit')
      this.currentRow = { ...row }
      this.editVisible = true
    },
    // 废除
    handleRepeal(row) {
      this.$confirm(this.$t('dictionary:signature:confirm:delFile'), {
        type: 'warning',
        distinguishCancelAndClose: true,
      })
        .then(() => {
          let arr = row.filter(item => !item.IsDeleted)
          if (arr.length <= 0) return this.getList()
          let data = {
            Ids: arr.map(item => item.Id)
          }
          this.loading = true
          outLineSystemDocument(data)
            .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
      this.attachment_Visible = 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>
