<script setup lang="ts">
import { ElMessageBox, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import UpdateEventsDialog from '../components/UpdateEventsDialog.vue'
import { getMemberEventList, deleteEvent } from '../api'
import type { MemberProp, AttributesProp } from '../types'

const route = useRoute()

const appList = $ref<InstanceType<typeof AppList> | null>(null)

let userInfo = $ref<MemberProp>()
// 列表配置
const listOptions = computed(() => {
  return {
    remote: {
      httpRequest: getMemberEventList,
      params: { id: route.query.user_id },
      callback: (data: any) => {
        userInfo = data
        return data.events
      }
    },
    columns: [
      { label: '序号', type: 'index', width: 60 },
      { label: '事件名称', prop: 'event_name' },
      { label: '链接名称', prop: 'connection_name' },
      { label: '事件更新时间', prop: 'updated_time' },
      { label: '事件发生时间', prop: 'created_time' },
      { label: '操作', slots: 'table-x', width: 240 }
    ]
  }
})

// 刷新
function handleRefresh() {
  appList?.refetch()
}

// 事件弹窗
let eventsVisible = $ref(false)

// 编辑
let currentRow = $ref<AttributesProp>()
const handleEdit = function (row: AttributesProp) {
  row.isView = false
  currentRow = row
  eventsVisible = true
}

// 删除
function handleRemove(row: AttributesProp) {
  ElMessageBox.confirm('确定要删除该属性吗？', '提示').then(() => {
    deleteEvent({ id: row.id }).then(() => {
      ElMessage({ message: '删除成功', type: 'success' })
      handleRefresh()
    })
  })
}

// 新建
const handleAdd = function () {
  currentRow = undefined
  eventsVisible = true
}

// 查看
const handleView = function (row: AttributesProp) {
  row.isView = true
  currentRow = row
  eventsVisible = true
}
</script>

<template>
  <AppCard title="用户事件数据">
    <div class="event-user_info">
      <span>姓名：{{ userInfo?.name }}</span>
      <span>id：{{ userInfo?.id }}</span>
      <span>来源链接：{{ userInfo?.connection_name }}</span>
      <span>状态：{{ userInfo?.status_name }}</span>
    </div>
  </AppCard>
  <AppCard>
    <AppList v-bind="listOptions" ref="appList">
      <template #header-buttons>
        <el-button type="primary" :icon="Plus" @click="handleAdd">新建用户事件</el-button>
      </template>
      <template #table-x="{ row }">
        <el-button type="primary" plain @click="handleView(row)">查看</el-button>
        <el-button type="primary" plain @click="handleEdit(row)">编辑</el-button>
        <el-button type="primary" plain @click="handleRemove(row)">删除</el-button>
      </template>
    </AppList>
  </AppCard>
  <!-- 新建更新事件 -->
  <UpdateEventsDialog @update="handleRefresh()" :data="currentRow" v-if="eventsVisible" :info="userInfo" v-model="eventsVisible"></UpdateEventsDialog>
</template>
<style lang="scss">
.event-user_info {
  span {
    margin-right: 50px;
  }
}
</style>
