<template>
  <div class="table-page">
    <div class="table-page-content">
      <div class="right-table">
        <div class="full-page bg">
          <div class="search-box">
            <div ref="btnPanel" class="btn-box">
              <el-button class="btn btn-plus" icon="el-icon-plus" size="small"
                         type="primary" @click="changePage('EditAddPage','id')">
                添加
              </el-button>
              <el-button :disabled="!currentDataDel.length" class="btn btn-delete" icon="el-icon-delete" plain
                         size="small"
                         type="danger" @click="handleDelete()">
                删除
              </el-button>
            </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"
                          @row-dblclick="handleDbClick">
                  <el-table-column align="center" type="selection" width="55" />
                  <el-table-column align="center" label="序号" type="index" width="60" />
                  <el-table-column align="center" label="名称" min-width="80" prop="name" show-overflow-tooltip />
                  <el-table-column align="center" label="编码" min-width="80" prop="code" show-overflow-tooltip />
                  <el-table-column
                    :formatter="({ homeworkVehicles }) => dictionaryEscape('zycl', homeworkVehicles) || '-'"
                    align="center" label="车类"
                    min-width="80"
                    prop="homeworkVehicles"
                    show-overflow-tooltip />
                  <!--                  <el-table-column align="center" label="收费明细" min-width="80" prop="decimalPlaces"-->
                  <!--                                   show-overflow-tooltip />-->
                  <el-table-column align="center" label="描述" min-width="80" prop="remarks" show-overflow-tooltip />
                  <el-table-column align="center" label="操作" min-width="80" show-overflow-tooltip>
                    <template v-slot="{ row }">
                      <!-- 开关按钮 -->
                      <el-switch
                        v-model="row.status"
                        active-text="启用"
                        active-value="0"
                        class="custom-switch"
                        inactive-text="禁用"
                        inactive-value="1"
                        @change="handleSwitchChange(row)"
                      />
                    </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 pagination from '@/components/SuperPagination/index.vue'
import {TableMixin} from '@/mixins/tableMixin'
import {statuschange, tableDataa, tableDelete} from '@/api/patrolAndRescue/infoMgmtPatrolsRescues/RescueFeeCq'
import PubSub from 'pubsub-js'
import {dictionaryEscape} from '@/utils/dictionary'

export default {
  name: 'TablePage',
  components: {
    pagination
  },
  mixins: [TableMixin],
  data() {
    return {
      pubSub: null,
      tableMaxHeight: '600px',
      loading: false,
      tableLoading: false,
      tableData: [],
      currentDataDel: [],
      params: {
        pageBean: {pageSize: 20, page: 1, total: 0},
        querys: [
          {operation: 'LIKE', property: 'name', value: ''},
          {operation: 'LIKE', property: 'code', value: ''},
          {operation: 'LIKE', property: 'address', value: ''},
          {operation: 'LIKE', property: 'org_Full_Id_', value: ''}
        ],
        sorter: []
      }
    }
  },
  created() {
    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,
    //获取数据
    async loadData() {
      this.tableLoading = true
      // console.log('查询参数:', this.params) // 打印查询参数
      const reponse = await tableDataa()
      console.log(reponse, '数据数据')
      // this.params.pageBean.total = total
      console.log('API返回数据:', reponse.rows) // 查看是否有目标字段
      // 确保状态字段与字典定义一致
      this.tableData = reponse.rows.map(row => {
        row.status = String(row.status)
        return row
      })

      this.params.pageBean.total = reponse.total
      // this.tableData = reponse.rows
      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) {
      console.log(row, '双击详情数据')
      // if (this.clickTimer) return (this.clickTimer = false)
      this.changePage('EditAddPage', row)
    },

    changePage(pageName = '', row = {}) {
      if (!pageName) return
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type: 'edit', data: row})
      }, row.id ? '编辑' : '添加')
    },
    // 处理开关状态改变
    handleSwitchChange(row) {
      console.log('当前行数据:', row)
      console.log('开关状态:', row.status)
      const newStatus = row.status
      const oldStatus = newStatus === '1' ? '0' : '1' // 根据新状态反推旧状态
      const actionText = newStatus === '1' ? '禁用' : '启用' // 操作文本
      // 弹出确认框
      this.$confirm(`确定要${actionText}该条目吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户确认后调用接口
        this.updateStatus(row.id, newStatus)
      }).catch(() => {
        // 用户取消后恢复原状态
        row.status = oldStatus
      })
      // 仅在切换为禁用时弹出确认框
      // if (newStatus === '1') {
      //   this.$confirm('确定要禁用该条目吗？', '提示', {
      //     confirmButtonText: '确定',
      //     cancelButtonText: '取消',
      //     type: 'warning'
      //   }).then(() => {
      //     this.updateStatus(row.id, newStatus) // 用户确认后调用接口
      //   }).catch(() => {
      //     row.status = oldStatus // 用户取消后恢复原状态
      //   })
      // } else {
      //   this.updateStatus(row.id, newStatus) // 启用时直接调用接口
      // }
      // 这里可以调用 API 更新服务器状态

    },
    async updateStatus(id, flag) {
      try {
        // 创建 FormData 对象
        const formData = new FormData()
        formData.append('flag', flag) // 添加 flag 参数
        formData.append('ids', String(id)) // 添加 ids 参数，确保是字符串格式

        // 调用接口
        const response = await statuschange(formData)

        if (response.state) {
          this.$message.success('状态更新成功')
          // 更新本地数据状态
          const targetRow = this.tableData.find(row => row.id === id)
          if (targetRow) targetRow.status = flag
        } else {
          this.$message.error(response.message || '状态更新失败')
          // 接口失败时恢复状态
          const targetRow = this.tableData.find(row => row.id === id)
          if (targetRow) targetRow.status = flag === '1' ? '0' : '1'
        }
      } catch (error) {
        this.$message.error('状态更新失败')
        // 网络异常时恢复状态
        const targetRow = this.tableData.find(row => row.id === id)
        if (targetRow) targetRow.status = flag === '1' ? '0' : '1'
      }
    }
  },

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

<style lang="scss" scoped>
.custom-switch {
  /* 启用文字 - 始终绿色 */
  ::v-deep .el-switch__label--right {
    color: #67C23A !important; /* 绿色 */
  }

  /* 禁用文字 - 始终红色 */
  ::v-deep .el-switch__label--left {
    color: #F56C6C !important; /* 红色 */
  }


}
</style>
