<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="right-table">
        <div class="full-page bg">
          <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
            <el-tab-pane label="已打卡点位信息" name="first"></el-tab-pane>
            <el-tab-pane label="应打卡点位信息" name="second"></el-tab-pane>
            <el-tab-pane label="未打卡点位信息" name="third"></el-tab-pane>
          </el-tabs>
          <div v-if="activeName === 'first'" class="search-box">
            <div class="search-box-combination">
              <SearchCommon :optionList="optionList" @search="handleSearch" />
            </div>
          </div>
          <div class="main-table-container">
            <div class="table-container" style="padding: 20px">
              <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"
                >
                  <el-table-column
                    :index="
                      index =>
                        index +
                        1 +
                        (params.pageBean.page - 1) * params.pageBean.pageSize
                    "
                    align="center"
                    label="序号"
                    type="index"
                    width="100"
                  />
                  <!--                  <el-table-column-->
                  <!--                    v-if="activeName === 'first'"-->
                  <!--                    :formatter="({inspectTime}) => inspectTime || '-'"-->
                  <!--                    align="center"-->
                  <!--                    label="巡查日期"-->
                  <!--                    min-width="100"-->
                  <!--                    prop="inspectTime"-->
                  <!--                    show-overflow-tooltip-->
                  <!--                  />-->
                  <el-table-column
                    v-if="activeName === 'first'"
                    :formatter="({roadCode}) => roadCode || '-'"
                    align="center"
                    label="路段"
                    min-width="70"
                    prop="roadCode"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({direction}) =>
                        dictionaryEscape('xsfx', direction) || '-'
                    "
                    align="center"
                    label="方向"
                    min-width="70"
                    prop="direction"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    v-if="activeName === 'first'"
                    :formatter="({typeContentDetail}) => typeContentDetail || '-'"
                    align="center"
                    label="点位名称"
                    min-width="90"
                    prop="typeContentDetail"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    v-if="activeName !== 'first'"
                    :formatter="({name}) => name || '-'"
                    align="center"
                    label="点位名称"
                    min-width="90"
                    prop="name"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="
                      ({type}) => dictionaryEscape('xcdwlx', type) || '-'
                    "
                    align="center"
                    label="点位类型"
                    min-width="80"
                    prop="type"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    v-if="activeName === 'first'"
                    :formatter="({typeContent}) => typeContent || '-'"
                    align="center"
                    label="内容"
                    min-width="80"
                    prop="typeContent"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    v-if="activeName !== 'first'"
                    :formatter="({content}) => content || '-'"
                    align="center"
                    label="内容"
                    min-width="80"
                    prop="content"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({pegVal}) => pegVal || '-'"
                    align="center"
                    label="点位桩号"
                    min-width="70"
                    prop="pegVal"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    v-if="activeName === 'first'"
                    :formatter="
                      ({category}) =>
                        dictionaryEscape('xcdwlb', JSON.stringify(category)) ||
                        '-'
                    "
                    align="center"
                    label="点位类别"
                    min-width="80"
                    prop="category"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    v-if="activeName !== 'first'"
                    :formatter="
                      ({category}) =>
                        dictionaryEscape('xcdwlb', category) ||
                        '-'
                    "
                    align="center"
                    label="点位类别"
                    min-width="80"
                    prop="category"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    v-if="activeName === 'first'"
                    align="center"
                    label="巡检情况"
                    min-width="100"
                    prop="inspectStatus"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <el-link
                        :type="row.inspectStatus === '1' ? 'primary' : 'danger'"
                        :underline="false"
                      >
                        {{
                          dictionaryEscape('xcdwzt', row.inspectStatus) || '-'
                        }}
                      </el-link>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="activeName === 'first'"
                    :formatter="
                      ({handleStatus}) =>
                        dictionaryEscape('ycclzt', handleStatus) || '-'
                    "
                    align="center"
                    label="处置情况"
                    min-width="100"
                    prop="handleStatus"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    v-if="activeName === 'first'"
                    align="center"
                    label="操作"
                    min-width="100"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <!--                      <el-link-->
                      <!--                        :underline="false"-->
                      <!--                        type="warning"-->
                      <!--                        @click="disposition(row)"-->
                      <!--                      >-->
                      <!--                        处置-->
                      <!--                      </el-link>-->
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="handleDetailPage(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 {getSorterDirection, refineRequestBody} from '@/utils/requestWrappers'
import pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import SearchCommon from '@/components/SearchCommon/index.vue'
import {
  checkInPointInformation,
  tableData,
  tableEdit,
  uncheckedPointInformation
} from '@/api/patrolAndRescue/roadWatch/abnormalHandling'
import PubSub from 'pubsub-js'
import {dictionaryEscape, getDictionaryByCode} from '@/utils/dictionary'
import {tableDelete} from '@/api/patrolAndRescue/roadWatch/inspectionResults'

export default {
  name: 'TablePage',
  components: {
    pagination,
    SearchCommon
  },
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  mixins: [TableMixin],
  data() {
    return {
      activeName: 'first',
      pubSub: null,
      tableMaxHeight: '600px',
      tableLoading: true,
      treeLoading: true,
      btnLoading: false,
      treeData: [], //左边树
      tabList: ['政策法规'], //左边tab
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      taskId: '',
      optionList: [
        {
          title: '处置情况',
          prop: 'handle_status_',
          type: 'select',
          option: getDictionaryByCode('ycclzt'),
          multiple: true,
          default: true
        },
        {
          title: '点位类型',
          prop: 'TYPE_',
          type: 'select',
          option: getDictionaryByCode('xcdwlx'),
          multiple: true
        },
        {
          title: '方向',
          prop: 'DIRECTION_',
          type: 'select',
          option: getDictionaryByCode('xsfx'),
          multiple: true
        }
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 'handle_status_'},
          {operation: 'IN', property: 'TYPE_'},
          {operation: 'IN', property: 'DIRECTION_'},
          {operation: 'EQUAL', property: 'taskId'}
        ],
        sorter: [{direction: '', property: 'typeId'}]
      }
    }
  },
  created() {
    this.loadData()
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      this.activeName = 'first'
      if (data.id) {
        this.taskId = data.id
        this.params.querys[3].value = data.id
        this.loadData()
      }
    })
  },
  methods: {
    dictionaryEscape,
    getSorterDirection,
    datePickerChange() {
      this.params.pageBean.page = 1
      this.loadData()
    },
    //获取数据
    async loadData() {
      try {
        this.tableLoading = true
        let params = {}
        if (this.activeName === 'first') {
          params = {...this.params}
        } else if (this.activeName === 'second') {
          params = {
            pageBean: {pageSize: 20, page: 1, total: 0},
            querys: [
              {operation: 'EQUAL', property: 'taskId', value: this.taskId}
            ],
            sorter: [{direction: '', property: ''}]
          }
        } else {
          params = {
            pageBean: {pageSize: 20, page: 1, total: 0},
            querys: [
              {operation: 'EQUAL', property: 'td.task_id_', value: this.taskId}
            ],
            sorter: [{direction: '', property: ''}]
          }
        }

        const apiMap = {
          first: tableData,
          second: checkInPointInformation,
          default: uncheckedPointInformation
        }
        const {
          total = 0,
          rows = []
        } = await (apiMap[this.activeName] || apiMap.default)(refineRequestBody(params))
        // let results = {}
        // if (this.activeName === 'first') {
        //   results = await tableData(refineRequestBody(params))
        // } else if (this.activeName === 'second') {
        //   results = await checkInPointInformation(refineRequestBody(params))
        // } else {
        //   results = await uncheckedPointInformation(refineRequestBody(params))
        // }
        // const {total = 0, rows = []} = results
        this.params.pageBean.total = total
        this.tableData = rows
      } finally {
        this.tableLoading = 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(_ => _)
    },

    // 处置
    disposition(row = {}) {
      this.$confirm('确定处置当前的异常查询吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.btnLoading = true
          try {
            const {state} = await tableEdit({
              ...row,
              taskId: this.taskId,
              handleStatus: row?.handleStatus === '1' ? '0' : '1'
            })
            if (state) {
              this.$message.success(`处置成功`)
              await this.loadData()
            }
          } finally {
            this.btnLoading = false
          }
        })
        .catch(_ => _)
      // if (this.clickTimer) return (this.clickTimer = false)
      // this.changePage('DispositionPage', row)
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return

      this.$emit(
        'changePage',
        pageName,
        _ => {
          PubSub.publish(pageName, row)
        },
        row.id ? '编辑' : '添加'
      )
    },
    handleClick() {
      this.params.pageBean.page = 1
      // 重置搜索条件
      if (this.activeName === 'first') {
        this.params.querys[0].value = []
        this.params.querys[1].value = []
        this.params.querys[2].value = []
      }
      this.loadData()
    }
  },
  beforeDestroy() {

    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
::v-deep.el-tabs {
  height: 55px;
}

.table-page {
  .basis {
    min-width: 400px !important;
  }
}
</style>
