<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 clearable  v-model="publish_unit" @change="handleFilterChange" style="border: 1px solid #ededed;" size="small" class="filter-select">
                                    <el-option v-for="item in slelectDate" :key="item.name" :label="item.name" :value="item.name"></el-option>
                                </el-select>
                            </div>
                            <div class="filter-item">
                                <span class="filter-label">时间筛选</span>
                                <el-date-picker
                                    v-model="filters.dateRange"
                                    type="daterange"
                                    range-separator="至"
                                    start-placeholder="开始时间"
                                    end-placeholder="结束时间"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    size="small"
                                    class="filter-date-picker"
                                    style="width: 240px; border: 1px solid #ededed !important;"
                                    @change="handleDateRangeChange">
                                </el-date-picker>
                            </div>
                            <el-input
                                style="border: 1px solid #ededed;"
                                placeholder="搜索关键字"
                                v-model="filters.keyword"
                                class="search-input"
                                size="small"
                                clearable>
                                <el-button slot="append" icon="el-icon-search" @click="handleSearch">搜索</el-button>
                            </el-input>
                            <el-button type="primary" size="small" class="follow-btn" @click="openFollowSetting">关注设置</el-button>
                        </div>
                    </div>

                    <div class="content-table">
                        <el-table
                            :data="pagedData"
                            border
                            :header-cell-style="{ background: '#EDEFFE', color: '#363636', textAlign: 'center' }"
                            :cell-style="cellStyle"
                            :row-class-name="rowClassName"
                            style="width: 100%">
                            <el-table-column type="index" label="序号" width="70" align="center" :index="formatIndex"></el-table-column>
                            <el-table-column prop="title" label="内容" min-width="400">
                                <template #default="{ row }">
                                    <div class="content-title">{{ row.title }}</div>
                                    <div class="content-summary">{{ row.summary }}</div>
                                    <div class="content-tags">
                                        <span class="tag-label">涉及项：</span>
                                        <span class="tag-item" v-for="tag in row.tags" :key="tag">{{ tag }}</span>
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column prop="publisher" label="发布单位" min-width="180"></el-table-column>
                            <el-table-column prop="publishDate" label="发布日期" min-width="140"></el-table-column>
                            <el-table-column label="附件数量" width="110" align="center">
                                <template #default="{ row: item }">
                                    {{ item.attachments?.length || 0 }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="120" align="center">
                                <template #default="scope">
                                    <el-button type="text" class="link-btn" @click="openDetail(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
            :visible.sync="detailDialogVisible"
            width="840px"
            class="follow-detail-dialog"
            :close-on-click-modal="false"
            :destroy-on-close="true">
            <template #title>
                <div class="detail-title">{{ detailData.title }}</div>
            </template>
            <div class="detail-body">
                <div class="detail-meta">
                    <span>发布单位：{{ detailData.publisher }}</span>
                    <span>发布时间：{{ detailData.publishDate }}</span>
                </div>
                <div class="detail-content">
                    <p v-for="(paragraph, index) in detailData.content" :key="index">{{ paragraph }}</p>
                </div>
                <div class="detail-attachments" v-if="detailData.attachments?.length">
                    <div class="attachments-title">附件下载</div>
                    <el-table
                        :data="detailData.attachments"
                        border
                        size="small"
                        :header-cell-style="{ background: '#F0F2FF', color: '#363636', textAlign: 'left' }"
                        :cell-style="{ textAlign: 'left', color: '#363636' }">
                        <el-table-column prop="name" label="附件名称"></el-table-column>
                        <el-table-column label="操作" width="120" align="center">
                            <template #default>
                                <el-button type="text" class="link-btn">下载</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
            <template #footer>
                <div class="detail-footer">
                    <el-button size="small" @click="detailDialogVisible = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog
            :visible.sync="followDialogVisible"
            width="600px"
            class="follow-setting-dialog"
            :close-on-click-modal="false"
            :destroy-on-close="true">
            <template #title>
                <div class="follow-setting-title">通知公告关注关键词设置</div>
            </template>
            <div class="follow-setting-section">
                <div class="follow-setting-label">关键词设置</div>
                <el-input
                    type="textarea"
                    v-model="followKeywords"
                    placeholder="请输入关注关键词，用“,”分组..."
                    class="follow-setting-input">
                </el-input>
            </div>
            <div class="follow-setting-note">
                <ol>
                    <li>请输入关注关键词，用“,”分组，关键词数量不超过30个；</li>
                    <li>设置关键词后系统将自动筛选最新的相关通知公告，默认查找近一年的通知公告。</li>
                </ol>
            </div>
            <template #footer>
                <div class="detail-footer">
                    <el-button type="primary" size="small" class="submit-btn" @click="submitFollowKeywords">保存提交</el-button>
                    <el-button size="small" @click="followDialogVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {myList,govAddr,save,getLastKeyWords} from '@/api/Innovation/government'
export default {
    data() {
        return {
            publish_unit:"",
            filters: {
                category: 'all',
                publisher: '',
                dateRange: [],
                keyword: ''
            },
            categoryOptions: [
                { value: 'all', label: '全部' },
                { value: 'notification', label: '通知公告' },
                { value: 'policy', label: '政策发布' }
            ],
            publisherOptions: [
                { value: 'all', label: '全部' },
                { value: '贵州省科学技术厅', label: '贵州省科学技术厅' },
                { value: '贵州省工业和信息化厅', label: '贵州省工业和信息化厅' }
            ],
            tableData: [],
            pagination: {
                currentPage: 1,
                pageSize: 10,
                total: 0
            },
            start_time:"",
            end_time:"",
            keyword:"",
            detailDialogVisible: false,
            detailData: {
                title: '',
                publisher: '',
                publishDate: '',
                content: [],
                attachments: []
            },
            slelectDate:[],
            page:1,
            limit:10,
            followDialogVisible: false,
            followKeywords: ''
        }
    },
    computed: {
        pagedData() {
            return this.tableData
        }
    },
    mounted(){
       
        this.getmyList()
        this.getgovAddr()
    },
    methods: {
        //关键词数据回显
        getgetLastKeyWords(){
            getLastKeyWords().then((res)=>{
                this.followKeywords=res.data.keywords
            })
        },
        //发布单位，
        getgovAddr(){
            govAddr().then((res)=>{
                this.slelectDate=res.data.data
            })
        },
        //列表数据
        getmyList(){
            // 处理筛选条件
          
            let keyword = this.filters.keyword || ''
            
            // 处理类别筛选（parent_id）
            let parent_id = ''
            if (this.filters.category === 'notification') {
                parent_id = '1' // 通知公告
            } else if (this.filters.category === 'policy') {
                parent_id = '2' // 政策发布
            }
            
            // 处理时间筛选（日期范围）
            let start_time = ''
            let end_time = ''
            if (this.filters.dateRange && this.filters.dateRange.length === 2) {
                start_time = this.filters.dateRange[0]
                end_time = this.filters.dateRange[1]
            }
            
            let parm = {
                publish_unit: this.publish_unit,
                start_time: start_time,
                end_time: end_time,
                keyword: keyword,
                page: this.pagination.currentPage,
                limit: this.pagination.pageSize
            }
            
            // 如果选择了类别，添加 parent_id 参数
            if (parent_id) {
                parm.parent_id = parent_id
            }
            
            myList(parm).then((res) => {
                if (res && res.code === 1 && res.data) {
                    // 更新总数
                    this.pagination.total = res.data.total || 0
                    
                    // 处理返回的数据
                    const dataList = res.data.data || []
                    this.tableData = dataList.map(item => {
                        // 解析附件
                        let attachments = []
                        if (item.file_address) {
                            try {
                                // 尝试解析 file_address JSON 字符串
                                const fileAddress = JSON.parse(item.file_address)
                                if (Array.isArray(fileAddress)) {
                                    attachments = fileAddress.map(file => ({
                                        name: file.name || file.destination || '附件',
                                        url: file.url || file.destination || '#'
                                    }))
                                }
                            } catch (e) {
                                // 如果解析失败，使用 file_num 作为附件数量
                                if (item.file_num > 0) {
                                    attachments = Array(item.file_num).fill(null).map((_, index) => ({
                                        name: `附件${index + 1}`,
                                        url: '#'
                                    }))
                                }
                            }
                        } else if (item.file_num > 0) {
                            attachments = Array(item.file_num).fill(null).map((_, index) => ({
                                name: `附件${index + 1}`,
                                url: '#'
                            }))
                        }
                        
                        // 处理标签（从 keyword 字段）
                        let tags = []
                        if (item.keyword) {
                            tags = item.keyword.split(/[,，]/).filter(tag => tag.trim())
                        }
                        
                        // 格式化日期
                        let publishDate = item.article_time || item.create_time || ''
                        if (publishDate) {
                            publishDate = this.formatDisplayDate(publishDate)
                        }
                        
                        return {
                            id: item.id,
                            title: item.title || '',
                            summary: item.abstract || '',
                            tags: tags,
                            publisher: item.publish_unit || '',
                            publishDate: publishDate,
                            attachments: attachments,
                            category: item.parent_id === '1' ? 'notification' : (item.parent_id === '2' ? 'policy' : 'notification'),
                            content: item.abstract ? [item.abstract] : [],
                            url: item.url || '',
                            content_url: item.content_url || '',
                            file_address: item.file_address || '',
                            keyword: item.keyword || ''
                        }
                    })
                } 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
            })
        },
        // 格式化显示日期
        formatDisplayDate(dateStr) {
            if (!dateStr) return ''
            const date = new Date(dateStr)
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${year}年${month}月${day}日`
        },
        handleSearch() {
            this.pagination.currentPage = 1
            this.getmyList()
        },
        handleSizeChange(val) {
            this.pagination.pageSize = val
            this.pagination.currentPage = 1
            this.getmyList()
        },
        handleCurrentChange(val) {
            this.pagination.currentPage = val
            this.getmyList()
        },
        formatIndex(index) {
            return (this.pagination.currentPage - 1) * this.pagination.pageSize + index + 1
        },
        rowClassName() {
            return 'follow-row'
        },
        cellStyle({ column }) {
            const leftAlignedProps = ['title', 'publisher', 'publishDate']
            return {
                textAlign: leftAlignedProps.includes(column.property) ? 'left' : 'center',
                color: '#363636'
            }
        },
        openDetail(row) {
            this.detailData = {
                title: row.title,
                publisher: row.publisher,
                publishDate: row.publishDate,
                content: row.content || [],
                attachments: row.attachments || []
            }
            this.detailDialogVisible = true
        },
        openFollowSetting() {
            this.followKeywords = this.filters.keyword || ''
            this.followDialogVisible = true
            this.getgetLastKeyWords()
        },
        submitFollowKeywords() {
            // 调用保存接口
            save({ keyword: this.followKeywords }).then((res) => {
                if (res && res.code === 1) {
                    this.$message.success('关注关键词已保存')
                    this.followDialogVisible = false
                    // 保存成功后，可以重新获取列表数据
                    this.getmyList()
                } else {
                    this.$message.error(res?.msg || '保存失败')
                }
            }).catch((error) => {
                console.error('保存关注关键词失败:', error)
                this.$message.error('保存失败')
            })
        },
        handleFilterChange() {
            this.pagination.currentPage = 1
            this.getmyList()
        },
        handleDateRangeChange() {
            // 当日期范围选择完成后，自动触发搜索
            this.pagination.currentPage = 1
            this.getmyList()
        }
    }
}
</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;
}

.filter-date-picker {
    width: 240px;
}

.filter-date-picker ::v-deep .el-input__inner {
    border: 1px solid #ededed !important;
}

.filter-date-picker ::v-deep .el-input__inner:focus {
    border-color: #DCDFE6;
}

.filter-date-picker ::v-deep .el-range-input {
    border: none;
}

.search-input {
    width: 220px;
}

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

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

.content-title {
    font-size: 14px;
    font-weight: 600;
    color: #17192C;
}

.content-summary {
    font-size: 13px;
    color: #6A6E8C;
    margin-top: 6px;
    line-height: 1.5;
}

.content-tags {
    margin-top: 8px;
    font-size: 12px;
    color: #6A6E8C;
}

.tag-label {
    margin-right: 6px;
}

.tag-item {
    display: inline-block;
    margin-right: 8px;
    color: #5165F7;
}

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

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

::v-deep .follow-row td {
    color: #363636;
}

::v-deep .el-table__body tr:hover > td {
    background-color: #F7F8FF !important;
}

.follow-detail-dialog ::v-deep .el-dialog {
    border-radius: 12px;
}

.follow-detail-dialog ::v-deep .el-dialog__header {
    padding: 20px 28px 12px;
    border-bottom: none;
}

.detail-title {
    font-size: 18px;
    font-weight: 600;
    color: #17192C;
    text-align: center;
}

.detail-body {
    padding: 0 28px 20px;
}

.detail-meta {
    display: flex;
    justify-content: center;
    gap: 24px;
    font-size: 12px;
    color: #6A6E8C;
    margin-bottom: 20px;
}

.detail-content {
    font-size: 14px;
    color: #363636;
    line-height: 1.7;
    margin-bottom: 24px;
}

.detail-content p {
    margin: 0 0 16px;
}

.follow-setting-dialog ::v-deep .el-dialog {
    border-radius: 12px;
}

.follow-setting-dialog ::v-deep .el-dialog__header {
    padding: 20px 28px 12px;
    border-bottom: none;
}

.follow-setting-dialog ::v-deep .el-dialog__body {
    padding: 0 28px 24px;
}

.follow-setting-dialog ::v-deep .el-dialog__footer {
    padding: 18px 28px 28px;
    border-top: none;
}

.follow-setting-title {
    font-size: 18px;
    font-weight: 600;
    color: #17192C;
    text-align: center;
}

.follow-setting-section {
    margin-top: 16px;
}

.follow-setting-label {
    font-size: 14px;
    font-weight: 600;
    color: #363636;
    margin-bottom: 12px;
}

.follow-setting-input ::v-deep textarea {
    background: #F8F9FF;
    min-height: 140px;
}

.follow-setting-note {
    margin-top: 16px;
    background: #F8F9FF;
    border-radius: 8px;
    padding: 12px 16px;
    font-size: 12px;
    color: #6A6E8C;
    line-height: 1.6;
}

.detail-footer {
    display: flex;
    justify-content: center;
    gap: 16px;
}

.submit-btn {
    background: #5165F7;
    border-color: #5165F7;
}
</style>