<template>
    <div>
        <el-card :body-style="cardBodyStyle">
            <el-form :inline="true">
                <#list queryList as item>
                    <#if item.controllerType == "日期">
                        <el-form-item label="${item.fieldComment}"  style="margin-bottom: 0px;">
                            <#if item.dateFlag =='1'>
                                <el-date-picker v-model="query.${item.prop}" type="daterange"
                                                align="right" range-separator="至"
                                                start-placeholder="开始日期" end-placeholder="结束日期"
                                                :picker-options="pickerOptions" style="width: 250px;"
                                                value-format="YYYY-MM-DD" format="YYYY-MM-DD">
                                </el-date-picker>
                            <#else>
                                <el-date-picker v-model="query.${item.prop}"  type="date"
                                                value-format="YYYY-MM-DD" format="YYYY-MM-DD"
                                                style="width: 200px;"></el-date-picker>
                            </#if>
                        </el-form-item>
                    <#elseif item.controllerType == "日期时间">
                        <el-form-item label="${item.fieldComment}" style="margin-bottom: 0px;">
                            <#if item.dateFlag =='1'>
                                <el-date-picker v-model="query.${item.prop}" type="datetimerange"
                                                align="right" unlink-panels range-separator="至"
                                                start-placeholder="开始时间" end-placeholder="结束时间"
                                                :picker-options="pickerOptions" style="width: 350px;"
                                                value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss">
                                </el-date-picker>
                            <#else>
                                <el-date-picker v-model="query.${item.prop}"
                                                type="datetime" style="width: 200px;"
                                                value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                            </#if>
                        </el-form-item>
                    <#else>
                        <el-form-item label="${item.fieldComment}" style="margin-bottom: 5px;" prop="${item.prop}">
                            <el-input v-model="query.${item.prop}" placeholder="请输入${item.fieldComment}"
                                      clearable></el-input>
                        </el-form-item>
                    </#if>
                </#list>
            </el-form>
        </el-card>
        <ButtonBar @search="handleSearch" @add="handleAdd" @remove="handleRemoveBatch" @edit="handleEditBatch"
                   @upload="handleUpload" @download="handleDownload" @import="handleImport" @export="handleExport"></ButtonBar>
        <el-card :body-style="cardBodyStyle">
            <el-table :data="tableData" border highlight-current-row  @selection-change="handleSelectionChange">
                <el-table-column type="selection" fixed></el-table-column>
                <el-table-column type="index" label="序号" align="center" width="60">
                    <template #default="scope">
                        <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
                    </template>
                </el-table-column>
                <#if lowCode.fixedFlag=='1'>
                    <el-table-column v-for="item in cols"  :key="item.id"  :prop="item.prop"
                                     :label="item.label" :width="item.width" :header-align="item.headerAlign" :align="item.align"
                                     show-overflow-tooltip></el-table-column>
                <#else>
                    <#list lowCodeFields as item>
                        <el-table-column v-if="<#if item.showFlag=='1'>true<#else>false</#if>" prop="${item.prop}" label="${item.fieldComment}" width="${item.width}"
                                         header-align="${item.headerAlign}" align="${item.align}"
                                         show-overflow-tooltip>
                        </el-table-column>
                    </#list>
                </#if>


                <el-table-column label="操作" header-align="center" align="center" width="200px">
                    <template #default="scope">
                        <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button plain type="danger" @click="handleDelete(scope.row )">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-card :body-style="cardBodyStyle">
            <el-pagination  :current-page="currentPage"  :page-size="pageSize" :page-sizes="pageSizes"
                           :total="totalRows" background="background" layout="total, sizes, prev, pager, next, jumper"
                           @size-change="handleSizeChange" @current-change="handleCurrentChange">
            </el-pagination>
        </el-card>

        <el-dialog :close-on-click-modal="false" draggable title="编辑" v-model="dialogVisible" width="1200px"
                   top="5vh"  @open="openDialog">
            <el-form :model="form" label-width="80px" label-position="right" inline ref="ruleFormRef" :rules="rules">
                <#list inputList as item>
                <el-form-item label="${item.fieldComment}" <#if item.requireFlag=='1'> prop="${item.prop}" </#if> >
                 <#if item.controllerType == "日期">
                    <el-date-picker v-model="form.${item.prop}"  type="date"  style="width: 200px;"
                                     value-format="YYYY-MM-DD" format="YYYY-MM-DD"
                                    ></el-date-picker>
                  <#elseif  item.controllerType == "日期时间">
                    <el-date-picker v-model="form.${item.prop}"  type="datetime" style="width: 200px;"
                                     value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
                   <#elseif  item.controllerType == "单行文本">
                    <el-input v-model="form.${item.prop}" clearable style="width: 200px"></el-input>
                    <#elseif  item.controllerType == "多行文本">
                     <el-input v-model="form.${item.prop}" clearable style="width: 200px"></el-input>
                  </#if>
                </el-form-item>
                </#list>
            </el-form>
            <#if lowCode.attachmentFlag=='1'>
                <Attachment ref="refUpload"></Attachment>
            </#if>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
                    <el-button type="danger" @click="handleCancelSave">取消</el-button>
                </div>
            </template>
        </el-dialog>


    </div>
</template>

<script setup>
    import ButtonBar from '@/components/ButtonBar.vue'

    import {
        ref,
        reactive,
        onMounted,
        getCurrentInstance
    } from 'vue'

    const {
        proxy
    } = getCurrentInstance()

    import tools from '@/tools'
    const cardBodyStyle = ref(tools.style.card)
    const inputStyle = ref(tools.style.input)

    onMounted(() => {
        <#if lowCode.fixedFlag=='1'>
        getCols()
        </#if>
        handleSearch()
    })
    <#if lowCode.attachmentFlag=='1'>
    import Attachment from '@/components/Attachment.vue'
    </#if>



    /**
     *   查询
     */


    <#if lowCode.fixedFlag=='1'>
    import {
        nextTick
    } from 'vue'
    const cols = ref([ ])
    const getCols = () => {
        var url = 'framework/LowCodePersonal/queryByUserIdMenuId'
        var param = {
            menuId: localStorage.getItem('menuId'),
            tName: '表格'
        }
        proxy.$axios.get(url, param).then(response => {
            var temp = []
            for (var col of response.data.data) {
                if (col.showFlag == '1') {
                    temp.push(col)
                }
            }
            var newArray = temp.slice(0)
            cols.value = []
            nextTick(() => {
                cols.value = newArray
            })
        })
    }
    </#if>


    const query = ref({
        <#list queryList as item>
        <#if item.controllerType == "日期">
            <#if item.dateFlag =='1'>
                ${item.prop} : [proxy.$dayjs().format('YYYY-MM-DD'), proxy.$dayjs().format('YYYY-MM-DD')] <#if item_has_next>, </#if>
            <#else>
                ${item.prop}: proxy.$dayjs().format('YYYY-MM-DD') <#if item_has_next>, </#if>
            </#if>
        <#elseif  item.controllerType == "日期时间" >
            <#if item.dateFlag =='1'>
              ${item.prop} : [proxy.$dayjs().format('YYYY-MM-DD') + ' 00:00:00', proxy.$dayjs().format('YYYY-MM-DD') + ' 23:59:59' ] <#if item_has_next>, </#if>
              <#else>
              ${item.prop}:proxy.$dayjs().format('YYYY-MM-DD HH:mm:ss')<#if item_has_next>, </#if>
            </#if>
        <#else>
           ${item.prop}: ''<#if item_has_next>, </#if>
       </#if>
       </#list>
   })
   const tableData = ref([])
   const handleSearch = () => {
       currentPage.value = 1
       getTableData()
   }

   const getTableData = () => {
       var url = '${lowCode.serviceName}/${entity}/query'
       var param = {
           page: currentPage.value,
           rows: pageSize.value,
           params: JSON.stringify(query.value)
       }
       proxy.$axios.get(url, param).then(response => {
            if (response.data.code == '0') {
                tableData.value = response.data.data.records
                totalRows.value = response.data.data.total
            } else {
                ElMessage.error('操作失败！' + response.data.msg)
            }
        })
    }
    /**
     *   查询
     */

    /**
     * 分页
     */
    const currentPage = ref(1)
    const totalRows = ref(0)
    const pageSizes = ref([5, 10, 20, 30, 40])
    const pageSize = ref(5)
    const handleSizeChange = (val) => {
        pageSize.value = val
        getTableData()
    }
    const handleCurrentChange = (val) => {
        currentPage.value = val
        getTableData()
    }
    /**
     * 分页
     */


    /**
     * 新增
     */
    const dialogVisible = ref(false)
    const form = ref({
        <#list inputList as item>
        ${item.prop}: ''<#if item_has_next>, </#if>
        </#list>
    })
    const ruleFormRef = ref()
    const rules = reactive({
        <#list inputList as item>
        <#if item.requireFlag=='1'>
        ${item.prop}: [{
            required: true,
            message: '请输入${item.fieldComment}',
            trigger: 'change' | 'blur'
        }]<#if item_has_next>, </#if>
        </#if>
        </#list>
    })

    const handleAdd = () => {
        form.value = {
            <#list inputList as item>
            ${item.prop}: ''<#if item_has_next>, </#if>
            </#list>
        }
        dialogVisible.value = true
    }
    /**
     * 新增
     */


    /**
     * 保存、修改、删除
     */
    <#if lowCode.attachmentFlag=='1'>
         const refUpload = ref()
    </#if>

    const openDialog=()=>{
        <#if lowCode.attachmentFlag=='1'>
        refUpload.value.fId = form.value.id
        refUpload.value.getTableData()
        </#if>
    }

    const handleSave = (ruleFormRef) => {
        ruleFormRef.validate((valid, fields) => {
            if (valid) {
                var url = '${lowCode.serviceName}/${entity}/save'
                var param = {
                    json: JSON.stringify(form.value),
                }
                proxy.$axios.post(url, param).then(response => {
                    if (response.data.code == 0) {
                        form.value = response.data.data
                        ElMessage({
                            message: '保存成功',
                            type: 'success',
                        })
                        <#if lowCode.attachmentFlag=='1'>
                        refUpload.value.fId = form.value.id
                        refUpload.value.upload()
                        </#if>
                        getTableData()
                        dialogVisible.value = false
                    } else {
                        // ElMessage.error('操作失败！' + response.data.msg)
                        ElMessage({
                            message: '操作失败' + response.data.msg,
                            type: 'error'
                        })
                    }
                })

            } else {
                console.log('error submit!', fields)
            }
        })
    }
    const handleCancelSave = () => {
        dialogVisible.value = false
    }
    const handleEdit = (row) => {
        dialogVisible.value = true
        form.value = row
    }
    const handleDelete = (row) => {
        ElMessageBox.confirm(
            '确定删除本条记录?',
            '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
                draggable: true,
            }
        )
            .then(() => {
                var url = '${lowCode.serviceName}/${entity}/remove'
                var param = {
                    id: row.id
                }
                proxy.$axios.post(url, param).then(response => {
                    if (response.data.code == 0) {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        getTableData()
                    } else {
                        ElMessage({
                            type: 'error',
                            message: '删除失败' + response.data.msg
                        });
                    }
                });
            })
            .catch(() => {
                ElMessage({
                    type: 'info',
                    message: '已取消',
                })
            })
    }

    /**
     * 保存、修改、删除
     */

    const multipleSelection = ref([])
    const handleSelectionChange = (val) => {
        multipleSelection.value = val
    }

    const handleRemoveBatch = () => {
        console.log('handleRemoveBatch')

        if (multipleSelection.value.length < 1) {
            ElMessage({
                type: 'warning',
                message: '请选择要删除的数据!'
            })
            return
        }

        ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            var ids = []
            multipleSelection.value.forEach((item, index) => {
                ids.push(item.id)
            })
            var url = '${lowCode.serviceName}/${entity}/removeBatch'
            var param = {
                ids: JSON.stringify(ids)
            }
            proxy.$axios.post(url, param).then(response => {
                if (response.data.code == '0') {
                    ElMessage({
                        type: 'success',
                        message: '操作成功!',
                    });
                    getTableData()
                    dialogVisible.value = false
                } else {
                    ElMessage({
                        type: 'error',
                        message: '操作失败!' + response.data.msg
                    });
                }
            })
        }).catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除'
            })
        })
    }

    const handleEditBatch = () => {
        console.log('handleEditBatch')
        if (multipleSelection.value.length != 1) {
            ElMessage({
                type: 'warning',
                message: '请选择一条数据编辑!'
            })
            return
        }
        handleEdit(multipleSelection.value[0])
    }

    const handleUpload = () => {
        console.log('handleUpload')
    }

    const handleDownload = () => {
        console.log('handleDownload')
    }

    const handleImport = () => {
        console.log('handleImport')
    }

    const handleExport = () => {
        console.log('handleExport')
    }

</script>

<style>
</style>