<template>
    <div class="table-box">
        <ProTable ref="proTable" :pagination="false" :columns="columns" row-key="${pkColumn.javaField}" :request-api="list${BusinessName}Api" :init-param="initParam" :data-callback="dataCallback">
            <!-- 表格 header 按钮 -->
            <template #tableHeader>
                <el-button type="primary" v-auth="['${moduleName}:${businessName}:add']" :icon="CirclePlus" @click="openDialog(1, '${functionName}新增')">
                    新增
                </el-button>
            </template>
            <!-- 表格操作 -->
            <template #operation="scope">
                <el-button
                    type="primary"
                    link
                    :icon="EditPen"
                    v-auth="['${moduleName}:${businessName}:edit']"
                    @click="openDialog(2, '${functionName}编辑', scope.row)"
                >
                    编辑
                </el-button>
                <el-button
                    type="primary"
                    link
                    v-auth="['${moduleName}:${businessName}:add']"
                    :icon="CirclePlus"
                    @click="openDialog(4, '${functionName}新增', scope.row)"
                >
                    新增
                </el-button>
                <el-button type="primary"
                           link
                           v-if="scope.row.${treeParentCode} != 0"
                           :icon="Delete" v-auth="['${moduleName}:${businessName}:remove']"
                           @click="delete${BusinessName}(scope.row)"
                >
                    删除
                </el-button>
            </template>
        </ProTable>
        <FormDialog ref="formDialogRef" />
        <ImportExcel ref="dialogRef" />
    </div>
</template>

<script setup lang="tsx" name="${BusinessName}">
    import { ref, reactive } from 'vue'
    import { useHandleData } from '@/hooks/useHandleData'
    import ProTable from '@/components/ProTable/index.vue'
    import ImportExcel from '@/components/ImportExcel/index.vue'
    import FormDialog from '@/components/FormDialog/index.vue'
    import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
    import { Delete, EditPen, CirclePlus } from '@element-plus/icons-vue'
    import { handleTree } from '@/utils/common'
    import {
        list${BusinessName}Api,
        del${BusinessName}Api,
        add${BusinessName}Api,
        update${BusinessName}Api,
        get${BusinessName}Api
    } from '@/api/modules/${moduleName}/${businessName}'
        #if(${dicts} != '')
        import { getDictsApi } from '@/api/modules/system/dictData'
        #end

    // ProTable 实例
    const proTable = ref<ProTableInstance>()

    // 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
    const initParam = reactive({ type: 1 })
    const ${businessName}Options = ref<any[]>([])
    // dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
    const dataCallback = (res: any) => {
        const data = handleTree(res, '${pkColumn.javaField}')
            ${businessName}Options.value = data
        setFieldList()
        return data
    }

    // 删除${functionName}信息
    const delete${BusinessName} = async (params: any) => {
        await useHandleData(del${BusinessName}Api, { id: [params.${pkColumn.javaField}] }, `删除【${params.id}】${functionName}`)
        proTable.value?.getTableList()
    }

    const formDialogRef = ref<InstanceType<typeof FormDialog> | null>(null)
    // 打开弹框的功能
    const openDialog = async (type: number, title: string, row?: any) => {
        let res = { data: {} }
        if (row?.${pkColumn.javaField}) {
            res = await get${BusinessName}Api(row?.${pkColumn.javaField} || null)
        }
        // 重置表单项
        setFieldList()
        if (row?.${treeParentCode} == 0 && type == 2) {
            fieldList.splice(0, 1)
        }
        // 增加子节点
        if (type == 4 && row?.${treeParentCode}) {
            res.data = {
                parentId: row?.${treeParentCode}
            }
        }
        const params = {
            title,
            width: 580,
            isEdit: type !== 3,
            fieldList: fieldList,
            model: type == 1 ? {} : res.data,
            api: type == 1 || type == 4 ? add${BusinessName}Api : update${BusinessName}Api,
            getTableList: proTable.value?.getTableList
        }
        formDialogRef.value?.openDialog(params)
    }

    // 表格配置项
    const columns = reactive<ColumnProps<any>[]>([
        { type: 'selection', fixed: 'left', width: 70 },
        #foreach($column in $columns)
            #set($javaField=$column.javaField)
            #set($parentheseIndex=$column.columnComment.indexOf("（"))
            #if($parentheseIndex != -1)
                #set($comment=$column.columnComment.substring(0, $parentheseIndex))
            #else
                #set($comment=$column.columnComment)
            #end
            #if($column.pk)
                { prop: '${javaField}', label: '${comment}' },
            #elseif($column.list && $column.htmlType == "datetime")
                {
                    prop: '${javaField}',
                    label: '${comment}',
                    #if($column.query)
                        search: {
                            el: 'date-picker',
                            props: { type: 'datetimerange', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
                        },
                    #else
                    #end
                    width: 120
                },
            #elseif($column.list && "" != $column.dictType)
                {
                    prop: '${javaField}',
                    label: '${comment}',
                    tag: true,
                    enum: () => getDictsApi('$column.dictType'),
                    #if($column.query)
                        search: {
                            el: 'tree-select'
                        },
                    #else
                    #end
                    fieldNames: { label: 'dictLabel', value: 'dictValue' }
                },
            #elseif($column.list && "" != $javaField)
                {
                    prop: '${javaField}',
                    label: '${comment}',
                    #if($column.query)
                        search: {
                            el: 'input'
                        },
                    #else
                    #end
                    width: 120
                },
            #end
        #end
        { prop: 'operation', label: '操作', width: 230, fixed: 'right' }
    ])

    // 表单配置项
    let fieldList: Form.FieldItem[] = []
    const setFieldList = () => {
        fieldList = [
            #foreach($column in $columns)
                #set($field=$column.javaField)
                #if($column.insert && !$column.pk)
                    #if(($column.usableColumn) || (!$column.superColumn))
                        #set($parentheseIndex=$column.columnComment.indexOf("（"))
                        #if($parentheseIndex != -1)
                            #set($comment=$column.columnComment.substring(0, $parentheseIndex))
                        #else
                            #set($comment=$column.columnComment)
                        #end
                        #set($dictType=$column.dictType)
                        #if("" != $treeParentCode && $column.javaField == $treeParentCode)
                            {
                                label: '${comment}',
                                field: '${field}',
                                enum: ${businessName}Options.value,
                                type: 'select-tree',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                options: {
                                    labelKey: '${treeName}',
                                    valueKey: '${treeParentCode}',
                                    children: 'children'
                                },
                                placeholder: '请选择${comment}'
                            },
                        #elseif($column.htmlType == "input")
                            {
                                label: '${comment}',
                                field: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'blur'}],
                                #else
                                #end
                                placeholder: '请输入${comment}'
                            },
                        #elseif($column.htmlType == "select" && "" != $dictType)
                            {
                                label: '${comment}',
                                field: '${field}',
                                enum: () => getDictsApi('$dictType'),
                                type: 'select',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                options: {
                                    labelKey: 'dictLabel',
                                    valueKey: 'dictValue'
                                },
                                placeholder: '请选择${comment}'
                            },
                        #elseif($column.htmlType == "checkbox" && "" != $dictType)
                            {
                                label: '${comment}',
                                field: '${field}',
                                enum: () => getDictsApi('$dictType'),
                                type: 'checkbox',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                options: {
                                    labelKey: 'dictLabel',
                                    valueKey: 'dictValue'
                                },
                                placeholder: '请选择${comment}'
                            },
                        #elseif($column.htmlType == "radio" && "" != $dictType)
                            {
                                label: '${comment}',
                                field: '${field}',
                                enum: () => getDictsApi('$dictType'),
                                type: 'radio',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                options: {
                                    labelKey: 'dictLabel',
                                    valueKey: 'dictValue'
                                },
                                placeholder: '请选择${comment}'
                            },
                        #elseif($column.htmlType == "datetime")
                            {
                                label: '${comment}',
                                field: '${field}',
                                type: 'date-picker',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                placeholder: '请选择${comment}'
                            },
                        #elseif($column.htmlType == "textarea")
                            {
                                label: '${comment}',
                                field: '${field}',
                                type: 'textarea',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'blur'}],
                                #else
                                #end
                                placeholder: '请输入内容'
                            },
                        #else
                            {
                                label: '${comment}',
                                field: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'blur'}],
                                #else
                                #end
                                placeholder: '请输入${comment}'
                            },
                        #end
                    #end
                #end
            #end
        ]
    }
</script>
