<template>
  <div class="table-page">
    <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 ref="btnPanel" class="btn-box"></div>
            <div class="search-box-combination">
              <div>
                <el-date-picker
                  v-model="params.querys[2].value"
                  :default-time="['00:00:00', '23:59:59']"
                  end-placeholder="来电时间（结束）"
                  range-separator="至"
                  start-placeholder="来电时间（开始）"
                  style="width: 360px"
                  type="datetimerange"
                  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="tableRef" class="table-content">
                <el-table
                  ref="multipleSelection"
                  v-loading="tableLoading"
                  :data="tableData"
                  :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"
                >
                  <el-table-column align="center" type="selection" width="55" />
                  <el-table-column
                    align="center"
                    label="序号"
                    type="index"
                    width="60"
                  />
                  <el-table-column
                    :formatter="({roadName}) => roadName || '-'"
                    align="center"
                    label="所属路段"
                    min-width="80"
                    prop="roadName"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({leadtype}) => leadtype || '-'"
                    align="center"
                    label="来电类型"
                    min-width="80"
                    prop="complaintSource"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({subordinate}) => subordinate || '-'"
                    align="center"
                    label="来电子类型"
                    min-width="80"
                    prop="subordinate"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({username}) => username || '-'"
                    align="center"
                    label="主持名称"
                    min-width="80"
                    prop="username"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({phone}) => phone || '-'"
                    align="center"
                    label="来电号码"
                    min-width="80"
                    prop="phone"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({duration}) => duration || '-'"
                    align="center"
                    label="通话时长 （秒）"
                    min-width="80"
                    prop="duration"
                    show-overflow-tooltip
                  />
                  <el-table-column
                    :formatter="({calltime}) => calltime || '-'"
                    align="center"
                    label="来电时间"
                    min-width="80"
                    prop="calltime"
                    show-overflow-tooltip
                  />

                  <!-- <el-table-column
                    align="center"
                    label="操作"
                    min-width="80"
                    show-overflow-tooltip
                  >
                    <template v-slot="{row}">
                      <el-link
                        :underline="false"
                        type="primary"
                        @click="handleDetailPage(row)"
                      >
                        详情
                      </el-link>
                      <el-link
                        :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 {refineRequestBody, setQueryValue} from '@/utils/requestWrappers'
import pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import treeSide from '@/components/treeSide/index.vue'
import SearchCommon from '@/components/SearchCommon/index.vue'
import {getTree} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/patrolAndRescueVehicleMgmt'
import {tableData} from '@/api/patrolAndRescue/operationalMonitoring/intelligentSeat'
import PubSub from 'pubsub-js'
import {dictionaryEscape} from '@/utils/dictionary'
import {mapState} from 'vuex'
import moment from 'moment'

export default {
  name: 'TablePage',
  components: {
    pagination,
    treeSide,
    SearchCommon
  },
  mixins: [TableMixin],
  computed: {
    action: () =>
      `${window.context.portal}/monitor/bizEarlyWarningManagement/v1/importData`,
    ...mapState({
      headers: state => ({
        Authorization: `Bearer ${state.login.currentUser.token}`
      })
    })
  },
  data() {
    return {
      isAddShow: false,
      pubSub: null,
      tableMaxHeight: '600px',
      loading: false,
      treeLoading: true,
      tableLoading: false,
      treeData: [], //左边树
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      currentDataDel: [],
      optionList: [
        {
          title: '来电类型',
          prop: 'leadtype',
          type: 'select',
          option: [
            {value: '突发事件', name: '突发事件'},
            {value: '公众服务', name: '公众服务'},
            {value: '施工', name: '施工'},
            {value: '通知', name: '通知'},
            {value: '通知', name: '通知'}
          ],
          multiple: true,
          default: true
        },
        {
          title: '来电号码',
          prop: 'phone',
          type: 'input'
        }
      ],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'IN', property: 'roadId'},
          {
            group: 'quick',
            operation: 'IN',
            relation: 'AND',
            property: 'leadtype'
          },
          {
            group: 'quick',
            operation: 'BETWEEN',
            relation: 'AND',
            property: 'calltime',
            value: [
              moment().format('YYYY-MM-DD 00:00:00'),
              moment().format('YYYY-MM-DD 23:59:59')
            ]
          },
          {
            group: 'quick',
            operation: 'LIKE',
            relation: 'AND',
            property: 'phone'
          }
        ],
        sorter: [{direction: 'DESC', property: 'calltime'}]
      },
      treeDialog: false, // 科目信息弹层
      treeItemId: '', // 树形目录id
      treeItem: {}, // 树形节点选中对象
      btnLoading: false
    }
  },
  created() {
    // 获取树形目录-
    this.getOrgTreeData(treeData => {
      // 回调中默认选中第一项并将其id作为参数请求表格
      this.treeItem = treeData[0] || {}
      let array = []
      if (this.treeItem.children.length > 0) {
        array = this.treeItem.children.map(item => item.id)
      }
      this.$nextTick(_ => {
        this.$refs.treeSide?.setCurrentKey(treeData[0]?.id) //通过 $refs 获取treeSide组件引用，并调用 setCurrentKey方法设置当前选中的树节点。
        this.$refs.treeSide?.expandHandle(true, 2)
      })
      setQueryValue(this.params, 'roadId', array)
      this.loadData() //加载表格数据
    })
  },
  mounted() {
    this.pubSub = PubSub.subscribe('TablePage', (_, data) => {
      switch (data.type) {
        case 'add':
          this.params.pageBean.page = 1
          this.loadData()
          break
        case 'edit':
          this.loadData()
          break
      }
    })
  },
  methods: {
    dictionaryEscape,
    // 时间范围切换
    datePickerChange(val) {
      let date = []
      if (val && val.length > 0) {
        let [start, end] = val
        const startDate = moment(start).format('YYYY-MM-DD HH:mm:ss')
        const endDate = moment(end).format('YYYY-MM-DD HH:mm:ss')
        date = [startDate, endDate]
      }
      setQueryValue(this.params, 'calltime', date)
      this.params.pageBean.page = 1
      this.loadData()
    },
    // 获取公司树-异步方法，用于从后端获取树形数据
    async getOrgTreeData(callback) {
      try {
        this.treeLoading = true //开始加载时显示加载状态
        let {value} = await getTree() // 调用 API 获取树形数据
        this.treeData = this.transformTreeData(value)
      } finally {
        this.treeLoading = false // 无论成功或失败，都关闭加载状态
        callback && callback(this.treeData) // 如果提供了回调函数，则调用它并传入树形数据
      }
    },
    transformTreeData(data) {
      return data.map(item => ({
        id: item.id,
        name: item.name, // 一级目录的 label
        children: item.roadList.map(grid => ({
          id: grid.id,
          name: grid.name, // 二级目录的 label
          path: grid.path
        }))
      }))
    },
    //左边树节点
    currentChange(nodeItem) {
      // 判断是否是一级目录（有 children 属性）
      if (nodeItem.children && nodeItem.children.length > 0) {
        this.isAddShow = false
        const array = nodeItem.children.map(item => item.id)
        setQueryValue(this.params, 'roadId ', array)
      } else {
        this.isAddShow = true
        setQueryValue(this.params, 'roadId ', [nodeItem?.id] || [])
      }
      // setQueryValue(this.params, 'roadId', nodeItem?.id || '')
      this.treeItem = nodeItem || {}
      this.calcTableHeight(500)
      PubSub.publish('TreeItemSelected', {
        id: nodeItem?.id || '',
        name: nodeItem?.name || '',
        path: nodeItem?.path || ''
      })
      this.params.pageBean.page = 1
      this.loadData()
    },
    //获取数据
    async loadData() {
      this.tableLoading = true
      const {total = 0, rows = []} = await tableData(
        refineRequestBody(this.params)
      )
      this.params.pageBean.total = total
      this.tableData = rows.map(row => ({
        ...row,
        roadName: row.roadName || this.treeItem.name
      }))
      this.tableLoading = false
    },

    // 删除
    handleDelete(row) {
      this.clickTimer = true
      this.$confirm('确定删除选中投诉台账吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let ids = row ? row.id : this.currentDataDel.join()
          let {state, message} = 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()
          } else {
            this.$message.error(message)
          }
        })
        .catch(_ => _)
    },

    //修改
    handleDbClick(row) {
      if (this.clickTimer) return (this.clickTimer = false)
      const payload = {
        ...row,
        roadName: row.roadName || this.treeItem.name
      }
      this.changePage('EditAddPage', payload)
    },

    // 模块下载
    async templateDownload() {
      this.btnLoading = true
      try {
        await complaintTemplateDownload()
      } finally {
        this.btnLoading = false
      }
    },
    // 导出数据
    async exportData() {
      this.btnLoading = true
      try {
        // await exportFile({ ...this.searchFrom, deptId: this.treeNode.id });
        // this.$message.success(`数据导出成功`);
      } finally {
        this.btnLoading = false
      }
    },

    //  导入文件上传前
    beforeUpload(file) {
      return new Promise((resolve, reject) => {
        this.uploadLoading = this.$loading({
          lock: true,
          text: '导入文件中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const {size, name} = file
        this.$confirm(`请确认是否上传 “${name}” 为附件？`, '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(_ => {
            const maxSize = 500 * 1024 * 1024 // 500MB
            const typeRegular = /\.(xls|xlsx)$/i
            const verification = [
              {
                condition: !typeRegular.test(name),
                result: () => this.$message.error('只能上传xls或xlsx文件类型')
              }
              // {
              //   condition: size > maxSize,
              //   result: () => this.$message.warning("附件大小不能超过500MB"),
              // },
            ]
            // 是否通过验证
            const passedOrNot = !verification.some(item => {
              if (item.condition) {
                this.uploadLoading?.close()
                setTimeout(() => item.result(), 0)
              }
              return item.condition
            })
            passedOrNot ? resolve() : reject()
          })
          .catch(_ => {
            reject()
            this.uploadLoading?.close()
          })
      })
    },

    // 导入文件上传成功
    async handleSuccess(res = {}) {
      const {code = 200} = res
      if (code === 200) {
        this.search()
        this.$message.success(`文件上传成功`)
      } else {
        this.$message.error('文件上传失败，请重试..')
      }
      this.uploadLoading?.close()
    },

    // 导入文件上传失败
    handleError() {
      this.$message.error('文件上传失败，请重试..')
      this.uploadLoading?.close()
    },

    // 改变页面
    changePage(pageName = '', row = {}) {
      if (!pageName) return
      const payload = row.id
        ? row
        : {
          catalogId: this.treeItem.id,
          roadName: this.treeItem.name,
          path: this.treeItem.path
        }
      this.$emit(
        'changePage',
        pageName,
        _ => {
          PubSub.publish(pageName, payload)
        },
        row.id ? '编辑' : '添加'
      )
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped></style>
