<script setup lang="ts">
import { Plus, Download, Upload, Delete } from '@element-plus/icons-vue'
import AppList from '@/components/base/AppList.vue'
import { getMemberList, deleteMember, getMemberConnectionsList, syncMember, clearMember } from '../api'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { MemberProp, ConnectionsProp } from '../types'
import { useUserStore } from '@/stores/user'
import { useStorage } from '@vueuse/core'

const userStore = useUserStore()

const UpdateDialog = defineAsyncComponent(() => import('../components/UpdateDialog.vue'))
const UploadEventsDialog = defineAsyncComponent(() => import('../components/UploadEventsDialog.vue'))
const UploadUserDialog = defineAsyncComponent(() => import('../components/UploadUserDialog.vue'))
const ViewProgressDialog = defineAsyncComponent(() => import('../components/ViewProgressDialog.vue'))
const ViewGenerateEventData = defineAsyncComponent(() => import('@/components/ViewGenerateEventData.vue'))
const ListColumnOptions = defineAsyncComponent(() => import('../components/ListColumnOptions.vue'))

const router = useRouter()

const route = useRoute()

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

// 链接列表（所属链接选项）
let connectionOptions = $ref<ConnectionsProp[]>()
const getConnectionsList = function () {
  getMemberConnectionsList().then((res: { data: ConnectionsProp[] }) => {
    connectionOptions = res.data
  })
}
getConnectionsList()

const defaultFields = [
  { label: '用户ID', prop: 'id' },
  { label: '姓名', prop: 'name' },
  { label: '性别', prop: 'gender_name' },
  { label: '手机号码', prop: 'mobile' },
  { label: '来源连接', prop: 'connection_name' },
]

const selectedFields = useStorage('userListColumns', [
  { label: '用户ID', prop: 'id' },
  { label: '姓名', prop: 'name' },
  { label: '性别', prop: 'gender_name' },
  { label: '手机号码', prop: 'mobile' },
  { label: '来源连接', prop: 'connection_name' },
])
// 列表配置
const listOptions = computed(() => {
  return {
    remote: {
      httpRequest: getMemberList,
      params: { name: '', id: '', mobile: '', status: '', experiment_connection_id: '' },
    },
    filters: [
      { type: 'input', prop: 'name', placeholder: '请输入用户姓名' },
      { type: 'input', prop: 'id', placeholder: '请输入用户ID' },
      { type: 'input', prop: 'mobile', placeholder: '请输入用户手机号' },
      {
        type: 'select',
        prop: 'status',
        placeholder: '请选择生效状态',
        options: [
          { label: '有效', value: '1' },
          { label: '失效', value: '0' },
        ],
      },
      {
        type: 'select',
        prop: 'experiment_connection_id',
        placeholder: '请选择来源链接',
        options: connectionOptions,
        labelKey: 'type_name',
        valueKey: 'id',
      },
    ],
    columns: [
      { type: 'selection' },
      { label: '序号', type: 'index', width: 60 },
      ...selectedFields.value,
      {
        label: '状态',
        prop: 'status_name',
        computed: (row: any) => {
          return row.row.status === '0'
            ? `<span style="color: rgb(170, 2, 49)">${row.row.status_name}</span>`
            : `<span style="color: #00ac27">${row.row.status_name}</span>`
        },
      },
      { label: '更新人', prop: 'updated_operator_name' },
      { label: '更新时间', prop: 'updated_time' },
      { label: '操作', slots: 'table-x', width: 380 },
    ],
  }
})

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

// 导入事件弹窗
const eventsVisible = $ref(false)

// 导入用户弹窗
const userVisible = $ref(false)

// 新建、更新、查看
let updateVisible = $ref(false)

// 新建、更新、查看
const progressVisible = $ref(false)

let multipleSelection = $ref<MemberProp[]>([])
function handleSelectionChange(selection: MemberProp[]) {
  multipleSelection = selection
}

// 删除
const handleRemove = function (row: { id: string; have_event: boolean }) {
  if (row.have_event) {
    ElMessageBox.confirm('此操作将会删除用户及所有关联事件数据', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteMembers({ ids: row.id })
    })
  } else {
    deleteMembers({ ids: row.id })
  }
}
const handleRemoves = function (isAll?: boolean) {
  const ids = multipleSelection.map((item) => item.id).join(',')
  if (isAll) {
    ElMessageBox.confirm('确定要删除全部用户数据吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteMembers({ type: 'all' })
    })
  } else {
    ElMessageBox.confirm('确定要删除选中的用户数据吗？', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteMembers({ ids })
    })
  }
}

let loading = $ref<any>()
const deleteMembers = function (params: any) {
  loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  deleteMember(params).then(() => {
    loading.close()
    ElMessage({ message: '删除成功', type: 'success' })
    handleRefresh()
  })
}

// 编辑
const currentRow = ref<MemberProp>()
const handleEdit = function (row: MemberProp) {
  currentRow.value = row
  row.isView = false
  updateVisible = true
}

// 查看
const handleView = function (row: MemberProp) {
  row.isView = true
  currentRow.value = row
  updateVisible = true
}

// 新建
const handleAdd = function () {
  updateVisible = true
  currentRow.value = undefined
}

// 事件详情页
const goPage = function (row: MemberProp) {
  router.push({
    path: '/user/eventDetails',
    query: { user_id: row.id },
  })
}

// 画像
const handleImage = function (row: MemberProp) {
  router.push({
    path: '/user/image',
    query: { user_id: row.id },
  })
}

// 导出用户
const downloadMember = function (isAll?: boolean) {
  const ids = multipleSelection
    .reduce((a: any, b: any) => {
      a.push(b.id)
      return a
    }, [])
    .toString()
  if (isAll) {
    window.open(`/api/lab/v1/experiment/member/download?experiment_id=${route.query.experiment_id}`)
  } else {
    window.open(`/api/lab/v1/experiment/member/download?experiment_id=${route.query.experiment_id}&ids=${ids}`)
  }
}

const generateEventVisible = ref(false)
// 同步用户和事件数据
const handleSync = async () => {
  await syncMember()
  ElMessage({ message: '同步成功', type: 'success' })
  handleRefresh()
}

const handleClear = async () => {
  await ElMessageBox.confirm('确定要清空用户数据吗？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await clearMember()
  ElMessage({ message: '清空成功', type: 'success' })
  handleRefresh()
}
</script>

<template>
  <AppCard>
    <AppList v-bind="listOptions" ref="appList" @selection-change="handleSelectionChange">
      <template #header-buttons>
        <el-row justify="space-between">
          <el-space>
            <el-button
              v-if="!userStore.status.status"
              type="primary"
              :icon="Plus"
              @click="handleAdd"
              v-permission="'v1-experiment-member-create'"
              >新建</el-button
            >
            <el-button v-if="userStore.status.status" type="primary" @click="handleSync">同步用户和事件数据</el-button>

            <el-dropdown v-permission="'v1-experiment-member-download'">
              <el-button type="primary" :icon="Download">导出</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="downloadMember(true)">全部用户数据</el-dropdown-item>
                  <el-dropdown-item :disabled="!multipleSelection.length" @click="downloadMember(false)"
                    >勾选用户数据</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <!-- v-permission="['v1-experiment-member-member-upload', 'v1-experiment-member-event-upload']" -->
            <el-dropdown v-if="!userStore.status.status">
              <el-button type="primary" :icon="Upload">导入</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="userVisible = true">用户数据</el-dropdown-item>
                  <el-dropdown-item @click="eventsVisible = true">用户事件数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button
              type="primary"
              v-if="!userStore.status.status"
              @click="progressVisible = true"
              v-permission="'v1-experiment-member-tasks'"
              >数据导入进度</el-button
            >
            <!-- <el-button type="danger" plain :icon="Delete" :disabled="!multipleSelection.length" @click="handleRemoves()" v-permission="'v1-experiment-member-delete'">删除</el-button> -->
            <!-- v-permission="'v1-experiment-member-delete'" -->
            <el-dropdown>
              <el-button type="danger" :icon="Delete">删除</el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleRemoves(true)">删除全部用户</el-dropdown-item>
                  <el-dropdown-item :disabled="!multipleSelection.length" @click="handleRemoves(false)"
                    >删除勾选用户</el-dropdown-item
                  >
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="danger" @click="handleClear" v-if="userStore.role?.id == 1">清空数据</el-button>
          </el-space>
          <el-space>
            <router-link to="/analyze/user"><el-button type="primary">用户分析</el-button></router-link>
            <el-button type="primary" @click="generateEventVisible = true">用户事件数据</el-button>
            <ListColumnOptions :fields="defaultFields" />
          </el-space>
        </el-row>
      </template>
      <template #table-x="{ row }">
        <el-button type="primary" plain @click="handleImage(row)">画像</el-button>
        <el-button type="primary" plain @click="handleView(row)">查看</el-button>
        <el-button type="primary" plain @click="handleEdit(row)" v-permission="'v1-experiment-member-update'"
          >编辑</el-button
        >
        <el-button type="primary" plain @click="handleRemove(row)" v-permission="'v1-experiment-member-delete'"
          >删除</el-button
        >
        <el-button type="primary" plain @click="goPage(row)">事件</el-button>
      </template>
    </AppList>
  </AppCard>
  <!-- 导入事件弹窗 -->
  <UploadEventsDialog @update="handleRefresh" v-if="eventsVisible" v-model="eventsVisible"></UploadEventsDialog>
  <!-- 导入用户弹窗 -->
  <UploadUserDialog @update="handleRefresh" v-if="userVisible" v-model="userVisible"></UploadUserDialog>
  <!-- 新建、更新、查看 -->
  <UpdateDialog v-if="updateVisible" :data="currentRow" v-model="updateVisible" @update="handleRefresh"></UpdateDialog>
  <!-- 查看上传 -->
  <ViewProgressDialog v-if="progressVisible" v-model="progressVisible"></ViewProgressDialog>
  <!-- 用户事件数据 -->
  <ViewGenerateEventData v-model="generateEventVisible" v-if="generateEventVisible"></ViewGenerateEventData>
</template>
