<template>
  <div class="bbsl-common-page">
    <div class="bbsl-table-search">
      <el-form ref="searchForm" v-model="queryParam.querys" :inline="true">
        <el-form-item label="姓名：">
          <el-input
            v-model="queryParam.querys[1].value"
            placeholder="请输入姓名"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch"
            >搜索
          </el-button>
          <el-button icon="el-icon-refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-content">
      <div class="tree-container">
        <tree-side
          ref="treeSide"
          :default-expand-all="false"
          :defaultProps="{children: 'children', label: 'name'}"
          :tabList="['组织维度']"
          :treeData="treeData"
          isDeselect
          @currentChange="currentChange"
        ></tree-side>
      </div>
      <div ref="contentPanel" class="bbsl-table-content">
        <div ref="btnPanel" class="bbsl-btn-content">
          <el-button
            icon="el-icon-upload2"
            type="warning"
            :disabled="multipleSelection.length === 0"
            @click="exportFile"
          >
            导出
          </el-button>
        </div>
        <el-table
          ref="multipleSelection"
          v-loading="loading"
          :cell-style="{'text-align': 'center'}"
          :data="tableData"
          :default-sort="getSorterDirection(queryParam, true)"
          :header-cell-style="{'text-align': 'center'}"
          :max-height="tableMaxHeight"
          :style="{width: '100%'}"
          size="mini"
          @selection-change="handleSelectionChange"
          @sort-change="sortChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column
            :index="
              (index) =>
                index +
                1 +
                (queryParam.pageBean.page - 1) * queryParam.pageBean.pageSize
            "
            fixed
            label="序号"
            type="index"
            width="55"
          />

          <el-table-column
            :formatter="({fullname}) => fullname || '-'"
            label="名称"
            min-width="100"
            prop="fullname"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({username}) => username || '-'"
            label="账号"
            min-width="100"
            prop="username"
            show-overflow-tooltip
          />
          <el-table-column
            :formatter="({sex}) => sex || '-'"
            label="性别"
            min-width="100"
            prop="sex"
            show-overflow-tooltip
          />
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" @click="getPerson(row)"
                >编辑档案</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          ref="paginationPanel"
          :current-page="queryParam.pageBean.page"
          :page-size="queryParam.pageBean.pageSize"
          :page-sizes="[20, 30, 40, 50]"
          :total="queryParam.pageBean.total"
          align="right"
          background
          class="bbsl-pagination"
          layout="prev, pager, next,total, sizes, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      title="选择导出年份"
      width="40%"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="form"
        label-position="left"
        ref="textForm"
        :rules="rules"
      >
        <el-form-item label="年份:" prop="year">
          <el-date-picker
            style="width: 90%"
            type="year"
            value-format="yyyy"
            v-model="form.year"
            autocomplete="off"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="this.closeDialog()">取 消</el-button>
        <el-button type="primary" @click="submitExport">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {TableMixin} from '@/mixins/tableMixin'
import {
  getSorterDirection,
  refineRequestBody,
  setQueryValue,
} from '@/utils/requestWrappers'
import {getOrgUserQuery, treeDataByDem} from '@/api/systemInterface'
import * as api from '@/api/examDataMenu/archivesManager/userFiles'

import {dictionaryEscape} from '@/utils/dictionary'
import treeSide from '@/components/treeSide/index.vue'

export default {
  name: 'UserFiles',
  components: {treeSide},
  mixins: [TableMixin],
  data() {
    return {
      tableData: [], // 表格数据
      // 查询对象
      queryParam: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'EQUAL', property: 'ORG_ID_'},
          {operation: 'LIKE', property: 'fullname'},
        ],
        sorter: [{direction:"DESC",property:"updateTime"}],
      },
      treeData: [],
      activeTreeItem: {},
      uploadLoading: false,
      dialogFormVisible: false,
      noLoadData: true,
      multipleSelection: [],
      form: {
        year: '',
      },
      rules: {
        year: [{required: true, message: '请选择导出年份', trigger: 'change'}],
      },
    }
  },
  created() {
    // 获取树形目录
    this.getTreeData((treeData) => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.activeTreeItem = treeData[0] || {}
      this.$nextTick((_) => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
        setQueryValue(this.queryParam, 'ORG_ID_', treeData[0]?.id || '')
        this.loadData()
      })
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    getPerson(row) {
      console.log(row,'qqqqq')
      this.$router.push({
        name: 'editPerson',
        query: row,
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val.map((item) => {
        return item.userId
      })
    },
    //获取树
    async getTreeData(callback) {
      this.treeData = [
        {
          name: '部门列表',
          id: '',
          parentId: '',
          children: await treeDataByDem() || [],
        },
      ]
      // this.treeData = (await equipmentTree()).value || []
      // 保证重新刷新树数据后，选中效果不失效
      if (this.activeTreeItem.id) {
        this.$nextTick((_) => {
          this.$refs.treeSide?.setCurrentKey(this.activeTreeItem.id)
        })
      }
      callback && callback(this.treeData)
    },

    //左边树节点
    currentChange(nodeItem) {
      // 修改对应的字段值
      setQueryValue(this.queryParam, 'ORG_ID_', nodeItem?.id || '')
      this.activeTreeItem = nodeItem || {}
      this.calcTableHeight(500)
      this.queryParam.pageBean.page = 1
      this.loadData()
    },

    // 获取表格数据
    async loadData() {
      try {
        this.loading = true
        const {total = 0, rows = []} = await getOrgUserQuery(this.queryParam)
        this.queryParam.pageBean.total = total
        this.tableData = rows
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.queryParam = this.$options.data().queryParam
      this.activeTreeItem = this.treeData[0] || {}
      this.$nextTick((_) => {
        this.$refs.treeSide?.setCurrentKey(this.activeTreeItem.id)
      })
      this.loadData()
    },

    // 导出数据
    exportFile() {
      this.dialogFormVisible = true
    },
    submitExport() {
      this.$refs.textForm.validate(async (valid) => {
        if (valid) {
          await api.downloadDoc({
            ids: this.multipleSelection,
            year: this.form.year * 1,
          })
          this.closeDialog()
        }
      })
    },
    closeDialog() {
      this.form.year = ''
      this.dialogFormVisible = false
    },
  },
}
</script>
<style lang="scss" scoped>
.bbsl-common-page {
  display: flex;
  flex-direction: column;
  row-gap: 10px;

  .page-content {
    display: flex;
    height: calc(100% - 70px);
    column-gap: 10px;

    .tree-container {
      height: 100%;
      min-width: 300px;
      background: #fff;
      border-radius: 20px;
      padding: 20px 20px;
      box-shadow: 0px 0px 12px 0 rgba($color: #000000, $alpha: 0.1);
      box-sizing: border-box;
    }

    .bbsl-table-content {
      height: 100%;
      flex: 1;
      margin-top: 0;
      box-sizing: border-box;
    }
  }
}

.avatar-uploader {
  display: inline-block;
  margin-left: 10px;
}
</style>
