<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form
            v-show="showSearch"
            ref="queryForm"
            :inline="true"
            :model="queryParams"
            label-width="100px"
        >
            <el-form-item label="模型名称" prop="name">
                <el-input
                    v-model="queryParams.name"
                    clearable
                    placeholder="请输入"
                    size="small"
                    style="width: 200px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="实现类" prop="providerClassName">
                <el-select
                    v-model="queryParams.providerClassName"
                    clearable
                    placeholder="全部"
                    size="small"
                    style="width: 200px"
                >
                    <el-option label="全部" value="" />
                    <el-option
                        v-for="item in providerClassNameList"
                        :key="item.id"
                        :label="item.providerClassName"
                        :value="item.providerClassName"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 工具栏 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    icon="el-icon-plus"
                    plain
                    size="mini"
                    type="primary"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    icon="el-icon-edit"
                    plain
                    size="mini"
                    type="success"
                    @click="handleEdit()"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    icon="el-icon-delete"
                    plain
                    size="mini"
                    type="danger"
                    @click="handleDelete()"
                >删除</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" />
        </el-row>

        <!-- 数据表格 -->
        <el-table v-loading="loading" :data="modelList" border @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column align="center" label="模型名称" prop="name"  />
            <el-table-column align="center" label="实现类" prop="providerClassName" />
            <el-table-column
                align="center"
                class-name="small-padding fixed-width"
                label="操作"
                width="200"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-document-copy"
                        @click="handleCopy(scope.row)"
                    >复制</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleEdit(scope.row)"
                    >编辑</el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <pagination
            v-show="total > 0"
            :limit.sync="queryParams.pageSize"
            :page.sync="queryParams.pageNum"
            :total="total"
            @pagination="getList"
        />

        <!-- 新增/编辑弹窗 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            width="700px"
            append-to-body
            @close="handleDialogClose"
            :fullscreen="isFullscreen"
        >
            <template slot="title">
                <span>{{ dialogTitle }}</span>
                <div style="display: inline-block; margin-left: 10px;">
                    <el-tooltip :content="isFullscreen ? '退出全屏' : '全屏'" placement="top">
                        <el-button
                            type="text"
                            icon="el-icon-full-screen"
                            @click="toggleFullscreen"
                            style="font-size: 16px;"
                        />
                    </el-tooltip>
                </div>
            </template>

            <account-form
                v-if="dialogVisible"
                ref="accountForm"
                :initial-data="currentRow"
                :provider-options="providerOptions"
                @cancel="handleDialogClose"
                @success="handleFormSuccess"
            />
        </el-dialog>
    </div>
</template>

<script>
import { list, remove } from '@/api/company/aiModel'
import { all } from '@/api/company/aiProvider'
import Info from '@/views/company/aiModel/account/info.vue'

export default {
    name: 'AiModelList',
    components: {
        AccountForm: Info
    },
    data() {
        return {
            selectedRows: [],
            isFullscreen: false,
            // 遮罩层
            loading: false,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            modelList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: undefined,
                providerClassName: undefined
            },
            // 实现类列表（用于搜索下拉和弹窗下拉）
            providerClassNameList: [],
            // 弹窗控制
            dialogVisible: false,
            dialogTitle: '新增模型账户',
            currentRow: {},
        }
    },
    computed: {
        providerOptions() {
            return this.providerClassNameList.map(item => item.providerClassName)
        }
    },
    created() {
        this.getList()
        this.getAll()
    },
    methods: {
        toggleFullscreen() {
            this.isFullscreen = !this.isFullscreen;
        },
        /** 查询列表 */
        getList() {
            this.loading = true
            list(this.queryParams)
                .then((response) => {
                    this.modelList = response.rows || []
                    this.total = response.total || 0
                    this.loading = false
                })
                .catch(() => {
                    this.loading = false
                })
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 获取所有实现类 */
        getAll() {
            all().then((response) => {
                //隐藏其他几种大模型
                if(!!response.data){
                    response.data =  response.data.filter(a => a.providerClassName == "DeepSeekChat")
                }
                this.providerClassNameList = response.data || [];
            })
        },
        /** 新增按钮 */
        handleAdd() {
            this.dialogTitle = '新增模型账户'
            this.currentRow = {} // 清空当前行
            this.dialogVisible = true
            this.isFullscreen = false;
        },
        /** 弹窗关闭时清理 */
        handleDialogClose() {
            this.isFullscreen = false;
            this.dialogVisible = false
            this.currentRow = {};
        },
        /** 表单提交成功回调（由子组件触发） */
        handleFormSuccess(response) {
            this.dialogVisible = false
            this.getList()
        },
        /** 修改按钮操作 */
        handleEdit(row) {
            let editRow = row;
            // 如果没有传入 row（即点击工具栏按钮），则从选中行获取
            if (!editRow) {
                if (this.selectedRows.length !== 1) {
                    this.$message.warning('请选择一条要修改的数据');
                    return;
                }
                editRow = this.selectedRows[0];
            }

            this.dialogTitle = '编辑模型账户';
            this.currentRow = { ...editRow };
            this.dialogVisible = true;
            this.isFullscreen = false;
        },
        /** 表格多选选中事件 */
        handleSelectionChange(selection) {
            this.selectedRows = selection;
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            let ids = [];
            if (row) {
                // 单行删除
                ids = [row.id];
            } else {
                // 批量删除（从选中行获取）
                if (this.selectedRows.length === 0) {
                    this.$message.warning('请至少选择一条要删除的数据');
                    return;
                }
                ids = this.selectedRows.map(item => item.id);
            }

            // 确认对话框
            this.$confirm(`此操作将永久删除${ids.length > 1 ? '这些' : '该'}记录，是否继续？`, '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.handleDeleteConfirm(ids);
            }).catch(() => {});
        },
        /** 执行删除操作 */
        async handleDeleteConfirm(ids) {
            try {
                const response = await remove(ids.join(','));
                if (response.code === 200) {
                    this.$message.success('删除成功');
                    this.getList(); // 刷新列表
                } else {
                    this.$message.error(response.msg || '删除失败');
                }
            } catch (error) {
                console.error('删除失败:', error);
                this.$message.error('删除失败');
            }
        },
        /** 复制按钮操作 */
        handleCopy(row) {
            // 前端直接复制数据
            const copiedRow = { ...row };
            // 清空ID，确保是新增操作
            delete copiedRow.id;
            // 添加"-副本"后缀
            copiedRow.name = copiedRow.name + '-副本';
            
            this.dialogTitle = '复制模型账户';
            this.currentRow = copiedRow;
            this.dialogVisible = true;
            this.isFullscreen = false;
        }
    }
}
</script>

<style scoped>
/* 原有样式保持不变 */
.record-container {
    padding: 20px;
}

.record-info {
    margin-bottom: 20px;
    padding: 10px;
    background: #f5f7fa;
    border-radius: 4px;
}

.record-info p {
    margin: 5px 0;
}

.record-controls {
    text-align: center;
}

.record-status {
    margin-bottom: 20px;
    font-size: 14px;
    color: #606266;
}

.recording-indicator {
    color: #f56c6c;
}

.record-buttons {
    margin-bottom: 20px;
}

.record-buttons .el-button {
    width: 60px;
    height: 60px;
    font-size: 24px;
}

.record-preview {
    margin-top: 20px;
}

.el-dialog__wrapper /deep/ .el-dialog--fullscreen .el-dialog__body {
    height: calc(100vh - 120px);
    overflow-y: auto;
    padding: 20px;
}
</style>
