<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" size="small" @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" size="small" @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-link v-if="tableConfigData.btnObj.isAdd" type="primary" :underline="false"
          @click="drawerData.handleShow('编辑', scope)">编辑</el-link>
        <el-divider direction="vertical" />
        <el-link v-if="tableConfigData.btnObj.isDelete" type="primary" :underline="false"
          @click="drawerData.delete(scope)">删除</el-link>
      </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="100px">
        <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, watch } 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: any, context: any) {
    const tableConfigData: TableConfigData = props.tableConfigData
    // 搜索框
    const searchData = searchLogic((value: string) => {
      console.log(value)
    })
    const data = tableLogic(props)
    const ruleFormRef = ref<FormInstance>()

    // 初始化表单数据变化次数
    const updateCount = ref(0)
    // 监听表单数据是否改变
    watch(() => tableConfigData, () => {
      updateCount.value++
    }, { deep: true })
    // 抽屉公共数据与方法 用于新增、编辑等修改
    const drawerData = reactive({
      drawerShow: false,
      clickKey: '新增',
      // 关闭弹窗
      handleClose() {
        if (updateCount.value > 1) {
          ElMessageBox.confirm(
            '是否提交已修改的内容?',
            {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'warning',
            }
          )
            .then(() => {
              updateCount.value = 0
              drawerData.onSubmit(ruleFormRef.value)
            })
            .catch(() => {
              updateCount.value = 0
              drawerData.drawerShow = false
            })
        } else {
          updateCount.value = 0
          drawerData.drawerShow = false
        }

      },
      // 打开编辑或新增
      handleShow(key: string, scope: Scope) {
        // 将列表数据派发至父组件
        context.emit('handleShow', { key: key, tableData: data.tableData.value, scope })
        updateCount.value = 0
        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.drawerShow = false
                data.init()
              }
            })
          }
        })
      }
    })

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

<style>
</style>