<template>
  <div class="app-container">
    <!-- 档案目录 -->
    <div class="left">
      <div class="left_top">
        当前选择的是:&nbsp;&nbsp;{{ chooseData.dictLabel }}
      </div>
      <!-- 操作工具栏 -->
      <el-row :gutter="10" class="mb8" style="margin-top: 1rem">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openCreateForm"
                     v-hasPermi="['archives:catalog:create']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" plain icon="el-icon-edit" :disabled="updateMultiple" size="mini"
                     @click="openUpdateForm"
                     v-hasPermi="['archives:catalog:update']"
          >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" plain icon="el-icon-delete" :disabled="deleteMultiple" size="mini"
                     @click="handleDelete"
                     v-hasPermi="['archives:catalog:remove']"
          >删除
          </el-button>
        </el-col>
      </el-row>
      <el-input placeholder="请输入名称" size="small" style="margin:1rem 0 1rem 0" v-model="filterText"/>
      <el-skeleton v-if="treeLoading"/>
      <el-tree v-else @check="handleSelectionChange" show-checkbox :data="dictDataTree" ref="tree"
               :filter-node-method="filterNode"
               @node-click="handleNodeClick"
               highlight-current
               :default-checked-keys="[chooseData.id]"
      >
        <template v-slot="{ node, data }">
          <!-- 自定义节点内容 -->
          <span class="custom-tree-node">
        {{ truncateText(data.dictLabel, 15) }}
      </span>
        </template>
      </el-tree>
    </div>

    <!-- 具体表格 -->
    <div class="right">
      <!-- 搜索栏 -->
      <el-empty style="margin-top: 10%" v-show="!chooseData" description="请先选择目录"></el-empty>
      <div v-show="!!chooseData">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="90px"
        >
          <el-form-item label="名称" prop="archivesName">
            <el-input v-model="queryParams.archivesName" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery"/>
          </el-form-item>
          <el-form-item v-if="activeTab === 'contract_type'" label="时间区间" prop="queryDateArray">
            <el-date-picker v-model="queryParams.queryDateArray" style="width: 240px" value-format="yyyy-MM-dd HH:mm:ss"
                            type="daterange"
                            range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                            :default-time="['00:00:00', '23:59:59']"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 操作工具栏 -->
        <el-row :gutter="10" class="mb8" style="margin-bottom: 1rem">
          <el-col :span="1.5" v-if="chooseData.isCreated">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openTableFrom(undefined)"
            >新增
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getTabList"></right-toolbar>
        </el-row>

        <!-- 表格 -->
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" :row-class-name="getRowClass">
          <el-table-column label="序号" align="center" width="80">
            <template scope="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" label="档案名称" align="center" prop="archivesName" width="180"/>
<!--          <el-table-column label="档案类别" align="center" prop="sex" width="80">-->
<!--            <template v-slot="scope">-->
<!--              <dict-tag :type="DICT_TYPE.ARCHIVES_ITEM_TYPE" :value="scope.row.archivesType"/>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column :show-overflow-tooltip="true" label="档案存放位置" align="center" prop="archivesPhysicsUrl" width="180"/>
          <el-table-column v-if="activeTab === 'contract_type'" label="签订日期" align="center" prop="signTime" width="180"/>
          <el-table-column v-if="activeTab === 'contract_type'" label="到期日期" align="center" prop="expireTime" width="180"/>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
          <el-table-column v-if="chooseData.isUpdated || chooseData.isDeleted" label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="180">
            <template v-slot="scope">
              <el-button v-if="chooseData.isUpdated" size="mini" type="text" icon="el-icon-edit" @click="openTableFrom(scope.row)"
              >修改
              </el-button>
              <el-button v-if="chooseData.isDeleted" size="mini" type="text" icon="el-icon-delete" @click="handleItemDelete(scope.row)"
              >删除
              </el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.$index, scope.row)">
                <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="showItem" size="mini" type="text" icon="el-icon-search"
                  >查看详情
                  </el-dropdown-item>
                  <el-dropdown-item v-if="chooseData.isDownload" command="downloadItem" size="mini" type="text" icon="el-icon-download"
                  >下载
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>

      </div>

      <div style="margin-bottom: 10rem">
        <!-- 分页组件 -->
        <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                    @pagination="getTabList"
        />
      </div>
    </div>

    <ArchivesCatalogForm ref="formRef" @success="getList"/>
    <ArchivesForm ref="archivesFormRef" @success="getTabList" />
    <ArchivesShowForm ref="archivesShowFormRef" @success="getTabList" />
  </div>
</template>

<script>

import { getArchivesCatalogList, removeArchivesRoleAndDict } from '@/api/company/archives/archivesRole'
import {queryArchivesPage, removeArchivesById} from '@/api/company/archives/archives'
import ArchivesCatalogForm from '@/views/knowledge/views/archives/form/ArchivesCatalogForm'
import ArchivesForm from '@/views/knowledge/views/archives/form/ArchivesForm'
import {downloadFilesAsZip} from '@/utils/downloadZIP'
import ArchivesShowForm from '@/views/knowledge/views/archives/form/ArchivesShowForm'

export default {
  name: 'ArchivesTable',
  components: {
    ArchivesCatalogForm,
    ArchivesForm,
    ArchivesShowForm
  },
  props: {
    activeTab: {
      type: String,
      defaultValue: undefined,
      required: true
    }
  },
  data() {
    return {
      filterText: '',
      chooseData: '',
      queryParams: {
        archivesName: null,
        queryDateArray: null,
        pageNo: 1,
        pageSize: 10,
        dataId: null
      },
      // 显示搜索条件
      showSearch: true,
      deleteMultiple: true,
      updateMultiple: true,
      dictDataTree: [],
      selectNodes: [],
      // 档案目录加载遮罩
      treeLoading : true,
      // 遮罩层
      loading: false,
      list: [],
      total: 0,
      chooseDataId: 0,
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    },
    activeTab() {
      this.getList()
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    // 新增
    openCreateForm() {
      const data = {
        activeTab: this.activeTab
      }
      this.$refs['formRef'].open(data)
    },
    // 修改
    openUpdateForm() {
      const data = {
        ...this.selectNodes[0],
        activeTab: this.activeTab
      }
      this.$refs['formRef'].open(data)
    },
    async getList() {
      this.selectNodes = []
      this.deleteMultiple = !this.selectNodes.length > 0
      this.updateMultiple = !(this.selectNodes.length === 1)
      try {
        this.treeLoading = true
        const res = await getArchivesCatalogList(this.activeTab)
        this.dictDataTree = res.data
      } finally {
        this.treeLoading = false
      }
    },
    // 节点事件
    handleNodeClick(e) {
      this.loading = true
      this.chooseData = e
      this.chooseDataId = e.dataId
      this.queryParams.dataId = e.dataId
      this.getTabList()
    },
    // 节点筛选
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    truncateText(text, maxLength) {
      if (text.length > maxLength) {
        return text.substring(0, maxLength) + '...'
      }
      return text
    },
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getTabList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.queryDateArray = null
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      const flag = this.selectNodes.findIndex(item => item.dataId === selection.dataId)
      if (flag > -1) {
        this.selectNodes.splice(flag, 1)
      } else {
        this.selectNodes.push(selection)
      }
      this.deleteMultiple = !this.selectNodes.length > 0
      this.updateMultiple = !(this.selectNodes.length === 1)
    },
    /** 删除按钮操作 */
    async handleDelete() {
      const dataIds = this.selectNodes.map(item => item.dataId)
      const dictLabels = this.selectNodes.map(item => item.dictLabel)
      try {
        await this.$modal.confirm('是否确认删除名称为"' + dictLabels + '"的数据项?')
        await removeArchivesRoleAndDict(dataIds)
        await this.getList()
        this.$modal.msgSuccess('删除成功')
      } catch {
      }
    },
    /** 获取表格数据 */
    async getTabList(){
      this.loading = true
      const res = await queryArchivesPage(this.queryParams)
      this.list = res.data.records
      this.total = res.data.total
      this.loading = false
    },
    openTableFrom(row){
      const data = {
        ...row,
        activeTab: this.activeTab,
        dataId: this.chooseDataId
      }
      this.$refs['archivesFormRef'].open(data)
    },
    async handleItemDelete(row){
      const id = row.id
      const name = row.archivesName
      try {
        await this.$modal.confirm('是否确认删除名称为"' + name + '"的数据项?')
        await removeArchivesById(id)
        await this.getTabList()
        this.$modal.msgSuccess('删除成功')
      }catch {}
    },
    // 下载ZIP
    async downloadItem(row){
      const fileObject = {
        zipName: row.archivesName,
        files: row.archivesUrls.split(",").map(item => {
          return {
            name: item.split("|")[1],
            url: item.split("|")[0],
            uid: item.split("|")[2],
            status: item.split("|")[3]
          }
        })
      }
      await downloadFilesAsZip(fileObject)
    },
    handleCommand(command, index, row){
      switch (command){
        case 'showItem':
          row = {
            ...row,
            activeTab: this.activeTab
          }
          this.$refs["archivesShowFormRef"].open(row)
          break
        case 'downloadItem':
          this.downloadItem(row)
          break
        default:
          break
      }
    },
    // 记录项颜色
    getRowClass(row, rowIndex){
      if (this.activeTab !== 'contract_type'){
        return '';
      }
      const diffTime = new Date(row.row.expireTime) - new Date()
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      if (diffDays < 0 || diffDays <= 30){
        return 'one-month-row';
      }else if (diffDays <= 90){
        return 'three-months-row';
      }
      return ''
    }
  }
}
</script>

<style scoped lang="scss">
div {
  padding: 0;
  margin: 0 auto;
}

.app-container {
  display: flex;
  justify-content: space-between;
}

.left {
  width: 20%;
  margin-right: 1rem;
}

.right {
  width: 80%;
}

.left_top {
  color: #00afff;
  font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
  font-size: 14px;
  padding-left: 5px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

::v-deep .el-tree-node__expand-icon.is-leaf {
  display: none;
}

::v-deep .el-table .one-month-row td{
  background-color: #ffcccc !important; /* 红色背景 */
}

::v-deep .el-table .three-months-row td{
  background-color: #ffffcc !important; /* 黄色背景 */
}
</style>
