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

const router = useRouter()

const emits = defineEmits(['gettabledatalength'])

const columnstest = ref([
  {
    field: '_rules_type_display',
    title: 'Event',
    type: 'link',
    formatter: ''
  },
  {
    field: 'shipment_details',
    title: 'Shipment Range',
    type: 'normal',
    formatter: ''
  },
  {
    field: 'event_details',
    title: 'Event Details',
    type: 'normal',
    formatter: ''
  },
  {
    field: 'frequency_display',
    title: 'Frequency',
    type: 'normal',
    formatter: ''
  },
  {
    field: 'method_display',
    title: 'Methods',
    type: 'normal',
    formatter: ''
  }
])
const datatest = ref([])
const tableData = ref<VxeGridProps<any>>({
  border: true,
  round: true,
  minHeight: 660,
  maxHeight: 660,
  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 tableRef = ref<VxeGridInstance | null>(null)
const pageInfo = ref({ pageNo: 1, pageSize: 15, total: 0 })

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)
  tableData.value.columns?.push({
    title: 'Operation',
    fixed: 'right',
    width: 100,
    slots: { default: 'action' }
  })
}
// 获取表格数据
const getTableData = async () => {
  // 保存页长以及当前页码
  tableData.value.data = datatest.value
  $api
    .MonitoringTable({
      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.monitoringRules
        emits('gettabledatalength', res.data.monitoringRules.length)
      }
    })
    .finally(() => {})
}

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

// 点击删除
const handleDelete = (row: any) => {
  row.visible = true
}

// 跳转Create New Rule页面
const ToCreateRule = () => {
  router.push({
    path: '/SystemSettings/createnewrule',
    query: {}
  })
  sessionStorage.setItem('activeTab', 'Monitoring Settings')
}

// 删除表格数据
const deleteMoniTable = (row: any) => {
  row.visible = false
  $api
    .deleteMonitoringTable({
      id: row.id
    })
    .then((res: any) => {
      if (res.code === 200) {
        tableData.value.data = tableData.value.data?.filter((item) => item.id !== row.id)
        emits('gettabledatalength', tableData.value.data?.length)
      }
    })
}

// 编辑表格数据
const handleedit = ({ row }: any) => {
  sessionStorage.setItem('activeTab', 'Monitoring Settings')
  sessionStorage.setItem('editTableid', row.id)
  sessionStorage.setItem('editTablerules_type', row.rules_type)
  sessionStorage.setItem('editTableoption', row.notifications_option)
  router.push({
    path: '/SystemSettings/createnewrule',
    query: {}
  })
}

const handleedittow = (row: any) => {
  sessionStorage.setItem('activeTab', 'Monitoring Settings')
  sessionStorage.setItem('editTableid', row.id)
  sessionStorage.setItem('editTablerules_type', row.rules_type)
  sessionStorage.setItem('editTableoption', row.notifications_option)
  router.push({
    path: '/SystemSettings/createnewrule',
    query: {}
  })
}

onMounted(() => {
  getTableColumns()
  getTableData()
})
</script>

<template>
  <div class="SettingTable">
    <vxe-grid
      ref="tableRef"
      :style="{ border: 'none' }"
      v-bind="tableData"
      @cell-dblclick="handleedit"
    >
      <!-- 空数据时的插槽 -->
      <template #empty v-if="tableData.data.length === 0">
        <TableEmpty EmptyTitle="Customize your shipment tracking preferences.">
          <template #suggestion>
            <el-button class="el-button--main" @click="ToCreateRule">+ Add Rule</el-button>
          </template>
        </TableEmpty>
      </template>
      <!-- Tracking No字段的插槽 -->
      <template #trackingNo="{ row, column }">
        <span
          style="color: var(--color-theme); cursor: pointer"
          @click="handleedittow(row)"
        >
          {{ row[column.field] }}
        </span>
      </template>
      <template #action="{ row }">
        <el-button class="el-button--blue" style="height: 24px" @click="handleedittow(row)">
          <span class="font_family icon-icon_edit_b"></span>
        </el-button>
        <el-popover trigger="click" :visible="row.visible" placement="left" :width="480">
          <div class="delete_title">
            <span class="font_family icon_alert icon-icon_tipsfilled_b"></span>
            Delete Rule
          </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" class="el-button--default" @click="row.visible = false"
              >cancel</el-button
            >
            <el-button style="width: 100px" type="warning" @click="deleteMoniTable(row)">
              OK
            </el-button>
          </div>
          <template #reference>
            <el-button @click="handleDelete(row)" 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">
    <span>Total {{ formatNumber(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="getTableData"
      @current-change="getTableData"
      background
    />
  </div>
</template>

<style lang="scss" scoped>
.SettingTable {
  padding: 0 24px 0 24px;
}
.icon-icon_delete_b::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 0 24px;
  padding: 4px 8px;
  border-radius: 0 0 6px 6px;
}
:deep(.el-icon svg) {
  width: 1em !important;
}

:deep(.vxe-table--empty-placeholder) {
  height: 500px !important;
}
</style>
