<template>
  <BaseContainer>
    <template slot="title-container">
      <div class="title" v-if="isDoc">
        {{ TITLE }}
      </div>
      <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">
        <!-- 文件类型 -->
        <el-form-item :label="$t('trials:signRecords:table:fileType')">
          <el-select v-model="searchData.FileTypeId" clearable style="width: 150px">
            <template v-if="isSystem">
              <el-option v-for="item of typeOptions" :key="item.id" :label="item.label" :value="item.id" />
            </template>
            <template v-else>
              <el-option v-for="item of typeOptions" :key="item.FileTypeId" :label="item.FileType"
                :value="item.FileTypeId" />
            </template>
          </el-select>
        </el-form-item>
        <!-- 文件名称 -->
        <el-form-item :label="$t('trials:signRecords:table:fileName')">
          <el-input v-model="searchData.Name" clearable style="width: 120px" />
        </el-form-item>
        <!-- 签署人 -->
        <el-form-item :label="$t('trials:signRecords:table:user')" v-if="!isSystem">
          <el-select v-model="searchData.UserId" clearable filterable style="width: 140px">
            <el-option v-for="item of userOptions" :key="item.UserId" :label="item.RealName" :value="item.UserId">
              <span style="float: left">{{ item.RealName || item.FullName }}</span>
              <span style="
                  float: right;
                  color: #8492a6;
                  font-size: 13px;
                  margin-left: 5px;
                ">
                {{ item.UserName }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:signRecords:table:user')" v-else-if="!isDoc">
          <el-select v-model="searchData.UserId" clearable filterable style="width: 140px">
            <el-option v-for="item of userOptions" :key="item.ConfirmUserId" :label="item.FullName"
              :value="item.ConfirmUserId">
              <span style="float: left">{{ item.RealName || item.FullName }}</span>
              <span style="
                  float: right;
                  color: #8492a6;
                  font-size: 13px;
                  margin-left: 5px;
                ">
                {{ item.UserName }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <!-- 用户名 -->
        <el-form-item :label="$t('trials:signRecords:table:userName')" v-if="isSystem">
          <el-input v-model="searchData.userName" clearable style="width: 120px" />
        </el-form-item>
        <!-- 用户类型 -->
        <el-form-item :label="$t('trials:signRecords:table:userType')" v-if="!isDoc && !isEASystem">
          <el-select v-model="searchData.UserTypeId" clearable filterable style="width: 120px">
            <el-option v-for="item of userTypeOptions"
              v-show="isSystem || (item.UserTypeEnum !== 26 && item.UserTypeEnum !== 27)" :key="item.Id"
              :label="item.UserTypeShortName" :value="item.Id">
              <span>{{ item.UserType }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:signRecords:table:isSign')" v-if="(!isDoc || !viewStatus) && !isEASystem">
          <el-select v-model="searchData.IsConfirmed" clearable style="width: 120px">
            <el-option v-for="i of $d.TrainingStatusEnum" :key="'IsConfirmed' + i.label" :value="i.value"
              :label="i.label" />
          </el-select>
        </el-form-item>
        <el-form-item :label="isDoc
          ? $t('trials:signRecords:table:isDeletedFile')
          : $t('trials:signRecords:table:isDeleted')
          " v-if="!isEASystem">
          <el-select v-model="searchData.IsDeleted" clearable style="width: 120px">
            <el-option v-for="i of $d.TrainingStatus" :key="'IsDeleted' + i.label" :value="i.value" :label="i.label" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('trials:signRecords:table:username')" v-if="isDoc && !isEASystem">
          <el-input v-model="searchData.UserName" style="width: 120px" />
        </el-form-item>
        <el-form-item :label="$t('trials:signRecords:table:confirmTime')" v-if="isDoc || isSystem">
          <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 :label="$t('trials:signRecords:table:uploadTime')" v-if="isSystem && !isEASystem">
          <el-date-picker v-model="timeListC" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange" :default-time="['00:00:00', '23:59:59']" @change="changeTimeListC" />
        </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-button type="primary" icon="el-icon-download" :loading="exportLoading" @click="handleExport"
            v-if="!isSystem || !hasPermi(['role:ea'])">
            {{ $t('common:button:export') }}
          </el-button>
        </el-form-item>
      </el-form>
    </template>

    <template slot="main-container">
      <!-- 系统文件列表 -->
      <el-table ref="AttachmentsManagement" v-loading="loading" v-adaptive="{ bottomOffset: 60 }" :data="list" stripe
        height="100" @sort-change="handleSortByColumn">
        <el-table-column type="index" width="40" />
        <!-- 文件类型 -->
        <el-table-column prop="FileType" :label="$t('trials:signRecords:table:fileType')" show-overflow-tooltip
          sortable="custom" width="160" />
        <!-- 文件名称 -->
        <el-table-column prop="Name" :label="$t('trials:signRecords:table:fileName')" show-overflow-tooltip
          sortable="custom" />
        <el-table-column :label="$t('trials:signRecords:table:AttachmentCount')" prop="AttachmentCount"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button type="text" @click.stop="openAttachment(scope.row, true)">{{ scope.row.AttachmentCount
            }}</el-button>
          </template>
        </el-table-column>
        <!-- 文件级别 -->
        <el-table-column prop="IsSystemDoc" :label="$t('trials:signRecords:table:fileLevel')" show-overflow-tooltip
          width="160" sortable="custom" v-if="!isSystem">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsSystemDoc" type="primary">{{
              $fd('IsSystemDoc', scope.row.IsSystemDoc)
            }}</el-tag>
            <el-tag v-else type="warning">{{
              $fd('IsSystemDoc', scope.row.IsSystemDoc)
            }}</el-tag>
          </template>
        </el-table-column>
        <!-- 是否废除 -->
        <el-table-column prop="IsDeleted" :label="isDoc
          ? $t('trials:signRecords:table:isDeletedFile')
          : $t('trials:signRecords: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="CreateTime" :label="$t('trials:signRecords:table:uploadTime')" show-overflow-tooltip
          width="160" sortable="custom" />
        <!-- 是否签署 -->
        <el-table-column prop="ConfirmTime" :label="$t('trials:signRecords:table:isSign')" show-overflow-tooltip
          sortable="custom">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.IsConfirmed" type="primary">{{
              $fd('TrainingStatusEnum', scope.row.IsConfirmed)
            }}</el-tag>
            <el-tag v-else type="danger">{{
              $fd('TrainingStatusEnum', scope.row.IsConfirmed)
            }}</el-tag>
          </template>
        </el-table-column>
        <!-- 签署人 -->
        <el-table-column prop="RealName" :label="$t('trials:signRecords:table:user')" show-overflow-tooltip
          sortable="custom" v-if="!isDoc || !viewStatus" />
        <!-- 用户名 -->
        <el-table-column prop="UserName" :label="$t('trials:signRecords:table:userName')" show-overflow-tooltip
          sortable="custom" />
        <!-- 用户类型 -->
        <el-table-column prop="UserConfirmedUserTypeList" :label="$t('trials:signRecords:table:userType')"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{
              Array.isArray(scope.row.UserConfirmedUserTypeList) &&
                scope.row.UserConfirmedUserTypeList.length > 0
                ? scope.row.UserConfirmedUserTypeList.join(', ')
                : ''
            }}</span>
          </template>
        </el-table-column>
        <!-- 签署时间 -->
        <el-table-column prop="ConfirmTime" :label="$t('trials:signRecords:table:confirmTime')" show-overflow-tooltip
          sortable="custom" />
        <el-table-column :label="$t('common:action:action')">
          <template slot-scope="scope">
            <!-- 预览 -->
            <el-button circle :title="$t('trials:signRecords:action:preview')" icon="el-icon-view"
              @click="handlePreview(scope.row)" />
          </template>
        </el-table-column>
      </el-table>

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

    <!-- 预览文件 -->
    <el-dialog v-if="previewVisible" :visible.sync="previewVisible" :title="$t('trials:signRecords:action: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" @getList="getList" />
      </div>
    </el-dialog>
    <attachmentList v-if="config.visible" :config="config" :rowData="currentRow" :SystemDocumentId="SystemDocumentId"
      :isView="true" @getList="getList" />
    <attachmentPreview :SystemDocumentId="SystemDocumentId" :visible.sync="perview_visible" :isView="true"
      v-if="perview_visible" />
  </BaseContainer>
</template>
<script>
import {
  getDocumentConfirmList,
  getTrialUserSelect,
  getTrialUserTypeList,
  getTrialDocAndSystemDocType,
  getSysDocumentConfirmList,
  getSysDocSignUserList
} from '@/api/trials'
import { pMTrainingRecordList_Export, getSysDocumentConfirmList_Export } from '@/api/export'
import BaseContainer from '@/components/BaseContainer'
import Pagination from '@/components/Pagination'
import PreviewFile from '@/components/PreviewFile/index'
import attachmentPreview from '@/views/dictionary/attachment/components/SignatureTemplate/attachmentPreview'
import attachmentList from '@/views/dictionary/attachment/components/SignatureTemplate/attachmentList'
const searchDataDefault = () => {
  return {
    UserName: null,
    StartConfirmTime: null,
    EndConfirmTime: null,
    EndCreateTime: null,
    BeginCreateTime: null,
    userName: null,
    FileTypeId: '',
    Name: '',
    UserId: '',
    UserTypeId: '',
    PageIndex: 1,
    PageSize: 20,
    IsConfirmed: null,
    IsDeleted: null,
  }
}
export default {
  name: 'AttachmentsManagement',
  components: { BaseContainer, Pagination, PreviewFile, attachmentPreview, attachmentList },
  props: {
    isDoc: {
      type: Boolean,
      default: false,
    },
    TITLE: {
      type: String,
      default: '',
    },
    viewStatus: {
      type: Boolean,
      default: false,
    },
    isSystem: {
      type: Boolean,
      default: false,
    }
  },
  data() {
    return {
      searchData: searchDataDefault(),
      loading: false,
      list: [],
      total: 0,
      currentRow: {},
      currentPath: '',
      currentType: '',
      previewVisible: false,
      userOptions: [],
      userTypeOptions: [],
      currentUser: zzSessionStorage.getItem('userName'),
      typeOptions: [],
      trialId: this.$route.query.trialId,
      exportLoading: false,
      timeList: [],
      timeListC: [],
      SystemDocumentId: null,
      perview_visible: null,
      config: {
        visible: false,
        title: this.$t('dictionary:signature:attachmentList:title'),
        width: '800px',
      },
    }
  },
  computed: {
    isEASystem() {
      return this.isSystem && this.hasPermi(['role:ea'])
    }
  },
  mounted() {
    this.getTypeOptions()
    this.getUserSelect()
    this.getUserType()
  },
  methods: {
    openAttachment(row, isList = false) {
      if (!row.AttachmentCount) return 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.StartConfirmTime = this.timeList[0]
        this.searchData.EndConfirmTime = this.timeList[1]
      } else {
        this.searchData.StartConfirmTime = null
        this.searchData.EndConfirmTime = null
      }
    },
    changeTimeListC() {
      if (this.timeListC) {
        this.searchData.BeginCreateTime = this.timeListC[0]
        this.searchData.EndCreateTime = this.timeListC[1]
      } else {
        this.searchData.BeginCreateTime = null
        this.searchData.EndCreateTime = null
      }
    },
    handleExport() {
      this.exportLoading = true
      if (this.isSystem) {
        return getSysDocumentConfirmList_Export(this.searchData)
          .then(() => {
            this.exportLoading = false
          })
          .catch((err) => {
            this.exportLoading = false
          })
      }
      pMTrainingRecordList_Export(this.searchData)
        .then(() => {
          this.exportLoading = false
        })
        .catch((err) => {
          this.exportLoading = false
        })
    },
    // 获取系统文件数据
    getList() {
      if (this.isEASystem) {
        this.searchData.IsConfirmed = true
        if (!this.searchData.FileTypeId && !this.searchData.Name && !this.searchData.UserId && !this.searchData.userName && (!Array.isArray(this.timeList) || this.timeList.length < 2)) {
          this.list = []
          this.total = 0
          return false
        }
      }
      this.loading = true
      if (this.viewStatus) {
        this.searchData.IsConfirmed = true
      }
      if (this.isDoc) {
        let IR = this.userTypeOptions.find((item) => item.UserTypeEnum == 13)
        if (IR) {
          this.searchData.UserTypeId = IR.Id
        }
      }
      if (this.isSystem) {
        getSysDocumentConfirmList(this.searchData)
          .then(async (res) => {
            this.loading = false
            this.list = res.Result.CurrentPageData
            this.total = res.Result.TotalCount
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.searchData.TrialId = this.trialId
        getDocumentConfirmList(this.searchData)
          .then(async (res) => {
            this.loading = false
            this.list = res.Result.CurrentPageData
            this.total = res.Result.TotalCount
          })
          .catch(() => {
            this.loading = false
          })
      }

    },
    // 获取文件类型下拉数据
    getTypeOptions() {
      if (this.isSystem) {
        this.typeOptions = this.$d.Sys_Document
        if (this.isEASystem) this.typeOptions = this.typeOptions.filter(item => item.raw.ChildGroup !== "Trial")
      } else {
        getTrialDocAndSystemDocType(this.trialId).then((res) => {
          this.typeOptions = res.Result
        })
      }

    },
    // 获取当前项目下参与者信息
    getUserSelect() {
      if (this.isSystem) {
        getSysDocSignUserList().then((res) => {
          this.userOptions = res.Result
        })
      } else {
        getTrialUserSelect(this.trialId).then((res) => {
          this.userOptions = res.Result
        })
      }
    },
    // 获取用户类型下拉数据
    getUserType() {
      getTrialUserTypeList()
        .then((res) => {
          this.userTypeOptions = res.Result
          this.getList()
        })
        .catch(() => {
          this.getList()
        })
    },
    // 预览
    handlePreview(row) {
      this.currentRow = { ...row }
      const { Name, FullFilePath } = row
      this.currentPath = FullFilePath
      this.currentType = row.Name
        ? Name.substring(Name.lastIndexOf('.') + 1).toLocaleLowerCase()
        : ''
      this.previewVisible = true
    },
    // 重置
    handleReset() {
      this.searchData = searchDataDefault()
      this.timeList = []
      this.timeListC = []
      this.getList()
      this.$nextTick(() => {
        this.$refs.AttachmentsManagement.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>
<style lang="scss" scoped>
.title {
  line-height: 40px;
  font-weight: bold;
  margin-bottom: 10px;
}
</style>
