<template>
    <FormDialog
        :width="width"
        class="parameter_setting_form_dialog"
        v-if="formVisible"
        :defaultFormData="{}" 
        :visible="formVisible" 
        :title="formTitle"
        :submitLoading="formSubmitLoading"
        @close="HandleFormClose"
        @confirm="HandleFormConfirm"
    >
        <template #form_pre>
            <div class="dictionary_box">
                <Table
                    v-model:tableRef="configTableDom"
                    :tableColumns="finalTableColumns" 
                    :tableData="tableData"
                    :hidePagination="true">
                    <template #moveable="{row,currentIndex}">
                        <TableRowDragUpDown  
                            :startIndex="startDragIndex()"
                            :endIndex="endDragIndex(tableData)"
                            v-if="(currentIndex - 1) >= startDragIndex() && (currentIndex - 1) <= endDragIndex(tableData)"
                            :currentIndex="currentIndex" 
                            :tableRow="row" :defaultTableData="tableData" 
                            @moveChange="HandleRowMove"/>
                    </template>
                    <template #num="{row,currentIndex}">
                        {{ currentIndex }}
                    </template>
                    <template v-slot:[middleColumnItm?.name]="{row,currentIndex}">
                        <slot :name="[middleColumnItm?.name]" :row="row" :currentIndex="currentIndex">
                            <el-input v-model="row[middleColumnItm.name]" v-if="row.tmpId" placeholder="请输入内容" />
                            <span v-else>{{ row?.[middleColumnItm?.name] }}</span>
                        </slot>
                    </template>

                    <template #operation="{row,currentIndex}">
                        <div class="table_row_option">
                            <!-- row.defaultStatus ?  -->
                            <span :class="disabledEditRowScene ?
                                        (disabledEditRowScene(row,currentIndex,tableData)  ? 'editor_disable' : 'el_button_editor') : 
                                        'el_button_editor'" 
                                    @click="disabledEditRowScene ?
                                            (disabledEditRowScene(row,currentIndex,tableData)  ? '' : HandleConfigEditOrSave(row)) : 
                                            HandleConfigEditOrSave(row)"
                            >{{row.tmpId ? '保存' : '编辑'}}</span>

                            <span v-if="row.tmpId" class="el_button_editor" @click="HandleConfigCancel(row)">取消</span>
                            <!-- row.defaultStatus  -->
                            <span v-else 
                                    :class="disabledDeleteRowScene ? 
                                            (disabledDeleteRowScene(row,currentIndex,tableData)  ? 'editor_disable' : 'el_button_delete') : 
                                            'el_button_delete'" 
                                    @click="disabledDeleteRowScene ? 
                                            (disabledDeleteRowScene(row,currentIndex,tableData)  ? '' : HandleConfigDelete(row)) : 
                                            HandleConfigDelete(row)"
                            >删除</span>
                        </div>
                    </template>
                </Table>
                <div class="add_option" @click="HandleAddConfig"> 
                    <el-icon><CloseBold /></el-icon>
                    <span>{{ addOperationName }}</span>
                </div>
            </div>
        </template>
    </FormDialog>



     <!-- 删除弹窗 -->
    <Dialog 
        v-if="dialogVisible"
        :submitLoading="dialogSubmitLoading"
        :visible="dialogVisible"
        @confirm="HandleDialogConfirm"
        @close="HandleDialogClose">
        是否确认删除？
    </Dialog>

</template>


<script setup lang="ts">
import { ref,watch, nextTick } from 'vue';
import {ElMessage} from 'element-plus'

import FormDialog from '@/baseComponents/FormDialog.vue';
import Dialog from '@/baseComponents/Dialog.vue';
import TableRowDragUpDown from '@/baseComponents/TableRowDragUpDown.vue';
import Table from '../Table.vue';
import {tableColumns} from './table'

interface MiddleColumnItm {
    name:string,
    label:string
}

const props = defineProps({
    startDragIndex:{  
        type:Function,
        required:true
    },
    endDragIndex:{
        type:Function,
        required:true
    },
    width:{  //弹窗宽度
        type:String,
        default:'680px'
    },
    formTitle:{  //弹窗标题
        type:String,
    },
    middleColumnItm:{  //表列中间的动态列
        type:Object as ()=>MiddleColumnItm
    },
    defaultTableData:{
        type:Array,
        default:()=>[]
    },
    disabledDeleteRowScene:{    // 禁止删除行 的条件：  true 禁止  false 允许
        type:Function
    },
    disabledEditRowScene:{  // 禁止编辑行 的条件 ：true 禁止   false 允许
        type:Function
    },
    addOperationName:{
        type:String,
        default:'增加'
    }
})

const emit = defineEmits([
    'editConfirm',  // 执行到最后要添加 row.editFlag = ''
    'addConfirm',  // 执行到最后要添加 row.tmpId = ''
    'deleteConfirm',
    'entiretyConfirm'])

/**
 * 1. 参数配置： 表单弹窗信息
 */
const formVisible = defineModel('formVisible')  //
const deleteFlag = defineModel('deleteFlag') // 当下 删除弹窗确认 是否成功的标识  // success | fail | none
const formDialogConfirmFlag = defineModel('formDialogConfirmFlag')
const formSubmitLoading = ref(false)


const finalTableColumns = ref([...tableColumns.value])  //最终渲染的表头
const tableData = ref<any[]>([])  //表数据
const configTableDom = ref()

// 处理表行的上下移动
const HandleRowMove = (val)=>{
    tableData.value = val
}

// 处理参数配置的增删改查
// 配置项添加 
const HandleAddConfig = async ()=>{
    if(props.middleColumnItm?.label === '跟进状态'){
        tableData.value.splice(tableData.value.length - 3,0,{
            // 临时id _ 待完善
            id:`tmp_${new Date().getTime()}_${tableData.value.length + 1}`,
            tmpId:(Number(tableData.value[tableData.value.length - 1]?.tmpId) || 0) + 1,   //新增时候的临时id
            [props.middleColumnItm?.name]:'',
            defaultStatus:1,   // defaultStatus：  0默认项  1非默认项 ,后续可能会用
        })
    }else{
        tableData.value.push({
            // 临时id _ 待完善
            id:`tmp_${new Date().getTime()}_${tableData.value.length + 1}`,
            tmpId:(Number(tableData.value[tableData.value.length - 1]?.tmpId) || 0) + 1,   //新增时候的临时id
            [props.middleColumnItm?.name]:'',
            defaultStatus:1,   // defaultStatus：  0默认项  1非默认项 ,后续可能会用
        })
    }
    await nextTick()
    // 新增元素后滚动到表格最底层
    configTableDom.value.setScrollTop(configTableDom.value.layout.table.refs.bodyWrapper.firstElementChild.firstElementChild.scrollHeight)
}

// 配置项保存 /编辑 
const HandleConfigEditOrSave = async (row)=>{
    // 初次新增确认 或者 准备变成编辑状态
    if(!row.editFlag){
        if(row.tmpId){
            // 初次新增确认  调用新增接口
            if(!(row?.[props?.middleColumnItm?.name]) ){
                ElMessage.warning('请填写内容')
                return
            }
            let params = {
                [props.middleColumnItm.name]:row?.[props?.middleColumnItm?.name],
            }
            // 调用新增接口
            emit('addConfirm',row,params)
        }else{
            // 准备变成编辑状态
            row.editFlag = 'edit'
            row.tmpId = row.id
        }
    }else{
        // 准备保存修改  调用修改接口
        if(!row?.[props?.middleColumnItm?.name]){
            ElMessage.warning('请填写类别内容')
            return
        }
        let params = {
            id:row.id,
            [props.middleColumnItm.name]:row?.[props?.middleColumnItm?.name],
        }
        emit('editConfirm',row,params)
    }
}
// 取消配置项操作
const HandleConfigCancel = (row)=>{
    if(!row.editFlag){
        // 不是已有的数据，要删除
        tableData.value = tableData.value.filter(item=>{
            return item.id !== row.id
        })
    }else{
        row.tmpId = ''
        row.editFlag = ''
    }
}

// 配置项删除
const HandleConfigDelete = async (row)=>{
    dialogVisible.value = true
    currentEditRow.value = row
}

const HandleFormConfirm = ()=>{
    formSubmitLoading.value = true
    // 整体表单提交
    emit('entiretyConfirm',tableData.value)
}

const HandleFormClose = ()=>{
    formVisible.value = false
    formSubmitLoading.value = false

}

watch(()=>deleteFlag.value,(newVal)=>{
    if(newVal == 'success'){
        HandleDialogClose()
        dialogSubmitLoading.value = false
        deleteFlag.value = 'none'
    }else if(newVal == 'fail'){
        dialogSubmitLoading.value = false
        deleteFlag.value = 'none'
    }
})

watch(()=>formDialogConfirmFlag.value,(newVal)=>{
    if(newVal == 'success'){
        HandleFormClose()
        formDialogConfirmFlag.value = 'none'
    }else if(newVal == 'fail'){
        formSubmitLoading.value = false
        formDialogConfirmFlag.value = 'none'
    }
})

/**
 * 2. 参数配置： 删除弹窗 信息
*/
const dialogVisible = ref(false)
const dialogSubmitLoading = ref(false)
const currentEditRow = ref()
const HandleDialogClose = ()=>{
    dialogVisible.value = false
    currentEditRow.value = null
}
const HandleDialogConfirm = async ()=>{
    dialogSubmitLoading.value = true
    let row  = currentEditRow.value
    emit('deleteConfirm',row)
}

// 动态变更最终表列
watch(()=>props.middleColumnItm,(newVal)=>{
    if(newVal){
       finalTableColumns.value = tableColumns.value.map((item,index)=>{
        if(index == 2){
            return [
                {
                    name:props.middleColumnItm?.name,
                    label:props.middleColumnItm?.label,
                    width:'350',
                    fixed:'',
                    align:'left',
                    minWdth:'',
                    custom:true,
                },
                item
            ]
        }
        return item
       }).flat()
    }
},{immediate:true,deep:true})


// 动态变更表数据
watch(()=>props.defaultTableData,(val)=>{
    tableData.value = JSON.parse(JSON.stringify(val)) || []
},{immediate:true,deep:true})

</script>




<style lang="scss" scoped>

.dictionary_box{
    width:100%;
    height: 480px;
    overflow: auto;
    display: flex;
    flex-direction: column;
    gap:10px;
    :deep(.page_table){
        overflow: auto;
    }

    .add_option{
        flex-shrink: 0;
        display: flex;
        justify-content: center;
        align-items: center;
        gap:8px;
        background-color: rgba(46, 100, 250,0.1);
        color:#2E64FA;
        padding:4px auto;
        text-align: center;
        border-radius: 6px;
        cursor: pointer;

        :deep(.el-icon){
            transform: rotate(45deg);
        }
    }

}

.parameter_setting_form_dialog{
    :deep(.el-dialog__body){
        min-height: 500px !important;
        max-height: 500px !important;
        padding:20px !important
    }
}
</style>