<script setup lang="ts">
import { delUser, userList } from 'apis/user'
import Edit from 'components/user/Edit/index.vue'
import { ElMessageBox } from 'element-plus'
import { FtMessage } from 'libs/message'
import { cloneDeep } from 'lodash'
import { useSystemStore } from 'stores/systemStore'
import { useTemplateRef } from 'vue'

const systemStore = useSystemStore()

const btnList = systemStore.systemStatus.currentUser?.fixedUser === 'ENABLE'
  ? [
      {
        name: '新增',
        type: 'primary',
        serverUrl: 'add',
        serverCondition: 0,
      },
      {
        name: '编辑',
        type: 'primary',
        serverUrl: 'edit',
        serverCondition: 1,
      },
      {
        name: '删除',
        type: 'danger',
        serverUrl: 'del',
        serverCondition: 2,
      },
    ]
  : []
const columns = [
  {
    type: 'selection',
    selectable: (row: any) => {
      return (row.fixedUser !== 'ENABLE') || row.username === systemStore.systemStatus.currentUser?.username
    },
  },
  {
    title: '账号',
    key: 'username',
  },
  {
    title: '用户名',
    key: 'nickname',
  },
]

const tableRef = useTemplateRef('tableRef')

const del = async (selectedRows: any) => {
  const ids = selectedRows.map((item: any) => item.id)
  await ElMessageBox.confirm('确定删除当前选中的行?', '消息', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
  await delUser(ids)
  FtMessage.success('删除成功')
  tableRef.value?.initData()
}

const addVisible = ref(false)

const currentData = ref({})
const addHandle = () => {
  currentData.value = {}
  addVisible.value = true
}

const editHandle = (data: any) => {
  currentData.value = cloneDeep(data[0])
  console.log(currentData.value)
  addVisible.value = true
}
</script>

<template lang="pug">
  div
    FtTable(ref="tableRef", has-header, has-page, :columns="columns", :btn-list="btnList", :get-data-fn="userList", @add="addHandle", @edit="editHandle", @del="del")
    Edit(v-if="addVisible", :data="currentData", @ok="addVisible = false;tableRef?.initData()", @cancel="addVisible = false")
</template>
