<script setup lang="ts">
import { type VxeGridInstance, type VxeGridProps } from 'vxe-table'
import { useRowClickStyle } from '@/hooks/rowClickStyle'
import { formatTimezone } from '@/utils/tools'
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useVisitedRowState } from '@/stores/modules/visitedRow'

const visitedRowState = useVisitedRowState()
const router = useRouter()
interface ColumnsListItem {
  field: String
  title: String
  type: String
  formatter: String
}
const props = defineProps({
  propsType: Boolean,
  ColumnsList: Array<ColumnsListItem>
})

const columnstest = ref(props.ColumnsList)

const tableData = ref<VxeGridProps<any>>({
  border: true,
  round: true,
  minHeight: 70,
  maxHeight: 500,
  columns: [],
  data: [],
  scrollY: { enabled: true, oSize: 20, gt: 30 },
  stripe: true,
  emptyText: ' ',
  showHeaderOverflow: true,
  showOverflow: true,
  headerRowStyle: {
    backgroundColor: 'var(--color-table-header-bg)'
  },
  columnConfig: { resizable: true, useKey: true },
  rowConfig: { isHover: true }
})
const pageInfo = ref({ pageNo: 1, pageSize: 10, total: 0 })

const tableRef = ref<VxeGridInstance | null>(null)

const handleColumns = (columns: any) => {
  const newColumns = columns.map((item: any) => {
    let curColumn: any = {
      title: item.title,
      field: item.field
    }
    // 格式化
    if (item.formatter === 'date') {
      curColumn = {
        ...curColumn,
        formatter: ({ cellValue }: any) => formatTimezone(cellValue)
      }
    }  else if (item.type === 'link') {
      curColumn = {
        ...curColumn,
        slots: { default: 'trackingNo' }
      }
    }
    return curColumn
  })
  return newColumns
}
// 获取表格列
const getTableColumns = async () => {
  tableData.value.columns = handleColumns(columnstest.value)
  if (props.propsType) {
    tableData.value.columns?.push({
      title: 'Action',
      fixed: 'right',
      width: 80,
      slots: { default: 'action' }
    })
  }
}
// 获取表格数据
const getTableData = (val: any) => {
  tableData.value.data = val.tableData
  if (!props.propsType) {
    pageInfo.value.pageNo = val.cp
    pageInfo.value.pageSize = val.ps
    pageInfo.value.total = val.rc
  }
}

// 实现行点击样式
useRowClickStyle(tableRef)

const emits = defineEmits(['deleteAddedRules'])
// 点击删除
const handleDelete = (row: any) => {
  row.visible = false
  $api
    .DeleteAddedRules({
      rules_type: row.Event
    })
    .then((res: any) => {
      if (res.code === 200) {
        tableData.value.data = tableData.value.data?.filter((item) => item.Event !== row.Event)
        emits('deleteAddedRules', row.Event)
      }
    })
}

// 点击link字段
const handleLinkClick = (row: any) => {
  console.log(row)
  router.push({
      path: '/tracking/detail',
      query: { a: row.__serial_no, _schemas: row._schemas }
    })
    visitedRowState.setTrackingTableData(row['__serial_no'])
}

onMounted(() => {
  getTableColumns()
})
defineExpose({
  getTableData
})
const getpaginationTableData = () => {
  $api
    .SubscribePagination({
      cp: pageInfo.value.pageNo,
      ps: pageInfo.value.pageSize
    })
    .then((res: any) => {
      if (res.code === 200) {
        pageInfo.value.total = Number(res.data.rc)
        pageInfo.value.pageNo = res.data.cp
        pageInfo.value.pageSize = res.data.ps
        tableData.value.data = res.data.tableData
      }
    })
}
</script>

<template>
  <div class="SettingTable">
    <vxe-grid
      :class="props.propsType ? 'radius-bottom' : ''"
      ref="tableRef"
      :style="{ border: 'none' }"
      v-bind="tableData"
    >
      <template #empty>
        <div class="empty">No data</div>
      </template>
      <!-- Tracking No字段的插槽 -->
      <template #trackingNo="{ row, column }">
        <span
          style="color: var(--color-theme); cursor: pointer"
          @click="handleLinkClick(row)"
        >
          {{ row[column.field] }}
        </span>
      </template>
      <template #action="{ row }">
        <el-popover :visible="row.visible" placement="left" :width="480">
          <div class="delete_title">
            <span class="font_family icon_alert icon-icon_tipsfilled_b"></span>
            Delete Rules
          </div>
          <p class="delete_content">Are you sure to delete this notification event?</p>
          <div style="text-align: right; margin: 0; padding: 8px">
            <el-button style="width: 100px" tupe="default" @click="row.visible = false"
              >cancel</el-button
            >
            <el-button style="width: 100px" type="warning" @click="handleDelete(row)">
              OK
            </el-button>
          </div>
          <template #reference>
            <el-button @click="row.visible = true" class="el-button--blue" style="height: 24px">
              <span class="font_family icon-icon_delete_b"></span>
            </el-button>
          </template>
        </el-popover>
      </template>
    </vxe-grid>
  </div>
  <div class="pagination" v-if="!props.propsType">
    <span>Total {{ pageInfo.total }}</span>
    <el-pagination
      v-model:current-page="pageInfo.pageNo"
      v-model:page-size="pageInfo.pageSize"
      layout="prev, pager, next"
      :total="pageInfo.total"
      :pager-count="5"
      @size-change="getpaginationTableData"
      @current-change="getpaginationTableData"
      background
    />
  </div>
</template>

<style lang="scss" scoped>
.SettingTable {
  padding: 0 24px 0 24px;
}
.radius-bottom {
  border-radius: 6px 6px 0 0;
}
.font_family::before {
  color: var(--color-btn-danger-bg);
}
.icon_alert::before {
  color: var(--color-btn-warning-bg);
}
.delete_title {
  font-size: 18px;
  font-weight: 700;
  padding: 20px 16px;
  color: var(--color-neutral-1);
}
.delete_content {
  font-size: 14px;
  font-weight: 400;
  color: var(--color-neutral-1);
  padding: 15px 0 33px 37px;
}
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid var(--color-border);
  border-top: none;
  margin: 0 24px 20px 24px;
  padding: 4px 8px;
  border-radius: 0 0 6px 6px;
}
:deep(.el-icon svg) {
  width: 1em !important;
}
</style>
