<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>
                <el-button type="primary" v-auth="['${moduleName}:${businessName}:import']" icon="Upload" plain @click="batchAdd">
                    导入
                </el-button>
                <el-button type="primary" v-auth="['${moduleName}:${businessName}:export']" icon="Download" plain @click="downloadFile">
                    导出
                </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
                           icon="Delete" v-auth="['${moduleName}:${businessName}:remove']"
                           @click="delete${BusinessName}(scope.row)"
                >
                    删除
                </el-button>
            </template>
        </ProTable>
        <FormDialog ref="formDialogRef" :items-options="itemsOptions" :model="model"/>
        <ImportExcel ref="dialogRef" />
        <TaskDialog ref="taskDialogRef" />
    </div>
</template>

<script setup lang="tsx" name="${BusinessName}">
    import { useHandleData } from '@/hooks/useHandleData'
    import { ElMessageBox } from 'element-plus'
    import ImportExcel from '@/components/ImportExcel/index.vue'
    import TaskDialog from '@/components/TaskDialog/index.vue'
    import FormDialog from '@/components/FormDialog/index.vue'
    import { ProTableInstance, ColumnProps } from '@/components/ProTable/interface'
    import { handleTree } from '@/utils/common'
    import {
        list${BusinessName}Api,
        del${BusinessName}Api,
        add${BusinessName}Api,
        update${BusinessName}Api,
        importTemplateApi,
        import${BusinessName}DataApi,
        export${BusinessName}Api,
        get${BusinessName}Api
    } from '@/api/modules/${moduleName}/${businessName}'
        #if(${dicts} != '')
            #set($dictsNoSymbol=$dicts.replace("'", ""))
        const { proxy } = getCurrentInstance() as ComponentInternalInstance
        const { ${dictsNoSymbol} } = toRefs<any>(proxy?.useDict(${dicts}));
        #end

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

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

    const taskDialogRef = ref<InstanceType<typeof TaskDialog> | null>(null)
    // 导出${functionName}列表
    const downloadFile = async () => {
        ElMessageBox.confirm('确认导出${functionName}数据?', '温馨提示', { type: 'warning' }).then(async () => {
            export${BusinessName}Api(proTable.value?.searchParam)
            taskDialogRef.value?.openExportDialog()
        })
    }

    // 批量添加${functionName}
    const dialogRef = ref<InstanceType<typeof ImportExcel> | null>(null)
    const batchAdd = () => {
        const params = {
            title: '${functionName}',
            tempApi: importTemplateApi,
            importApi: import${BusinessName}DataApi,
            getTableList: proTable.value?.getTableList
        }
        dialogRef.value?.acceptParams(params)
    }

    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)
        }
        // 重置表单项
        setItemsOptions()
        if (row?.${treeParentCode} == 0 && type == 2) {
            itemsOptions.splice(0, 1)
        }
        // 增加子节点
        if (type == 4) {
            res.data = {
                parentId: row?.${pkColumn.javaField}
            }
        }
        model.value = type == 1 ? {} : res.data
        const params = {
            title,
            width: 580,
            isEdit: type !== 3,
            api: [1, 4].includes(type) ? 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.htmlType == "input-number")
                {
                    prop: '${javaField}',
                    label: '${comment}',
                    #if($column.query)
                        search: {
                            el: 'input',
                        },
                    #else
                    #end
                    width: 120
                },
            #elseif($column.list && $column.dictType && "" != $column.dictType)
                {
                    prop: '${javaField}',
                    label: '${comment}',
                    tag: true,
                    enum: ${businessName}Options,
                    #if($column.query)
                        search: {
                            el: 'tree-select'
                        },
                    #else
                    #end
                },
            #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 itemsOptions = reactive<ProForm.ItemsOptions[]>([])
    const setItemsOptions = () => {
        itemsOptions = [
            #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(${field} == "parentId")
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'blur'}],
                                #else
                                #end
                                compOptions: {
                                    elTagName: 'tree-select',
                                    enum: ${businessName}Options.value,
                                    valueKey: '${pkColumn.javaField}',
                                    checkStrictly: true,
                                    props: {
                                        value: '${pkColumn.javaField}',
                                        label: '${treeName}'
                                    },
                                    placeholder: '请选择${comment}'
                                }
                            },
                        #elseif($column.htmlType == "input")
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'blur'}],
                                #else
                                #end
                                compOptions: {
                                    placeholder: '请输入${comment}'
                                }
                            },
                        #elseif($column.htmlType == "input-number")
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'blur'}],
                                #else
                                #end
                                compOptions: {
                                    elTagName: 'input-number',
                                }
                            },
                        #elseif($column.htmlType == "select" && "" != $dictType)
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                compOptions: {
                                    elTagName: 'select',
                                    enum: ${column.dictType}.value,
                                    placeholder: '请选择${comment}'
                                }
                            },
                        #elseif($column.htmlType == "checkbox" && "" != $dictType)
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                compOptions: {
                                    elTagName: 'checkbox-group',
                                    enum: ${column.dictType}.value,
                                    placeholder: '请选择${comment}'
                                }
                            },
                        #elseif($column.htmlType == "radio" && "" != $dictType)
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                compOptions: {
                                    elTagName: 'radio-group',
                                    enum: ${column.dictType}.value,
                                    placeholder: '请选择${comment}'
                                }
                            },
                        #elseif($column.htmlType == "datetime")
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'change'}],
                                #else
                                #end
                                compOptions: {
                                    elTagName: 'date-picker',
                                    type: 'date',
                                    placeholder: '请选择${comment}'
                                }
                            },
                        #elseif($column.htmlType == "textarea")
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'blur'}],
                                #else
                                #end
                                compOptions: {
                                    type: 'textarea',
                                    clearable: true,
                                    placeholder: '请输入内容'
                                }
                            },
                        #else
                            {
                                label: '${comment}',
                                prop: '${field}',
                                #if($column.required)
                                    rules: [{required: true, message: '${comment}不能为空', trigger: 'blur'}],
                                #else
                                #end
                                compOptions: {
                                    placeholder: '请输入${comment}'
                                }
                            },
                        #end
                    #end
                #end
            #end
        ]
    }
</script>
