<template>
  <!-- 顶部搜索 -->
  <div class="search-content">
    <el-form :model="formData">
      <el-form-item label="搜索">
        <el-row :gutter="10">
          <el-col :span="18"><el-input v-model="formData.keyword" :placeholder="`请输入${tableConfigData.title}`" @change="searchList" /></el-col>
          <el-col :span="6"><el-button type="primary" @click="searchList">搜索</el-button></el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <div class="button-content margin-bottom-10">
      <el-button v-if="tableConfigData.btnObj.isAdd" type="primary" @click="drawerData.handleShow('新增')">
        <el-icon><Plus /></el-icon>
          新增
      </el-button>
      <slot name="button"></slot>
    </div>
  </div>
  <!-- 表格列表渲染 -->
  <el-table
    :data="tableData"
    style="width: 100%; margin-bottom: 20px"
    row-key="id"
    border
  >
    <el-table-column type="selection" width="50" />
    <el-table-column
      v-for="(item, index) in tableConfigData.tableTitle"
      :key="index"
      :prop="item.prop"
      :label="item.label"
      :sortable="item.sortable"
      :width="item.width ?? '180'" />
    <el-table-column
      align="center"
      label="操作"
      :width="tableConfigData.btnObj.width"
      fixed="right"
    >
      <template #default="scope">
        <!-- 自定义按钮插槽 -->
        <slot name="tableButton" v-bind="scope" />
        <el-button v-if="tableConfigData.btnObj.isAdd" type="primary" size="small" @click="drawerData.handleShow('编辑', scope)">编辑</el-button>
        <el-button v-if="tableConfigData.btnObj.isDelete"  type="danger" size="small" @click="drawerData.delete(scope)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 编辑or新增抽屉 -->
  <el-drawer
    v-model="drawerData.drawerShow"
    :title="drawerData.clickKey + tableConfigData.title"
    direction="rtl"
    :before-close="drawerData.handleClose"
  >
    <el-card v-if="drawerData.drawerShow">
      <el-form ref="ruleFormRef" :model="tableConfigData.drawerformData" :rules="tableConfigData.rules" label-width="80px">   
        <slot name="drawer" />
        <el-form-item>
          <el-button type="primary" @click="drawerData.onSubmit(ruleFormRef)">保存</el-button>
          <el-button @click="drawerData.handleClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-drawer>
</template>

<script lang="ts">
import { searchLogic } from './business/search'
import { tableLogic } from './business/table'
import { ref, reactive, PropType } from 'vue'
import { Scope, TableConfigData } from './type'
import { FormInstance, ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import { tableDelete, tableSave } from '@/services/api/customTable'
export default {
  name: 'CustomTable',
  emits: ['handleShow'],
  props: {
    tableConfigData: {
      type: Object as PropType<TableConfigData>,
      required: true
    }
  },
  setup(props, context) {
    const tableConfigData: TableConfigData = props.tableConfigData
    // 搜索框
    const searchData = searchLogic((value: string) => {
      console.log(value)
    })
    const data = tableLogic(props)
    const ruleFormRef = ref<FormInstance>()
    // 抽屉公共数据与方法 用于新增、编辑等修改
    const drawerData = reactive({
      drawerShow: false,
      clickKey: '新增',
      // 关闭弹窗
      handleClose() {
        drawerData.drawerShow = false
      },
      // 打开编辑或新增
      handleShow(key: string, scope: Scope) {
        // 将列表数据派发至父组件
        context.emit('handleShow', { key: key, tableData: data.tableData.value, scope })
        drawerData.drawerShow = true
        drawerData.clickKey = key
      },
      // 删除表格某一行
      delete(scope: Scope) {
        ElMessageBox.confirm('确定删除吗？', '温馨提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          tableDelete(tableConfigData.apiKey + '/delete', { id: scope.row.id }).then((res: any) => {
            if (res.code === 200) {
              ElMessage({
                type: 'success',
                message: '删除成功',
              })
              // 重新加载表格数据
              data.init()
            }
          })
        })
      },
      // 接口新增和保持
      async onSubmit(formEl: FormInstance | undefined) {
        // 保存
        await formEl?.validate(valid => {
          if (valid) {
            const apiName = drawerData.clickKey === '新增' ? '/add' : '/edit'
            tableSave(tableConfigData.apiKey + apiName, apiName === '/add' ? 'post' : 'put', tableConfigData.drawerformData).then((res: any) => {
              if (res.code === 200) {
                ElNotification({
                  title: '温馨提示',
                  message: '保存成功！',
                  type: 'success'
                })
                drawerData.handleClose()
                data.init()
              }
            })
          }
        })
      }
    })

    return {
      ...searchData,
      tableData: data.tableData,
      drawerData,
      ruleFormRef
    }
  }
}
</script>

<style>

</style>