<template>
    <div>
        <div class="coentent">
            <div class="contents-area">
                <div class="areas">
                    <div class="headers">
                        <div class="headers-left">
                            <div class="headers-name">地址管理</div>
                        </div>
                        <div class="headers-right">
                            <div class="filter-item">
                                <span class="filter-label">级别</span>
                                <el-select 
                                    v-model="levelFilter" 
                                    @change="handleFilterChange" 
                                    style="border: 1px solid #ededed;" 
                                    placeholder="全部" 
                                    size="small" 
                                    class="filter-select"
                                    clearable>
                                    <el-option 
                                        v-for="item in levelOptions" 
                                        :key="item.value" 
                                        :label="item.label" 
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </div>
                            <el-button type="primary" size="small" class="add-btn" @click="handleAdd">添加</el-button>
                        </div>
                    </div>

                    <div class="content-table">
                        <el-table
                            :data="tableData"
                            border
                            :header-cell-style="{ background: '#EDEFFE', color: '#363636', textAlign: 'center' }"
                            :cell-style="cellStyle"
                            style="width: 100%">
                            <el-table-column type="index" label="序号" width="70" align="center" :index="formatIndex"></el-table-column>
                            <el-table-column prop="name" label="官网名称" min-width="200" align="left"></el-table-column>
                            <el-table-column prop="level" label="单位级别" width="150" align="center"></el-table-column>
                            <el-table-column prop="phone" label="咨询电话" width="150" align="center"></el-table-column>
                            <el-table-column label="操作" width="240" align="center">
                                <template #default="scope">
                                    <el-button type="text" class="link-btn" @click="handleGo(scope.row)">前往网址</el-button>
                                    <el-button type="text" class="link-btn" @click="handleCopy(scope.row)">复制网址</el-button>
                                    <el-button type="text" class="link-btn delete-btn" @click="handleDelete(scope.row)">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="footer">
                            <el-pagination
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="pagination.currentPage"
                                :page-sizes="[10, 20, 30, 50]"
                                :page-size="pagination.pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="pagination.total">
                            </el-pagination>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加/编辑弹框 -->
        <el-dialog
            :title="dialogTitle"
            :visible.sync="dialogVisible"
            width="800px"
            :close-on-click-modal="false"
            :destroy-on-close="true"
            class="add-dialog">
            <div class="content-areas" style="top: 5px;">
                <div class="contents-left">
                    <span class="table-name">官网名称</span>
                </div>
                <div class="contents-right" style="border: none;">
                    <div class="rightss rightss1">
                        <el-input v-model="formData.name" placeholder="请输入内容" style="width: 100%;"></el-input>
                    </div>
                    <div class="contents-left">
                        <span class="table-name">官网地址</span>
                    </div>
                    <div class="rightss rightss3">
                        <el-input v-model="formData.url" placeholder="请输入内容" style="width: 100%;"></el-input>
                    </div>
                </div>
            </div>
            <div class="content-areas" style="top: 1px;">
                <div class="contents-left">
                    <span class="table-name">单位级别</span>
                </div>
                <div class="contents-right" style="border: none;">
                    <div class="rightss rightss1">
                        <el-select v-model="formData.level" placeholder="请选择单位级别" style="width: 100%;">
                            <el-option 
                                v-for="item in levelSelectOptions" 
                                :key="item.value" 
                                :label="item.label" 
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </div>
                    <div class="contents-left">
                        <span class="table-name">咨询电话（选填）</span>
                    </div>
                    <div class="rightss rightss3">
                        <el-input v-model="formData.phone" placeholder="请输入内容" style="width: 100%;"></el-input>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer-custom">
                    <el-button type="primary" size="small" class="save-btn" @click="handleSubmit">保存</el-button>
                    <el-button size="small" @click="dialogVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { getGovList, addGov, deleteGov } from '@/api/Innovation/government'

export default {
    data() {
        return {
            levelFilter: '',
            levelOptions: [
                { value: 'all', label: '全部' },
                { value: '省级', label: '省级' },
                { value: '市级', label: '市级' },
                { value: '区县级', label: '区县级' }
            ],
            // 单位级别下拉选项（用于表单，传数字给后台）
            levelSelectOptions: [
                { value: 1, label: '省级' },
                { value: 2, label: '市级' },
                { value: 3, label: '区县级' }
            ],
            tableData: [],
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },
            dialogVisible: false,
            dialogTitle: '网站添加',
            formData: {
                id: '',
                name: '',
                level: null, // 数字类型：1省, 2市, 3区
                phone: '',
                url: ''
            },
            formRules: {
                name: [
                    { required: true, message: '请输入官网名称', trigger: 'blur' }
                ],
                level: [
                    { required: true, message: '请选择单位级别', trigger: 'change' }
                ],
                phone: [
                    // 咨询电话为选填，不需要必填验证
                ],
                url: [
                    { required: true, message: '请输入官网地址', trigger: 'blur' }
                ]
            }
        }
    },
    computed: {
        // 过滤掉 'all' 选项，用于表单选择
        filteredLevelOptions() {
            return this.levelOptions.filter(item => item.value !== 'all')
        }
    },
    mounted() {
        this.getList()
    },
    methods: {
        // 获取列表数据
        getList() {
            // 将筛选的级别转换为数字（省级=1, 市级=2, 区县级=3）
            let levelParam = ''
            if (this.levelFilter && this.levelFilter !== 'all') {
                const levelMap = {
                    '省级': 1,
                    '市级': 2,
                    '区县级': 3
                }
                levelParam = levelMap[this.levelFilter] || ''
            }
            
            const params = {
                page: this.pagination.currentPage,
                limit: this.pagination.pageSize,
                level: levelParam
            }
            getGovList(params).then((res) => {
                if (res && res.code === 1 && res.data) {
                    this.pagination.total = res.data.total || 0
                    this.tableData = res.data.data || []
                } else {
                    this.$message.error(res?.msg || '获取数据失败')
                    this.tableData = []
                    this.pagination.total = 0
                }
            }).catch((error) => {
                console.error('获取列表数据失败:', error)
                this.$message.error('获取数据失败')
                this.tableData = []
                this.pagination.total = 0
            })
        },
        // 筛选变化
        handleFilterChange() {
            this.pagination.currentPage = 1
            this.getList()
        },
        // 添加
        handleAdd() {
            this.dialogTitle = '网站添加'
            this.formData = {
                id: '',
                name: '',
                level: null, // 初始化为 null，确保下拉框显示 placeholder
                phone: '',
                url: ''
            }
            this.dialogVisible = true
        },
        // 提交表单
        handleSubmit() {
            // 表单验证
            if (!this.formData.name || !this.formData.name.trim()) {
                this.$message.warning('请输入官网名称')
                return
            }
            if (!this.formData.url || !this.formData.url.trim()) {
                this.$message.warning('请输入官网地址')
                return
            }
            if (!this.formData.level) {
                this.$message.warning('请选择单位级别')
                return
            }
            
            const params = {
                name: this.formData.name.trim(),
                url: this.formData.url.trim(),
                level: this.formData.level, // 数字：1省, 2市, 3区
                phone: this.formData.phone ? this.formData.phone.trim() : '' // 选填
            }
            
            // 添加
            addGov(params).then((res) => {
                if (res && res.code === 1) {
                    this.$message.success('添加成功')
                    this.dialogVisible = false
                    this.getList()
                } else {
                    this.$message.error(res?.msg || '添加失败')
                }
            }).catch((error) => {
                console.error('添加失败:', error)
                this.$message.error('添加失败')
            })
        },
        // 前往网址
        handleGo(row) {
            const url = row.url || row.website_url || ''
            if (url) {
                // 确保URL格式正确，如果没有协议前缀则添加 http://
                let targetUrl = url.trim()
                if (targetUrl && !targetUrl.match(/^https?:\/\//i)) {
                    targetUrl = 'http://' + targetUrl
                }
                // 在新标签页中打开
                window.open(targetUrl, '_blank')
            } else {
                this.$message.warning('该官网地址不存在')
            }
        },
        // 复制网址
        handleCopy(row) {
            // 获取列表中的链接地址字段
            const url = row.url || row.website_url || ''
            if (url && url.trim()) {
                const urlToCopy = url.trim()
                // 使用 Clipboard API 复制
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(urlToCopy).then(() => {
                        this.$message.success('复制成功')
                    }).catch(() => {
                        this.fallbackCopyTextToClipboard(urlToCopy)
                    })
                } else {
                    this.fallbackCopyTextToClipboard(urlToCopy)
                }
            } else {
                this.$message.warning('该官网地址不存在')
            }
        },
        // 备用复制方法
        fallbackCopyTextToClipboard(text) {
            const textArea = document.createElement('textarea')
            textArea.value = text
            textArea.style.position = 'fixed'
            textArea.style.left = '-999999px'
            document.body.appendChild(textArea)
            textArea.focus()
            textArea.select()
            try {
                document.execCommand('copy')
                this.$message.success('复制成功')
            } catch (err) {
                this.$message.error('复制失败')
            }
            document.body.removeChild(textArea)
        },
        // 删除
        handleDelete(row) {
            this.$confirm('确定要删除这条记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 调用删除接口
                const params = {
                    id: row.id
                }
                deleteGov(params).then((res) => {
                    if (res && res.code === 1) {
                        this.$message.success('删除成功')
                        // 删除成功后刷新列表
                        this.getList()
                    } else {
                        this.$message.error(res?.msg || '删除失败')
                    }
                }).catch((error) => {
                    console.error('删除失败:', error)
                    this.$message.error('删除失败')
                })
            }).catch(() => {
                // 用户取消删除，不做任何操作
            })
        },
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.pagination.currentPage = 1
            this.getList()
        },
        handleCurrentChange(val) {
            this.pagination.currentPage = val
            this.getList()
        },
        formatIndex(index) {
            return (this.pagination.currentPage - 1) * this.pagination.pageSize + index + 1
        },
        cellStyle({ column }) {
            const leftAlignedProps = ['name']
            return {
                textAlign: leftAlignedProps.includes(column.property) ? 'left' : 'center',
                color: '#363636'
            }
        }
    }
}
</script>

<style scoped>
.coentent {
    width: 100%;
    height: 100%;
    background: white;
}

.contents-area {
    width: 100%;
    margin-top: 20px;
}

.areas {
    width: 97%;
    margin: 0 auto;
}

.headers {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    flex-wrap: wrap;
    gap: 16px;
    padding-top: 18px;
}

.headers-left {
    display: flex;
    align-items: center;
    gap: 20px;
}

.headers-name {
    font-size: 15px;
    color: #17192C;
}

.headers-right {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 16px;
}

.filter-item {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: #6A6E8C;
}

.filter-label {
    min-width: 70px;
}

.filter-select {
    width: 140px;
}

.add-btn {
    background: #5165F7;
    border-color: #5165F7;
}

.content-table {
    background: #fff;
    border-radius: 8px;
}

.footer {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.link-btn {
    color: #5165F7;
    padding: 0;
    margin: 0 8px;
}

.delete-btn {
    color: #F56C6C;
}

.dialog-footer-custom {
    display: flex;
    justify-content:center;
    gap: 16px;
    padding: 0;
}
.content-areas {
    display: flex;
    height: 50px;
    flex-wrap: wrap;
}
.save-btn {
    background: #5165F7;
    border-color: #5165F7;
}

.add-form ::v-deep .el-form-item {
    margin-bottom: 20px;
}

.add-dialog ::v-deep .el-dialog__header {
    text-align: center;
    padding: 20px 20px 20px;
    background: #F7F7FA;
}

.add-dialog ::v-deep .el-dialog__title {
    font-size: 16px;
    font-weight: 600;
    color: #17192C;
}

.rightss {
    height: 100%;
    border: 1px solid #DCE0FD;
    width: 26%;
    border-top: none;
    padding-left: 20px;
}

.content-areas2 {
    position: relative;
    top: 1px;

}

.contents-right {
    flex: 1;
    border: 1px solid #DCE0FD;
    line-height: 50px;
    font-size: 14px;
    color: #363636;
    display: flex
}

.contents-left {
    width: 20%;
    border: 1px solid #DCE0FD;
    background: #EDEFFE;
    ;
    line-height: 50px;
    font-size: 14px;
    color: #363636;
    padding-left: 20px;
}
.add-dialog ::v-deep .el-dialog__body {
    padding: 20px;
}

.add-dialog ::v-deep .el-dialog__footer {
    padding: 10px 20px 20px;
}
</style>

