<template>
    <div class="setting_card" >
        <div class="card_label">{{cardTitle}}</div>
        <div class="tag_container">
            <span class="tag_item" 
                v-for="(item, index) in cardItems" 
                :key="'region_' + index"
            >{{ item?.[middleColumnItm?.name] }}</span>
        </div>
        <span class="button_editor" @click="formVisible= true">编辑</span>
    </div>

    <!-- 参数配置弹窗 -->
    <FormDialog
        width="680px"
        class="parameter_setting_form_dialog"
        v-if="formVisible"
        :defaultFormData="{}" 
        :visible="formVisible" 
        :title="cardTitle"
        :submitLoading="formSubmitLoading"
        @close="formVisible = false"
    >
        <template #form_pre>
            <div class="dictionary_box">
                <Table
                    v-model:tableRef="configTableDom"
                    :tableColumns="finalTableColumns" 
                    :tableData="tableData"
                    :hidePagination="true">
                    <template #moveable="{row,currentIndex}">

                        <TableRowDragUpDown  
                            :startIndex="middleColumnItm?.label == '跟进状态' ? 1 : 0"
                            :endIndex="middleColumnItm?.label == '跟进状态' ? tableData.length - 4 : tableData.length - 1"
                            v-if="!(middleColumnItm?.label == '跟进状态'  
                                &&([1,tableData.length, tableData.length-1, tableData.length-2].includes(currentIndex) ))"
                            
                            :currentIndex="currentIndex" 
                            :tableRow="row" :defaultTableData="tableData" 
                            @moveChange="HandleRowMove"/>
                    </template>

                    <template #num="{row,currentIndex}">
                        {{ currentIndex }}
                    </template>

                    <template v-slot:[middleColumnItm?.name]="{row}">
                        <!-- 地区管理的下拉为省份 -->
                         <template v-if="middleColumnItm?.label == '省份'">
                             <el-select v-model="row[middleColumnItm.name]" v-if="row.tmpId">
                                <el-option
                                    label="输入框"
                                    :value="1"
                                />
                                <el-option
                                    label="单选"
                                    :value="2"
                                />
                            </el-select>
                            <span v-else>{{ row?.[middleColumnItm?.name] }}</span>
                         </template>
                        <template v-else>
                            <el-input v-model="row[middleColumnItm.name]" v-if="row.tmpId" placeholder="请输入内容" />
                            <span v-else>{{ row?.[middleColumnItm?.name] }}</span>
                        </template>
                    </template>

                    <template #operation="{row,currentIndex}">
                        <div class="table_row_option">
                            <!-- row.defaultStatus ?  -->
                            <span :class="'el_button_editor'" @click="HandleConfigEditOrSave(row)">{{row.tmpId ? '保存' : '编辑'}}</span>
                            <span v-if="row.tmpId" class="el_button_editor" @click="HandleConfigCancel(row)">取消</span>
                            <!-- row.defaultStatus  -->
                            <!-- editor_disable -->
                            <span v-else :class="middleColumnItm?.label == '跟进状态'&& [1,tableData.length, tableData.length-1, tableData.length-2].includes(currentIndex)  ? 'editor_disable' : 'el_button_delete'" 
                                    @click="middleColumnItm?.label == '跟进状态'&& [1,tableData.length, tableData.length-1, tableData.length-2].includes(currentIndex)  ? '' : HandleConfigDelete(row)"
                            >删除</span>
                        </div>
                    </template>
                </Table>
                <div class="add_option" @click="HandleAddConfig"> 
                    <el-icon><CloseBold /></el-icon>
                    <span>增加选项配置</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 Table from '@/baseComponents/Table.vue';
import TableRowDragUpDown from '@/baseComponents/TableRowDragUpDown.vue';

import {tableColumns} from './table'

interface MiddleColumnItm {
    name:string,
    label:string
}
const props = defineProps({
    cardItems:{
        type:Array,
        detault:()=>[]
    },
    cardTitle:{
        type:String,
        default:''
    },
    middleColumnItm:{
        type:Object as ()=>MiddleColumnItm
    },
    defaultTableData:{
        type:Array,
        default:()=>[]
    },
})

const emit = defineEmits([''])

/**
 * 1. 参数配置： 表单弹窗信息
 */
const formVisible = defineModel('formVisible')
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)
}

// dictContent
// dictName —— 后续待替换  待完善
// 配置项保存 /编辑 
const HandleConfigEditOrSave = async (row)=>{
    // 初次新增确认 或者 准备变成编辑状态
    if(!row.editFlag){
        if(row.tmpId){
            // 初次新增确认
            // 调用新增接口
            // 接口调用
            if(!(row?.[props?.middleColumnItm?.name]) ){
                ElMessage.warning('请填写内容')
                return
            }
            let params = {
                dictName: row.dictName,
                dictContent: row.dictContent,
            }
            let res = await addDictionaryApi(params)

            if(res.code == 200){
                ElMessage.success(res.msg)
                row.id = res?.data?.id
                row.dictContent = res?.data?.dictContent
                row.tmpId = ''
                row.editFlag = ''
            }
        }else{
            // 准备变成编辑状态
            row.editFlag = 'edit'
            row.tmpId = row.id
        }
    }else{
        // 准备保存修改
        // 调用修改接口
        // 接口调用
        if(!row.dictContent){
            ElMessage.warning('请填写类别内容')
            return
        }
        let params = {
            id:row.id,
            dictName: row.dictName,
            dictContent: row.dictContent,
        }
        let editRes = await editDictionaryApi(params)
        if(editRes.code == 200){
            ElMessage.success(editRes.msg)
            row.dictContent = editRes?.data?.dictContent
            HandleConfigCancel(row)
        }
    }
}
// 取消配置项操作
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
}

/**
 * 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
    let res = undefined
    try{
        res = await deleteDictionaryApi(row.id)
    }catch{}

    if(res?.code == 200){
        ElMessage.success(res.msg)
        tableData.value = tableData.value.filter(item=>{
            return item.id !== row.id
        })
        HandleDialogClose()
    }
    dialogSubmitLoading.value = false
}



// 动态变更最终表列
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>
.setting_card {
    display: flex;
    align-items: flex-start;
    gap: 16px;

    border-radius: 10px;
    padding: 16px;
    border: 1px solid #E4E7ED;
    font-size: 14px;

    .card_label {
        width: 56px;
        height: 32px;
        line-height: 32px;
        color: #333;
    }

    .tag_container {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        gap: 16px;

        .tag_item {
            height: 32px;
            border-radius: 4px 4px 4px 4px;
            border: 1px solid #DCDFE6;
            padding: 6px 12px;
            color: #666;
        }
    }

    .button_editor{
        height: 32px;
        color: #2E64FA;
        line-height: 32px;
        cursor: pointer;
    }
}

.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){
        margin:0 !important;
        top: 50% !important;
        left: 50% !important; /* 若需水平居中可加上此行 */
        transform: translate(-50%, -50%); /* 核心：基于自身宽高反向偏移 */
    }
    :deep(.el-dialog__body){
        min-height: 500px !important;
        max-height: 500px !important;
        padding:20px !important
    }
}

</style>