<template>
    <div style="opacity: 1;background-color: #FFF;padding:20px">
        <!-- 搜索框组件 -->
        <search-operation v-show="SSearch" :searchCondition="searchCondition" @RefreshLeft="RefreshLeft">
            <!-- 具名插槽 -->
            <slot name="search" :searchCondition="searchCondition" />
        </search-operation>

        <!-- CRUD组件 -->
        <crud-operation v-if="false" style="margin-top:10px" @add="add" @edit="edit" @remove="remove" @refresh="refresh"
            @search="search" :DEdit="EStart" :DDelete="DStart" :SSearch="SSearch">
        </crud-operation>

        <!-- 表单组件 -->
        <el-table ref="multipleTableRef" :data="testData" @selection-change="handleSelectionChange"
            style="width: 100%;margin: 20px 0 20px 0" :border="tableFrom.border">
            <!-- 表头拓展 -->
            <el-table-column v-for="(item,index) in tableFrom.extend" :key="index" :type="item.type" :width="item.width"
                :label="item.label" />
            <!-- 字段内容 -->
            <el-table-column v-for="(item,index) in tableFrom.field" :key="index" :prop="item.prop" :label="item.label"
                :width="item.width" :show-overflow-tooltip="!item.overflow" />

            <el-table-column :fixed="tableFrom.operateFixed ? 'right' : 'false'" :label="tableFrom.operateTitle"
                :width="tableFrom.operateWidth ? tableFrom.operateWidth : '150px'">
                <!-- 默认插槽值 -->
                <template #default="scope">
                    <ud-operation :scope="scope" :data="testData" :isEdit="tableFrom.operate.edit"
                        :isDelete="tableFrom.operate.delete" @handleEdit="handleEdit" @handleDelete="handleDelete">
                    </ud-operation>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination v-if="false" :page-size="20" :pager-count="11" layout="prev, pager, next" :total="1000" />
        <!-- 对话框 -->
        <el-dialog v-model="dialogFormVisible" :title="`${title}`">
            <!-- 是否自定义Dialog -->
            <div v-if="tableFrom.customDialog">
                <slot name="search" :searchCondition="searchCondition" />
            </div>
            <div v-else>
                <!-- 系统内容 -->
                <el-form ref="ruleFormRef" :rules="rules" :model="form">
                    <el-form-item v-for="(item,index) in tableFrom.field" :label="item.label" :prop="item.prop"
                        :label-width="formLabelWidth">
                        <!-- 输入框 -->
                        <div style="width: 100%;" v-if="item.form.type === 'input'">
                            <el-input v-model="form[item.prop]" :type="item.itemType"
                                :placeholder="item.form.placeholder" />
                        </div>
                        <!-- 选择框 -->
                        <div style="width: 100%;" v-else-if="item.form.type === 'select'">
                            <el-select style="width: 100%;" v-model="form[item.prop]"
                                :placeholder="item.form.placeholder">
                                <el-option v-for="(itemData,index) in item.form.listData" :label="itemData.label"
                                    :value="itemData.value" />
                            </el-select>
                        </div>
                        <!-- 日期框 -->
                        <div style="width: 100%;" v-else-if="item.form.type === 'date'">
                            <el-date-picker style="width: 100%;" v-model="form[item.prop]"
                                :value-format="item.form.valueFormat" :type="item.form.itemType"
                                :placeholder="item.form.placeholder" />
                        </div>
                    </el-form-item>

                </el-form>

            </div>

            <template v-if="!tableFrom.customDialog" #footer>
                <span class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="affirm(ruleFormRef)">提交</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>
<script lang="ts" setup>
    import crudOperation from '@/crud/components/CRUD.operation.vue'
    import searchOperation from '@/crud/components/Search.operation.vue'
    import udOperation from '@/crud/components/UD.operation.vue'
    import {
        reactive,
        ref,
        toRaw
    } from 'vue'

    // 声明事件
    const emit = defineEmits(['add', 'remove', 'refresh', 'edit', 'search', 'submit', 'handleEdit', 'handleDelete'])
    // 声明props
    const props = defineProps({
        homeData: { //表单配置
            type: Object,
            default: function () {
                return {}
            }
        },
        tableData: { //表单数据
            type: Array,
            default: function () {
                return [{
                    name: '测试数据'
                }, {
                    name: '测试数据'
                }, {
                    name: '测试数据'
                }]
            }
        }
    })

    const tableFrom = props.homeData ? props.homeData.table : [] //表单字段
    const multipleTableRef = ref() //表单ref(清空全选)
    const testData = ref(props.tableData) //表单数据
    const visible = ref(false) //删除提示框是否显示
    const dialogFormVisible = ref(false) //表单弹框是否显示
    const formLabelWidth = '100px' //默认表单宽度
    const title = ref('添加') //表单标题
    const DStart = ref(true) //删除按钮状态
    const EStart = ref(true) //编辑按钮状态
    const SSearch = ref(true) //是否打开搜索框
    let index = -1
    let indexs = []
    //表单校验
    const ruleFormRef = ref()
    let initRules = {}
    let initForm = {}
    //初始化数据
    if (tableFrom) {
        tableFrom.field.forEach(element => {
            initForm[element.prop] = ''
            if (element.form.required) {
                initRules[element.prop] = [{
                    required: true,
                    message: element.label + '不能为空',
                    trigger: 'blur'
                }]
            }
        });
    }
    const rules = reactive(initRules)

    //搜索条件
    let searchCondition = reactive(props.homeData ? props.homeData.search : [])

    //表单字段
    const form = ref(initForm)

    //重置
    const RefreshLeft = () => {
        Object.keys(searchCondition).forEach(key => (searchCondition[key] = ''));
    }

    //添加
    const add = () => {
        console.log('点击了添加按钮');
        form.value = {}
        title.value = '添加'
        dialogFormVisible.value = true
        emit('add')
    }

    //删除
    const remove = () => {
        console.log('点击了删除按钮');
        emit('remove')
    }

    //刷新
    const refresh = () => {
        console.log('点击了刷新按钮');
        emit('refresh')
    }

    //编辑
    const edit = () => {
        console.log('点击了修改按钮');
        if (index != -1) {
            title.value = '编辑'
            form.value = JSON.parse(JSON.stringify(testData.value[index]))
            dialogFormVisible.value = true
            emit('edit')
        }
    }

    //搜索
    const search = () => {
        console.log('点击了搜索按钮');
        SSearch.value = !SSearch.value
        emit('search')
    }

    //头部多选处理
    const handleSelectionChange = (val) => {
        if (val) {
            index = -1
            DStart.value = true
            EStart.value = true
            if (val.length === 1) {
                testData.value.forEach((element, idx) => {
                    if (element === val[0]) {
                        index = idx
                    }
                });
                EStart.value = false
                DStart.value = false
            } else if (val.length > 0) {
                DStart.value = false
            }
        }
    }

    //表单提交
    const affirm = (formEl) => {
        if (!formEl) {
            return
        }
        formEl.validate((valid, fields) => {
            if (valid) { //是否通过表单验证
                if (index !== -1) {
                    testData.value.splice(index, 1, form.value)
                } else {
                    testData.value.push(form.value)
                }
                emit('search', form.value)
                index = -1 //重置标识
                dialogFormVisible.value = false
                multipleTableRef.value.clearSelection() //清空多选
            } else {
                return false
            }
        })
    }

    //取消
    const cancel = () => {
        dialogFormVisible.value = false
    }

    //编辑
    const handleEdit = (idx, row) => {
        console.log('点击了编辑按钮');
        title.value = '编辑'
        form.value = JSON.parse(JSON.stringify(toRaw(row)))
        dialogFormVisible.value = true
        index = idx
        emit('handleEdit', idx, row)
    }

    //删除
    const handleDelete = (idx, row) => {
        console.log('点击了删除按钮');
        testData.value.splice(idx, 1)
        row.visible = false
        emit('handleDelete', idx, row)
    }
</script>
<style lang="scss">
</style>