<template>
  <div class="table-page">
    <!--  四级路由切换  -->
    <page-route-tab />
    <div class="table-page-content">
      <div class="left-tree">
        <tree-side
          ref="treeSide"
          :dataLoading="treeLoading"
          :default-expand-all="false"
          :defaultProps="defaultProps"
          :tabList="['行政维度']"
          :treeData="treeData"
          isDeselect
          @currentChange="currentChange"
        ></tree-side>
      </div>
      <div class="right-table">
        <div class="full-page bg">
          <div class="search-box">
            <div class="search-box-combination">
              <div class="search-box-label">工作时间：</div>
              <div>
                <el-date-picker
                  v-model="dateRange"
                  end-placeholder="工作时间"
                  range-separator="至"
                  start-placeholder="工作时间"
                  style="width: 360px"
                  type="datetimerange"
                  format="yyyy-MM-dd HH:mm"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  @change="datePickerChange"
                >
                </el-date-picker>
              </div>
              <SearchCommon :optionList="optionList" @search="handleSearch" />
            </div>
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <div ref="btnPanel" class="btn-box">
                <el-button
                  class="btn btn-plus"
                  icon="el-icon-plus"
                  size="small"
                  type="primary"
                  @click="changePage('EditAddPage', {catalogId: treeItem.id})"
                >
                  添加
                </el-button>
                <el-button
                  :disabled="!currentDataDel.length"
                  :loading="btnLoading"
                  class="btn btn-delete"
                  icon="el-icon-delete"
                  plain
                  size="small"
                  type="danger"
                  @click="handleDelete()"
                >
                  删除
                </el-button>
                <el-button
                  :disabled="!currentDataDel.length"
                  :loading="downloadLoading"
                  class="btn btn-delete"
                  icon="el-icon-download"
                  size="small"
                  type="warning"
                  @click="handleExport"
                >
                  导出
                </el-button>
              </div>
              <div ref="tableRef" class="table-content">
                <el-table
                  ref="multipleSelection"
                  v-loading="tableLoading"
                  :data="tableData"
                  :default-sort="getSorterDirection(params, true)"
                  :max-height="tableMaxHeight"
                  border
                  class="table-list"
                  element-loading-background="rgba(10 ,38 ,61, 0.9)"
                  row-key="id"
                  stripe
                  @select="handleSelection"
                  @selection-change="handleSelectionChange"
                  @sort-change="sortChange"
                  @row-dblclick="handleDbClick"
                >
                  <el-table-column align="center" type="selection" width="50" />
                  <el-table-column
                    :index="
                      index =>
                        index +
                        1 +
                        (params.pageBean.page - 1) * params.pageBean.pageSize
                    "
                    align="center"
                    label="序号"
                    type="index"
                    width="60"
                  />

                  <el-table-column
                    :formatter="
                      ({startTime, endTime}) =>
                        `${startTime.slice(0, 16)} 至 ${endTime.slice(0, 16)}`
                    "
                    align="center"
                    label="工作时间"
                    min-width="160"
                    prop="startTime"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({shiftName}) => shiftName || '-'"
                    align="center"
                    label="班次"
                    min-width="70"
                    prop="shiftName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({dutyPersonnel}) => dutyPersonnel || '-'"
                    align="center"
                    label="值班人员"
                    min-width="160"
                    prop="dutyPersonnel"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({nextShiftPersonnel}) => nextShiftPersonnel || '-'
                    "
                    align="center"
                    label="接班人员"
                    min-width="160"
                    prop="nextShiftPersonnel"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    align="center"
                    label="审核状态"
                    min-width="160"
                    prop="isAudit"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <div
                        :style="{
                          color: row.isAudit === '1' ? '#409EFF' : '#909399'
                        }"
                      >
                        {{ row.isAudit === '1' ? '已审核' : '未审核' }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    align="center"
                    label="操作"
                    min-width="100"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="handleDetailPage(row)"
                      >
                        详情
                      </el-link>
                      <el-link
                        :disabled="btnLoading"
                        :underline="false"
                        type="danger"
                        @click="handleDelete(row)"
                      >
                        删除
                      </el-link>
                    </template>
                  </el-table-column>
                </el-table>
                <pagination
                  ref="paginationPanel"
                  :pageResult="params.pageBean"
                  style="margin-top: 10px"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import PageRouteTab from '@/components/PageRouteTab/index.vue'
import pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import SearchCommon from '@/components/SearchCommon/index.vue'
import PubSub from 'pubsub-js'
import {
  getSorterDirection,
  refineRequestBody,
  setQueryValue
} from '@/utils/requestWrappers'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {
  tableData,
  tableDelete,
  exportDataBatch
} from '@/api/patrolAndRescue/commandDispatch/reportManagement/dutyRecords.js'
import treeSide from '@/components/treeSide/index.vue'
import {getTree} from '@/api/tree'
import moment from 'moment'

export default {
  name: 'TablePage',
  components: {
    PageRouteTab,
    treeSide,
    pagination,
    SearchCommon
  },
  mixins: [TableMixin],
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      btnLoading: false,
      downloadLoading: false,
      treeLoading: true,
      treeItem: {},
      treeData: [], //左边树
      dateRange: [
        moment()
          .startOf('month')
          .format('YYYY-MM-DD HH:mm:ss'),
        moment()
          .endOf('month')
          .format('YYYY-MM-DD HH:mm:ss')
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      optionList: [
        {
          title: '班次',
          prop: 'shift_name_',
          type: 'select',
          default: true,
          option: getDictionaryByCode('pbbc')
        },
        {
          title: '值班人员',
          prop: 'duty_personnel_',
          type: 'input',
          
        },
        {
          title: '接班人员',
          prop: 'next_shift_personnel_',
          type: 'input'
        },
        {
          title: '审核状态',
          prop: 'is_audit_',
          type: 'select',
          option: [
            {name: '已审核', value: '1'},
            {name: '未审核', value: '0'}
          ],
          
        }
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 'road_id_'},
          {operation: 'LIKE', property: 'shift_name_'},
          {operation: 'LIKE', property: 'duty_personnel_'},
          {operation: 'LIKE', property: 'next_shift_personnel_'},
          {operation: 'IN', property: 'is_audit_'},
          {operation: 'GREAT_EQUAL', property: 'start_time_'},
          {operation: 'LESS_EQUAL', property: 'end_time_'}
        ]
      }
    }
  },
  created() {
    // 获取树形目录
    this.getOrgTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      let array = []
      if (this.treeItem.children.length > 0) {
        array = this.extractIds(this.treeItem)
      }
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id)
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'road_id_ ', array)
      this.loadData()
    })
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.handleCurrentChange(1)
          break
        case 'edit':
          this.loadData()
          break
      }
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    // 时间范围切换
    datePickerChange(val) {
      if (!val || val.length === 0) {
        setQueryValue(this.params, 'start_time_', '')
        setQueryValue(this.params, 'end_time_', '')
      } else {
        setQueryValue(this.params, 'start_time_', val[0])
        setQueryValue(this.params, 'end_time_', val[1])
      }
      this.params.pageBean.page = 1
      this.loadData()
    },
    extractIds(node) {
      let ids = []
      // 如果当前节点有 children，则递归提取
      if (node.children) {
        ids = node.children.map(child => child.id) // 提取当前节点的 id
        // 递归提取子节点的 id
        node.children.forEach(child => {
          ids = ids.concat(this.extractIds(child))
        })
      }
      return ids
    },
    // 获取路段树
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true
        let {value} = await getTree()
        this.treeData = [value]
      } finally {
        this.treeLoading = false
        callback && callback(this.treeData)
      }
    },

    //左边树节点
    currentChange(nodeItem) {
      if (nodeItem.id === '1766017468444450816') {
        setQueryValue(this.params, 'road_id_', this.extractIds(nodeItem))
      } else if (nodeItem.children && nodeItem.children.length > 0) {
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 'road_id_', array)
      } else {
        setQueryValue(this.params, 'road_id_', [nodeItem?.id] || [])
      }
      this.params.pageBean.page = 1
      this.calcTableHeight(500)
      PubSub.publish('TreeItemSelected', nodeItem)
      this.treeItem = nodeItem || {}
      this.loadData()
    },

    //获取数据
    async loadData() {
      try {
        this.tableLoading = true
        const {total = 0, rows = []} = await tableData(refineRequestBody(this.params))
        this.params.pageBean.total = total
        this.tableData = rows.map(i => ({
          ...i
        }))
      } finally {
        this.tableLoading = false
      }
    },

    // 导出
    async handleExport() {
      this.downloadLoading = true
      try {
        const params = this.currentDataDel.map(id => `ids=${id}`).join('&')
        await exportDataBatch(params)
      } catch (e) {
        this.$message.error(`数据导出失败`)
      } finally {
        this.downloadLoading = false
      }
    },

    // 删除
    handleDelete(row) {
      this.clickTimer = true
      setTimeout(_ => (this.clickTimer = false))
      this.$confirm('确定删除选中的值班日志吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.btnLoading = true
          let ids = row ? row.id : this.currentDataDel.join()
          try {
            const {state} = await tableDelete(ids)
            if (state) {
              this.$message.success(`值班日志删除成功`)
              const {page, pageSize, total} = this.params.pageBean
              const totalPages = Math.ceil(total / pageSize) // 计算总页数
              if (totalPages > 1 && page === totalPages) {
                if (this.tableData.length === 1) {
                  // 当前页只有一条数据
                  this.params.pageBean.page -= 1 // 返回前一页
                }
              }
              await this.loadData()
            }
          } finally {
            this.btnLoading = false
          }
        })
        .catch(_ => _)
    },

    //修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      if (row.adminComment)
        return this.$message.warning('该日志已审核，无法修改！')
      this.changePage('EditAddPage', row)
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      // 传递当前选中的树节点信息
      const payload = row.id
        ? row
        : {
            catalogId: this.treeItem.id,
            orgName: this.treeItem.name,
            path: this.treeItem.path,
            code: this.treeItem.code,
            clearForm: true // 清空表单标志
          }
      this.$emit(
        'changePage',
        pageName,
        _ => {
          PubSub.publish(pageName, payload)
        },
        row.id ? '编辑' : '添加'
      )
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
.table-page {
  .basis {
    min-width: 240px !important;
  }
}
</style>
