import { h, ref, reactive } from 'vue'
import TableAction from '@/components/DataTable/tools/Action.vue'
import { deleteDept } from '@/api/system/dept/index.js'

/* 注册table */
const tableRef = ref()
const searchParams = ref()

function handleSearch(params) {
  searchParams.value = { ...params }
  tableRef.value.reFetch({ searchParams })
}

/**
 * @description: 获取数据及操作
 * @param {*} row 单行数据
 * @param {*} type 操作类型 create:创建，preview:预览，edit:编辑
 * @return {*}
 */
function getRowData(row, type) {
  data.rowData = type === 'create' ? { pid: row.id } : row
  data.modalType = type
  data.modalShow = true
}

// 删除方法
function deleteData(id) {
  deleteDept(id)
    .then((res) => {
      if (res.code === 0) {
        handleSearch()
      }
    })
    .catch((e) => {
      console.log(e)
    })
}

const data = reactive({
  tableRef,
  searchParams,
  rowData: {},
  modalType: 'create',
  modalShow: false,
  handleSearch,

  columns: [
    {
      title: '部门编号',
      key: 'code',
      align: 'center'
    },
    {
      title: '部门名称',
      key: 'name',
      align: 'center'
    },
    {
      title: '排序',
      key: 'sort',
      align: 'center'
    },
    {
      title: '创建时间',
      key: 'createTime',
      align: 'center',
      minWidth: 120
    },
    {
      title: '更新时间',
      key: 'updateTime',
      align: 'center',
      minWidth: 120
    },
    {
      title: '操作',
      align: 'center',
      width: 150,
      fixed: 'right',
      render(row) {
        return h(TableAction, {
          actions: [
            {
              label: '添加',
              type: 'button',
              props: {
                type: 'primary',
                text: true,
                onClick: getRowData.bind(null, row, 'create')
              },
              auth: 'basic_list'
            },
            {
              label: '修改',
              type: 'button',
              props: {
                type: 'primary',
                text: true,
                onClick: getRowData.bind(null, row, 'update')
              },
              auth: 'basic_list'
            },
            {
              label: '删除',
              type: 'popconfirm',
              auth: 'basic_list',
              tip: '确定删除这条数据吗?',
              props: {
                onPositiveClick: deleteData.bind(null, [row.id])
              },
              ButtonProps: {
                text: true,
                type: 'primary'
              }
            }
          ],
          align: 'center'
        })
      }
    }
  ]
})

export default data
