<template>
    <div class="app-container">
        <!-- 顶部操作栏 -->
        <div class="operation-bar">
            <el-input v-model="searchQuery" placeholder="搜索项目名称或编号" class="search-input" prefix-icon="Search" />
            <el-button type="primary" size="default" @click="handleAdd" icon="Plus">
                新增项目
            </el-button>
        </div>

        <!-- 项目列表表格 -->
        <el-table v-loading="loading" :data="projectList" border stripe class="project-table"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="项目名称" min-width="180" />
            <el-table-column prop="id" label="项目编号" width="150" />
            <el-table-column prop="builderName" label="建设单位" min-width="150" />
            <el-table-column label="项目周期" width="220">
                <template #default="scope">
                    {{ formatDate(scope.row.determineDate) }} - {{ formatDate(scope.row.harvestDate) }}
                </template>
            </el-table-column>
            <el-table-column prop="status" label="项目状态" width="120">
                <template #default="scope">
                    <el-tag :type="getStatusTagType(scope.row.status)">{{statusOptions.find(item => item.value ==
                        scope.row.status)?.label ?? '-'}}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="250" fixed="right">
                <template #default="scope">
                    <el-button size="small" text @click="handleView(scope.row)">查看</el-button>
                    <el-button size="small" text type="primary" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button size="small" text type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50]"
                :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>

        <!-- 项目信息弹窗 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" :width="dialogWidth" destroy-on-close>
            <el-form ref="projectFormRef" :model="formData" :rules="formRules" label-width="120px" class="project-form">
                <!-- 基础信息卡片 -->
                <el-card class="form-card" header="项目基础信息">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="项目名称" prop="name">
                                <el-input v-model="formData.name" placeholder="请输入项目名称" maxlength="100" />
                            </el-form-item>
                        </el-col>
                        <!-- <el-col :span="12">
              <el-form-item label="项目编号" prop="id" v-if="formData.id">
                <el-input v-model="formData.id" placeholder="请输入项目编号" maxlength="50" disabled/>
              </el-form-item>
            </el-col> -->
                        <el-col :span="12">
                            <el-form-item label="建设单位" prop="builderId">
                                <el-select @change="handleBuildChange" v-model="formData.builderId" filterable remote
                                    :remote-method="remoteMethodByBuild" placeholder="请搜索选择">
                                    <el-option v-for="item in buildOption" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目类型" prop="type">
                                <el-select v-model="formData.type" multiple placeholder="请选择项目类型">
                                    <el-option v-for="type in projectTypeOptions" :key="type.value" :label="type.label"
                                        :value="type.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目经理" prop="managerId">
                                <el-select @change="handleUserChange" v-model="formData.managerId" filterable remote
                                    :remote-method="remoteMethodByUser" placeholder="请搜索选择">
                                    <el-option v-for="item in userOption" :key="item.userId" :label="item.nickname"
                                        :value="item.userId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目开始日期" prop="determineDate">
                                <el-date-picker v-model="formData.determineDate" type="date" placeholder="选择开始日期"
                                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目结束日期" prop="harvestDate">
                                <el-date-picker v-model="formData.harvestDate" type="date" placeholder="选择结束日期"
                                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="项目概况" prop="content">
                                <el-input v-model="formData.content" type="textarea" rows="3" placeholder="请输入项目概况"
                                    maxlength="300" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="行政区" prop="area">
                                <el-select v-model="formData.area" placeholder="请选择行政区">
                                    <el-option v-for="region in administrativeRegionOptions" :key="region.value"
                                        :label="region.label" :value="region.value" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目影响等级" prop="level">
                                <el-select v-model="formData.level" placeholder="请选择影响等级">
                                    <el-option v-for="level in impactLevelOptions" :key="level.value"
                                        :label="level.label" :value="Number(level.value)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="项目当前状态" prop="status">
                                <el-select v-model="formData.status" placeholder="请选择项目状态">
                                    <el-option v-for="status in statusOptions" :key="status.value" :label="status.label"
                                        :value="Number(status.value)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="管理类型" prop="adminType">
                                <el-select v-model="formData.adminType" placeholder="请选择管理类型">
                                    <el-option v-for="type in managementTypeOptions" :key="type.value"
                                        :label="type.label" :value="Number(type.value)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="项目位置" prop="location">
                                <el-input v-model="formData.location" placeholder="请输入项目位置(线路站点)" maxlength="200" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="审查状态" prop="auditType">
                                <el-select v-model="formData.auditType" placeholder="请选择">
                                    <el-option v-for="region in auditOptions" :key="region.value" :label="region.label"
                                        :value="Number(region.value)" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="24">
                            <el-form-item label="审查意见" prop="auditTip">
                                <el-input v-model="formData.auditTip" type="textarea" rows="3" placeholder="请输入审查意见"
                                    maxlength="300" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-card>

                <!-- 参建单位信息卡片 -->
                <el-card class="form-card" header="参建单位信息" style="margin-top: 20px;">
                    <div class="add-company-btn">
                        <el-button type="primary" size="small" @click="addParticipatingCompany" icon="Plus">
                            添加参建单位
                        </el-button>
                    </div>

                    <el-table v-if="participatingCompanies.length > 0" :data="participatingCompanies" border
                        size="small" max-height="300">
                        <el-table-column label="单位类型" prop="type" >
                            <template #default="scope">
                                <div v-if="scope.row.id">{{ companyTypeOptions.find(item=>item.value===scope.row.type)?.label }}</div>
                                <el-select v-else v-model="scope.row.type" placeholder="请选择"
                                    @change="handleCompanyTypeChange(scope.row)" size="small">
                                    <el-option v-for="type in companyTypeOptions" :key="type.value" :label="type.label"
                                        :value="Number(type.value)" />
                                </el-select>
                            </template>
                        </el-table-column>
                        <el-table-column label="单位名称" prop="name" >
                            <template #default="scope">
                                <div v-if="scope.row.id">{{ scope.row.name }}</div>
                                <el-input v-else v-model="scope.row.name" placeholder="请输入单位名称" size="small"
                                    :disabled="dialogType === 'view'" />
                            </template>
                        </el-table-column>
                        <el-table-column label="联系人" prop="stakeholder" >
                            <template #default="scope">
                                <div v-if="scope.row.id">{{ scope.row.stakeholder }}</div>
                                <el-input v-else v-model="scope.row.stakeholder" placeholder="请输入联系人" size="small"
                                    :disabled="dialogType === 'view'" />
                            </template>
                        </el-table-column>
                        <el-table-column label="联系方式" prop="stakeholderTel">
                            <template #default="scope">
                                <div v-if="scope.row.id">{{ scope.row.stakeholderTel }}</div>
                                <el-input v-else v-model="scope.row.stakeholderTel" placeholder="请输入联系方式" size="small"
                                    :disabled="dialogType === 'view'" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作"  v-if="dialogType !== 'view'">
                            <template #default="scope">
                                <el-button size="small" type="danger" icon="Delete"
                                    @click="removeParticipatingCompany(scope.$index)" />
                            </template>
                        </el-table-column>
                    </el-table>

                    <div v-else class="empty-company-tip">
                        <el-empty description="暂无参建单位信息，点击上方按钮添加" />
                    </div>
                </el-card>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button v-if="dialogType !== 'view'" type="primary" @click="handleDialogConfirm">
                        {{ dialogType === 'add' ? '创建' : '保存' }}
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed,watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { get, add, update, del } from '@/api/public/basic'

// 状态定义
const loading = ref(false);
const searchQuery = ref('');
const projectList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const selectedRows = ref([]);
const userOption = ref([]);
const buildOption = ref([]);

// 弹窗相关
const dialogVisible = ref(false);
const dialogType = ref(''); // add, edit, view
const dialogTitle = ref('');
const dialogWidth = ref('80%');
const projectFormRef = ref(null);
const participatingCompanies = ref([]);

// 表单数据模型
const formData = reactive({});
const state = reactive({
    paramsQuery: {
        pageSize: 10,
        pageNum: 1,
        name: null
    }
})

// 审查状态
// 待提交、待审查、已通过、已驳回
const auditOptions = [
    {
        value: 1,
        label: '待提交'
    },
    {
        value: 2,
        label: '待审查'
    },
    {
        value: 3,
        label: '已通过'
    }
]

// 下拉选项数据
const projectTypeOptions = [
    { value: '1', label: '土建工程' },
    { value: '2', label: '电气工程' },
    { value: '3', label: '机械工程' },
    { value: '4', label: '道路工程' },
    { value: '5', label: '桥梁工程' },
    { value: '6', label: '隧道工程' }
];

const administrativeRegionOptions = [
    { value: 'bj', label: '北京市' },
    { value: 'sh', label: '上海市' },
    { value: 'gz', label: '广州市' },
    { value: 'sz', label: '深圳市' },
    { value: 'hz', label: '杭州市' }
];

const impactLevelOptions = [
    { value: '1', label: '高' },
    { value: '2', label: '中' },
    { value: '3', label: '低' }
];

const statusOptions = [
    { value: '1', label: '规划中' },
    { value: '2', label: '建设中' },
    { value: '3', label: '已暂停' },
    { value: '4', label: '已完成' },
    { value: '5', label: '已取消' }
];

const managementTypeOptions = [
    { value: '1', label: '监管' },
    { value: '2', label: '监测' }
];

const companyTypeOptions = [
    { value: 1, label: '设计单位' },
    { value: 2, label: '施工单位' },
    { value: '3', label: '监理单位' },
    { value: '5', label: '咨询单位' },
    { value: '6', label: '供应商' }
];

// 表单验证规则
const formRules = reactive({
    name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        { min: 2, max: 100, message: '项目名称长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    constructionUnit: [
        { required: true, message: '请输入建设单位', trigger: 'blur' }
    ],
    startDate: [
        { required: true, message: '请选择项目开始日期', trigger: 'change' }
    ],
    endDate: [
        { required: true, message: '请选择项目结束日期', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                if (value && formData.startDate && new Date(value) < new Date(formData.startDate)) {
                    callback(new Error('结束日期不能早于开始日期'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ],
    administrativeRegion: [
        { required: true, message: '请选择行政区', trigger: 'change' }
    ],
    status: [
        { required: true, message: '请选择项目当前状态', trigger: 'change' }
    ],
    managementType: [
        { required: true, message: '请选择管理类型', trigger: 'change' }
    ]
});


watch(()=>searchQuery.value,(val)=>{
    state.paramsQuery.name=val ||null
    fetchProjectList()

})

// 获取人员信息
const remoteMethodByUser = (query) => {
    const params = {
        pageSize: 30,
        pageNum: 1,
    }
    if (query) {
        params.nickname = query
    }
    get(params, 'i5nFpHiD7N5').then(res => {
        userOption.value = res?.data?.result
    })

}
const handleUserChange = (value) => {
    Object.assign(formData, {
        managerName: userOption.value.find(item => item.userId == value)?.nickname,
    })
}

// 获取建设单位
const remoteMethodByBuild = (query) => {
    const params = {
        pageSize: 30,
        pageNum: 1,
    }
    if (query) {
        params.name = query
    }
    get(params, 'i5nFaj9Pc87').then(res => {
        buildOption.value = res?.data?.result
    })

}
const handleBuildChange = (value) => {
    Object.assign(formData, {
        builderName: buildOption.value.find(item => item.id == value)?.name,
    })
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
};

// 获取状态标签类型
const getStatusTagType = (status) => {
    const statusMap = {
        'planning': 'info',
        'under_construction': 'primary',
        'paused': 'warning',
        'completed': 'success',
        'cancelled': 'danger'
    };
    return statusMap[status] || 'default';
};

// 添加参建单位
const addParticipatingCompany = () => {
    participatingCompanies.value.push({
        type: '',
        name: '',
        stakeholder: '',
        stakeholderTel: ''
    });
};

// 移除参建单位
const removeParticipatingCompany = (index) => {
    ElMessageBox.confirm('确定要删除该参建单位信息吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            participatingCompanies.value.splice(index, 1);
        })
        .catch(() => { });
};

// 处理参建单位类型变更
const handleCompanyTypeChange = (row) => {
    // 可以在这里添加类型变更后的额外处理逻辑
};

// 处理搜索
const handleSearch = () => {
    currentPage.value = 1; // 重置到第一页
    fetchProjectList();
};

// 处理分页大小变化
const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchProjectList();
};

// 处理页码变化
const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchProjectList();
};

// 处理选择变化
const handleSelectionChange = (rows) => {
    selectedRows.value = rows;
};

// 打开新增对话框
const handleAdd = () => {
    dialogType.value = 'add';
    dialogTitle.value = '新增项目信息';
    dialogVisible.value = true;

    // 重置表单
    resetForm();
    participatingCompanies.value = [];
};

// 打开编辑对话框
const handleEdit = async (row) => {
    dialogVisible.value = true;
    dialogType.value = 'edit';
    dialogTitle.value = '编辑项目信息';
    // 重置表单并填充数据
    // resetForm();
    Object.assign(formData, { ...row, type: row.type?.split(',') });
    userOption.value = [{
        userId: row.managerId,
        nickname: row.managerName
    }]
    buildOption.value = [{
        id: row.builderId,
        name: row.builderName
    }]
    remoteMethodByUser()
    remoteMethodByBuild()
    // 获取关联参建单位

    const resBuild = []
    if (row.builderPartIds) {
        const arr = row.builderPartIds?.split(',')
        for (let i = 0; i < arr.length; i++) {
            const res = await get(arr[i], 'i5nFaj9Pc87')
            if (res.data?.[0]) {
                const { id, name, stakeholder, stakeholderTel,type } = res.data[0] || {}
                resBuild.push({
                    id,
                    name,
                    stakeholder,
                    stakeholderTel,
                    type
                })
            }
        }
    participatingCompanies.value = resBuild
    }
};

// 打开查看对话框
const handleView = (row) => {
    dialogType.value = 'view';
    dialogTitle.value = '查看项目信息';
    dialogVisible.value = true;

    // 填充数据
    Object.assign(formData, { ...row });
    participatingCompanies.value = JSON.parse(JSON.stringify(row.participatingCompanies || []));
};

// 处理删除
const handleDelete = (id) => {
    ElMessageBox.confirm('确定要删除该项目信息吗？此操作不可撤销。', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
    })
        .then(async () => {
            loading.value = true;
            try {
                del({
                    id:[id]
                }, 'i5nD7bSWgsQ')
                ElMessage.success('删除成功');
                fetchProjectList(); // 重新获取列表
            } catch (error) {
                ElMessage.error('删除失败: ' + (error.message || '未知错误'));
            } finally {
                loading.value = false;
            }
        })
        .catch(() => { });
};

// 处理对话框关闭
const handleDialogClose = () => {
    // 可以在这里添加关闭前的处理逻辑
    resetForm();

};

// 重置表单
const resetForm = () => {
    if (projectFormRef.value) {
        projectFormRef.value.resetFields();
    }

    // 重置所有表单数据
    Object.keys(formData).forEach(key => {
        if (Array.isArray(formData[key])) {
            formData[key] = [];
        } else {
            formData[key] = '';
        }
    });
};

// 处理对话框确认
const handleDialogConfirm = async () => {
    // 表单验证
    const valid = await projectFormRef.value.validate();
    if (!valid) return;

    loading.value = true;
    try {
        // 处理参建单位
        if (participatingCompanies.value.length > 0) {
            const hasInvalidCompany = participatingCompanies.value.some(company =>
                !company.type || !company.name
            );
            if (hasInvalidCompany) {
                ElMessage.error('请完善所有参建单位的类型和名称信息');
                return;
            }
        }

        const params = {
            ...formData,
            type: formData.type?.join(',') ?? null,
        }
        if (formData.id) {
            update(formData.id,{
                ...params,
                builderPartIds: participatingCompanies.value.map(i=>i.id)?.join(',') ?? null,
            }, 'i5nD7bSWgsQ').then(res => {
                if (res.status == 0) {
                    ElMessage.success('操作成功')
                    dialogVisible.value = false
                    fetchProjectList(); // 刷新列表
                } else {
                    ElMessage.error('添加失败')
                }
            })
        } else {
            const builderPartIds = []
            if (participatingCompanies.value.length > 0) {
                for (let i = 0; i < participatingCompanies.value.length; i++) {
                    const res = await add(participatingCompanies.value[i], 'i5nFaj9Pc87')
                    if (res.status == 0) {
                        builderPartIds.push(res.data)
                    }
                }
            }
            add({
                ...params,
                builderPartIds: builderPartIds.join(',') ?? null,
            }, 'i5nD7bSWgsQ').then(res => {
                if (res.status == 0) {
                    ElMessage.success('添加成功')
                    dialogVisible.value = false
                    fetchProjectList(); // 刷新列表
                } else {
                    ElMessage.error('添加失败')
                }
            })
        }
    } catch (error) {
        ElMessage.error('操作失败: ' + (error.message || '未知错误'));
    } finally {
        loading.value = false;
    }
};

// 获取项目列表
const fetchProjectList = async () => {
    loading.value = true;
    const param = state.paramsQuery
    try {
        const res = await get(param, 'i5nD7bSWgsQ');
        projectList.value = res.data?.result || []
        total.value = res.data?.count || 0
    } catch (error) {
        ElMessage.error('获取项目列表失败: ' + (error.message || '未知错误'));
    } finally {
        loading.value = false;
    }
};

// 页面加载时获取数据
onMounted(() => {
    fetchProjectList();
});

// 监听搜索框回车事件
const searchInput = ref(null);
</script>

<style scoped>
.app-container {
    padding: 20px;
    min-height: 100vh;
    background-color: #f5f7fa;
}

.operation-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
}

.project-table {
    background-color: #fff;
    margin-bottom: 20px;
}

.pagination {
    text-align: right;
    margin-top: 15px;
}

.form-card {
    margin-bottom: 20px;
}

.add-company-btn {
    margin-bottom: 15px;
    text-align: right;
}

.empty-company-tip {
    padding: 40px 0;
    text-align: center;
}

.project-form {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
    padding-right: 10px;
}

/* 滚动条美化 */
.project-form::-webkit-scrollbar {
    width: 6px;
}

.project-form::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
}

.project-form::-webkit-scrollbar-track {
    background-color: #f5f5f5;
}

/* 适配小屏幕 */
@media (max-width: 1200px) {
    .dialog-width {
        width: 95% !important;
    }
}
</style>