<template>
    <div class="enterprise-management-container">
        <div class="page-header">
            <h1>企业单位</h1>
            <div class="header-actions">
                <el-button type="primary" size="default" @click="openDialog('add')" icon="Plus" class="add-btn">
                    添加企业
                </el-button>
            </div>
        </div>

        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" size="small" inline class="search-form">
                <el-form-item label="企业编码" prop="id">
                    <el-input v-model="searchForm.id" placeholder="请输入企业编码" :maxlength="20" class="search-input" @key-up:enter="handleQuery"/>
                </el-form-item>
                <el-form-item label="企业名称" prop="name">
                    <el-input v-model="searchForm.name" placeholder="请输入企业名称" :maxlength="255" class="search-input" @key-up:enter="handleQuery"/>
                </el-form-item>
                <!-- <el-form-item label="企业类型" prop="type">
          <el-select 
            v-model="searchForm.type" 
            placeholder="请选择企业类型"
            class="search-select"
          >
            <el-option 
              v-for="item in enterpriseTypes" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
                <el-form-item>
                    <el-button type="primary" @click="handleQuery" icon="Search">
                        查询
                    </el-button>
                    <el-button @click="resetSearch" icon="RefreshRight">
                        重置
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 数据表格 -->
        <el-card class="table-card">
            <div class="table-container">
                <el-table v-loading="loading" :data="enterpriseList" border stripe class="enterprise-table"
                    @selection-change="handleSelectionChange">
                    <!-- <el-table-column type="selection" width="50" /> -->
                    <el-table-column type="index" label="序号" width="80" align="center" />
                    <el-table-column prop="id" label="企业编码" min-width="120" />
                    <el-table-column prop="name" label="企业名称" min-width="180" />
                    <!-- <el-table-column prop="type" label="企业类型" min-width="120" align="center">
            <template #default="scope">
              <el-tag 
                :type="getTypeTagType(scope.row.type)"
                class="type-tag"
              >
                {{ getTypeName(scope.row.type) }}
              </el-tag>
            </template>
</el-table-column> -->
                    <el-table-column prop="stakeholder" label="企业干系人" min-width="120" />
                    <el-table-column prop="stakeholderTel" label="联系电话" min-width="140" />
                    <el-table-column label="操作" min-width="160" align="center" fixed="right">
                        <template #default="scope">
                            <el-button size="small" type="primary" text @click="openDialog('edit', scope.row)"
                                class="operation-btn edit-btn">
                                <el-icon size="16">
                                    <Edit />
                                </el-icon>
                                编辑
                            </el-button>
                            <el-button size="small" type="danger" text @click="confirmDelete(scope.row)"
                                class="operation-btn delete-btn">
                                <el-icon size="16">
                                    <Delete />
                                </el-icon>
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="state.queryParams.pageNum"
                    v-model:page-size="state.queryParams.pageSize" :page-sizes="[10, 20, 50, 100]" :total="state.total"
                    layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" class="pagination" />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" :width="dialogWidth" :close-on-click-modal="false"
            destroy-on-close>
            <el-form ref="enterpriseForm" :model="formData" :rules="formRules" label-width="100px"
                class="enterprise-form">
                <el-form-item label="企业名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入企业名称" :maxlength="255" class="form-input" />
                </el-form-item>

                <!-- <el-form-item label="企业类型" prop="type">
          <el-select
            v-model="formData.type"
            placeholder="请选择企业类型"
            class="form-select"
          >
            <el-option
              v-for="item in enterpriseTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->

                <el-form-item label="企业干系人" prop="stakeholder">
                    <el-input v-model="formData.stakeholder" placeholder="请输入企业干系人" :maxlength="20"
                        class="form-input" />
                </el-form-item>

                <el-form-item label="联系电话" prop="stakeholderTel">
                    <el-input v-model="formData.stakeholderTel" placeholder="请输入联系电话" :maxlength="20"
                        class="form-input" />
                    <div class="form-hint">请输入有效的联系电话</div>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="closeDialog">取消</el-button>
                    <el-button type="primary" @click="submitForm">保存</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { Edit, Delete, Search, RefreshRight, WarningFilled, Plus } from '@element-plus/icons-vue';
import { enterpriseTypes } from '@/constant/dict/enterprise';
import { add, update, get, del } from '@/api/public/basic';
import { Enterprise } from '@/@types/enterprise';

// 搜索表单数据
const searchForm = reactive({
    id: '',
    name: '',
    type: ''
});

// 表格数据
const enterpriseList = ref([]);
const loading = ref(false);
const multipleSelection = ref([]);


// 对话框数据
const dialogVisible = ref(false);
const dialogType = ref(''); // 'add' | 'edit'
const dialogTitle = computed(() => dialogType.value === 'add' ? '新增企业' : '编辑企业');
const dialogWidth = ref('500px');
const confirmDialogVisible = ref(false);
// 表单数据
const formData = reactive({} as Enterprise);
const state = reactive({
    loading: false,
    queryParams: {
        pageSize: 10,
        pageNum: 1,
        id: null,
        name: null,
    } as any,
    eventForm: {

    },
    total: 0

})

// 表单规则
const formRules = reactive({
    id: [
        { required: true, message: '请输入企业编码', trigger: 'blur' },
        { max: 20, message: '企业编码长度不能超过20个字符', trigger: 'blur' }
    ],
    name: [
        { required: true, message: '请输入企业名称', trigger: 'blur' },
        { max: 255, message: '企业名称长度不能超过255个字符', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择企业类型', trigger: 'change' }
    ],
    stakeholder: [
        { required: true, message: '请输入企业干系人', trigger: 'blur' },
        { max: 20, message: '企业干系人长度不能超过20个字符', trigger: 'blur' }
    ],
    stakeholderTel: [
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        {
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入有效的手机号码',
            trigger: 'blur'
        }
    ]
});

const enterpriseForm = ref();

// 初始化
onMounted(() => {
    handleQuery();
});

// 获取企业列表
const handleQuery = async () => {
    loading.value = true;
    // 模拟API请求
    try {
        get({
            ...state.queryParams,
        }, 'i5nFaj9Pc87').then(res => {
            if (res.status == 0) {
                enterpriseList.value = res.data?.result || []
                state.total = res?.data.count
                loading.value = false;
            }
        })

    } catch (error) {
        ElMessage({
            type: 'error',
            message: '获取数据失败，请重试'
        });
    } finally {
    }
};

// 打开对话框
const openDialog = (type, row = null) => {
    dialogType.value = type;
    dialogVisible.value = true;

    // 重置表单
    if (enterpriseForm.value) {
        enterpriseForm.value.resetFields();
    }

    // 初始化表单数据
    if (type === 'add') {
        formData.id = '';
        formData.name = '';
        formData.type = '';
        formData.stakeholder = '';
        formData.stakeholderTel = '';
    } else if (type === 'edit' && row) {
        // 复制行数据到表单
        formData.idx = row.idx;
        formData.id = row.id;
        formData.name = row.name;
        formData.type = row.type;
        formData.stakeholder = row.stakeholder;
        formData.stakeholderTel = row.stakeholderTel;
    }
};

// 关闭对话框
const closeDialog = () => {
    dialogVisible.value = false;
    confirmDialogVisible.value = false;
};

// 提交表单
const submitForm = async () => {
    if (!enterpriseForm.value) return;
    try {
        await enterpriseForm.value?.validate();
        if (formData.id) {
            update(formData.id, formData, 'i5nFaj9Pc87').then(res => {
                if (res.status == 0) {
                    ElMessage.success('操作成功');
                    closeDialog();
                    handleQuery();
                } else {
                    ElMessage.error('操作失败');
                }
            })
        } else {
            add(formData, 'i5nFaj9Pc87').then(res => {
                if (res.status == 0) {
                    ElMessage.success('操作成功');
                    closeDialog();
                    handleQuery();
                } else {
                    ElMessage.error('操作失败');
                }
            })
        }
    } catch (error) {
        console.error('表单验证失败:', error);
        return;
    }
};

// 确认删除
const confirmDelete = (row) => {
    ElMessageBox.confirm('确定要删除该企业吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            del({id:[row.id]},'i5nFaj9Pc87').then(res => {
                if(res.status == 0){
                    ElMessage.success('删除成功');
                    handleQuery();
                }
        })})
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消删除',
            });
    })
};


// 重置搜索
const resetSearch = () => {
    state.queryParams = {
        paeNum: 1,
        pageSize: 10,
    }
    handleQuery();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
    state.queryParams.pageSize = size;
    handleQuery();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
    state.queryParams.pageNum = page;
    handleQuery();
};

// 获取企业类型名称
const getTypeName = (type) => {
    const typeItem = enterpriseTypes.find(item => item.value === type);
    return typeItem ? typeItem.label : '未知类型';
};

// 获取企业类型标签样式
const getTypeTagType = (type) => {
    const typeMap = {
        1: 'primary',
        2: 'success',
        3: 'info',
        4: 'warning',
        5: 'danger'
    };
    return typeMap[type] || 'default';
};

// 处理选择变化
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};
</script>

<style scoped lang="scss">
.enterprise-management-container {
    padding: 20px;
    background-color: #f5f7fa;
}

.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h1 {
        font-size: 22px;
        font-weight: 600;
        color: #1d2129;
        margin: 0;
    }

    .header-actions {
        display: flex;
        gap: 10px;
    }
}

.search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .search-form {
        padding: 15px 20px;

        .search-input,
        .search-select {
            width: 200px;
        }
    }
}

.table-card {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    overflow: hidden;

    .table-container {
        max-height: calc(100vh - 360px);
        overflow-y: auto;

        .enterprise-table {
            width: 100%;

            .type-tag {
                margin: 0 5px;
            }

            .operation-btn {
                margin: 0 5px;
                transition: all 0.2s;

                &:hover {
                    transform: translateY(-2px);
                }
            }
        }
    }

    .pagination-container {
        padding: 15px 20px;
        display: flex;
        justify-content: flex-end;
        border-top: 1px solid #f0f2f5;
    }
}

.enterprise-form {
    padding: 10px 0;

    .form-item {
        margin-bottom: 18px;
    }

    .form-input,
    .form-select {
        width: 100%;
    }

    .form-hint {
        color: #909399;
        font-size: 12px;
        margin-top: 5px;
    }
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
    padding: 15px 20px 20px;
    border-top: 1px solid #f0f2f5;
}

.confirm-content {
    display: flex;
    align-items: flex-start;
    padding: 15px 0;

    .confirm-icon {
        margin-right: 15px;
        padding-top: 3px;

        .icon-warning {
            font-size: 24px;
        }
    }

    .confirm-text {
        .confirm-subtext {
            color: #909399;
            margin-top: 5px;
            font-size: 13px;
        }

        .highlight-text {
            color: #ff4d4f;
            font-weight: 500;
        }
    }
}

// 动画和过渡效果
::v-deep .el-table {
    animation: tableFadeIn 0.5s ease-in-out;
}

::v-deep .el-card {
    transition: transform 0.2s, box-shadow 0.2s;

    &:hover {
        transform: translateY(-3px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
}

::v-deep .el-button {
    transition: all 0.2s;
}

::v-deep .el-input,
::v-deep .el-select,
::v-deep .el-tag {
    transition: all 0.2s;
}

@keyframes tableFadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

// 响应式设计
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        align-items: flex-start;

        .header-actions {
            margin-top: 15px;
            width: 100%;
            justify-content: flex-start;
        }
    }

    .search-form {
        flex-direction: column;
        align-items: flex-start !important;

        .el-form-item {
            width: 100%;
            margin-bottom: 15px;

            .search-input,
            .search-select {
                width: 100% !important;
            }
        }

        .el-button {
            width: 100%;
            margin-bottom: 10px;
        }
    }

    .dialogWidth {
        width: 90% !important;
    }
}
</style>