<template>
    <basic-container>
        <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" ref="crud" @row-del="rowDel"
            v-model="form" :permission="permissionList" @row-update="rowUpdate" @row-save="rowSave"
            :before-open="beforeOpen" @search-change="searchChange" @search-reset="searchReset"
            @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
            @refresh-change="refreshChange" @on-load="onLoad">
            <template slot="menuLeft">
                <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.announcement_delete"
                    @click="handleDelete">删 除
                </el-button>
            </template>
            <template slot-scope="{row}" slot="dealer">
                <el-tag>{{ row.dealerName }}</el-tag>
            </template>
            <template slot-scope="{row}" slot="brand">
                <el-tag>{{ row.brandName }}</el-tag>
            </template>
            <template slot-scope="{row}" slot="detail">
                <el-button type="text" @click="viewDetail(row)">查看详情</el-button>
            </template>
        </avue-crud>

        <!-- 详情查看对话框 -->
        <el-dialog title="公告详情" :visible.sync="detailVisible" width="60%" append-to-body>
            <div class="detail-content">
                <h3>{{ currentDetail.title }}</h3>
                <div class="detail-info">
                    <p><strong>发布时间：</strong>{{ currentDetail.publishTime }}</p>
                    <p><strong>经销商：</strong>{{ currentDetail.dealerName }}</p>
                    <p><strong>品牌：</strong>{{ currentDetail.brandName }}</p>
                </div>
                <div class="detail-body" v-html="currentDetail.content"></div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="detailVisible = false">关 闭</el-button>
            </span>
        </el-dialog>
    </basic-container>
</template>

<script>
import { getList, remove, update, add, getAnnouncement, getDealerList, getBrandList, getCategoryList } from "@/api/announcement";
import { mapGetters } from "vuex";

export default {
    name: 'AnnouncementIndex',
    data() {
        return {
            form: {},
            query: {},
            loading: true,
            detailVisible: false,
            currentDetail: {},
            page: {
                pageSize: 10,
                currentPage: 1,
                total: 0
            },
            selectionList: [],
            dealerOptions: [],
            brandOptions: [],
            categoryOptions: [], // 添加分类选项数组
            option: {
                height: 'auto',
                calcHeight: 30,
                dialogWidth: 950,
                tip: false,
                searchShow: true,
                searchMenuSpan: 6,
                border: true,
                index: true,
                viewBtn: true,
                selection: true,
                excelBtn: false,        // 隐藏下载按钮
                columnBtn: false,       // 隐藏列设置按钮
                dialogClickModal: false,
                column: [
                    {
                        label: "公告标题",
                        prop: "title",
                        span: 12,
                        search: true,
                        overHidden: true,
                        rules: [{
                            required: true,
                            message: "请输入公告标题",
                            trigger: "blur"
                        }]
                    },
                    {
                        label: "客户编号",
                        prop: "customerCode",
                        span: 12,
                        search: true,
                        overHidden: true
                    },
                    {
                        label: "发布时间",
                        prop: "publishTime",
                        type: "daterange",
                        format: "yyyy-MM-dd",
                        valueFormat: "yyyy-MM-dd",
                        rangeSeparator: "至",
                        searchRange: true,
                        startPlaceholder: "开始时间",
                        endPlaceholder: "结束时间",
                        overHidden: true,
                        search: true,
                        hide: true,  // 在表格中隐藏，只用于搜索
                        addDisplay: false,  // 新增时不显示
                        editDisplay: false, // 编辑时不显示
                        viewDisplay: false  // 查看时不显示
                    },
                    {
                        label: "经销商",
                        prop: "dealerId",
                        type: "select",
                        dicData: [],
                        props: {
                            label: "dealerName",
                            value: "id"
                        },
                        slot: true,
                        overHidden: true,
                        search: true,
                        span: 12,
                        rules: [{
                            required: true,
                            message: "请选择经销商",
                            trigger: "change"
                        }]
                    },
                    {
                        label: "品牌",
                        prop: "brandId",
                        type: "select",
                        dicData: [],
                        props: {
                            label: "brandName",
                            value: "id"
                        },
                        slot: true,
                        overHidden: true,
                        search: true,
                        span: 12,
                        rules: [{
                            required: true,
                            message: "请选择品牌",
                            trigger: "change"
                        }]
                    },
                    {
                        label: "分类",
                        prop: "categoryId",
                        type: "select",
                        dicData: [], // 初始为空，通过loadCategoryOptions方法动态加载
                        props: {
                            label: "categoryName", // 根据后端返回的字段名调整
                            value: "id"
                        },
                        search: true,
                        span: 12,
                        rules: [{
                            required: true,
                            message: "请选择分类",
                            trigger: "change"
                        }]
                    },
                    {
                        label: "角色",
                        prop: "roleType",
                        type: "select",
                        dicData: [
                            { label: "工厂", value: "factory" },
                            { label: "经销商", value: "dealer" },
                            { label: "零售商", value: "retailer" }
                        ],
                        search: true,
                        span: 12,
                        rules: [{
                            required: true,
                            message: "请选择角色",
                            trigger: "change"
                        }]
                    },
                    {
                        label: "公告内容",
                        prop: "content",
                        component: 'AvueUeditor',
                        options: {
                            action: '/api/blade-resource/oss/endpoint/put-file',
                            props: {
                                res: "data",
                                url: "link",
                            }
                        },
                        showColumn: false,
                        hide: true,
                        minRows: 6,
                        span: 24,
                        rules: [{
                            required: true,
                            message: "请输入公告内容",
                            trigger: "blur"
                        }]
                    },
                ]
            },
            data: []
        };
    },
    computed: {
        ...mapGetters(["permission"]),
        permissionList() {
            return {
                addBtn: this.vaildData(this.permission.announcement_add, false),
                viewBtn: this.vaildData(this.permission.announcement_view, false),
                delBtn: this.vaildData(this.permission.announcement_delete, false),
                editBtn: this.vaildData(this.permission.announcement_edit, false)
            };
        },
        ids() {
            let ids = [];
            this.selectionList.forEach(ele => {
                ids.push(ele.id);
            });
            return ids.join(",");
        }
    },
    created() {
        this.loadDealerOptions();
        this.loadBrandOptions();
        this.loadCategoryOptions(); // 添加分类加载
    },
    methods: {
        // 加载分类选项
        async loadCategoryOptions() {
            try {
                const res = await getCategoryList();
                this.categoryOptions = res.data.data || [];
                const categoryColumn = this.option.column.find(col => col.prop === 'categoryId');
                if (categoryColumn) {
                    categoryColumn.dicData = this.categoryOptions;
                }
            } catch (error) {
                // 如果接口不存在，使用模拟数据
                this.categoryOptions = [
                    { id: 1, categoryName: '系统公告', value: 1, label: '系统公告' },
                    { id: 2, categoryName: '产品公告', value: 2, label: '产品公告' },
                    { id: 3, categoryName: '活动公告', value: 3, label: '活动公告' },
                    { id: 4, categoryName: '维护公告', value: 4, label: '维护公告' }
                ];
                const categoryColumn = this.option.column.find(col => col.prop === 'categoryId');
                if (categoryColumn) {
                    categoryColumn.dicData = this.categoryOptions;
                }
            }
        },
        // 查看详情
        viewDetail(row) {
            this.currentDetail = row;
            this.detailVisible = true;
        },
        // 加载经销商选项
        async loadDealerOptions() {
            try {
                const res = await getDealerList();
                this.dealerOptions = res.data.data || [];
                const dealerColumn = this.option.column.find(col => col.prop === 'dealerId');
                if (dealerColumn) {
                    dealerColumn.dicData = this.dealerOptions;
                }
            } catch (error) {
                // 如果接口不存在，使用模拟数据
                this.dealerOptions = [
                    { id: 1, dealerName: '经销商A' },
                    { id: 2, dealerName: '经销商B' },
                    { id: 3, dealerName: '经销商C' }
                ];
                const dealerColumn = this.option.column.find(col => col.prop === 'dealerId');
                if (dealerColumn) {
                    dealerColumn.dicData = this.dealerOptions;
                }
            }
        },
        // 加载品牌选项
        async loadBrandOptions() {
            try {
                const res = await getBrandList();
                this.brandOptions = res.data.data || [];
                const brandColumn = this.option.column.find(col => col.prop === 'brandId');
                if (brandColumn) {
                    brandColumn.dicData = this.brandOptions;
                }
            } catch (error) {
                // 如果接口不存在，使用模拟数据
                this.brandOptions = [
                    { id: 1, brandName: '品牌A' },
                    { id: 2, brandName: '品牌B' },
                    { id: 3, brandName: '品牌C' }
                ];
                const brandColumn = this.option.column.find(col => col.prop === 'brandId');
                if (brandColumn) {
                    brandColumn.dicData = this.brandOptions;
                }
            }
        },
        async rowSave(row, done, loading) {
            try {
                await add(row);
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
                done();
            } catch (error) {
                console.log(error);
                loading();
            }
        },
        async rowUpdate(row, index, done, loading) {
            try {
                await update(row);
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
                done();
            } catch (error) {
                console.log(error);
                loading();
            }
        },
        async rowDel(row) {
            try {
                await this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                });
                await remove(row.id);
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
            } catch (error) {
                // 用户取消删除或删除失败
                console.log(error);
            }
        },
        searchReset() {
            this.query = {};
            this.onLoad(this.page);
        },
        searchChange(params, done) {
            this.query = params;
            this.page.currentPage = 1;
            this.onLoad(this.page, params);
            done();
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud.toggleSelection();
        },
        async handleDelete() {
            if (this.selectionList.length === 0) {
                this.$message.warning("请选择至少一条数据");
                return;
            }
            try {
                await this.$confirm("确定将选择数据删除?", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                });
                await remove(this.ids);
                this.onLoad(this.page);
                this.$message({
                    type: "success",
                    message: "操作成功!"
                });
                this.$refs.crud.toggleSelection();
            } catch (error) {
                // 用户取消删除或删除失败
                console.log(error);
            }
        },
        async beforeOpen(done, type) {
            if (["edit", "view"].includes(type)) {
                try {
                    const res = await getAnnouncement(this.form.id);
                    this.form = res.data.data;
                } catch (error) {
                    console.log(error);
                }
            }
            done();
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
        },
        refreshChange() {
            this.onLoad(this.page, this.query);
        },
        async onLoad(page, params = {}) {
            const { publishTime } = this.query;
            let values = {
                ...params,
            };
            if (publishTime) {
                values = {
                    ...params,
                    publishTimeStart: publishTime[0],
                    publishTimeEnd: publishTime[1],
                    ...this.query
                };
                values.publishTime = null;
            }
            this.loading = true;
            try {
                const res = await getList(page.currentPage, page.pageSize, values);
                const data = res.data.data;
                this.page.total = data.total;
                this.data = data.records;
                this.loading = false;
                this.selectionClear();
            } catch (error) {
                console.log(error);
                this.loading = false;
            }
        }
    }
};
</script>

<style scoped>
.detail-content {
    padding: 20px;
}

.detail-info {
    margin: 20px 0;
    padding: 15px;
    background-color: #f5f5f5;
    border-radius: 4px;
}

.detail-info p {
    margin: 8px 0;
}

.detail-body {
    margin-top: 20px;
    padding: 15px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    min-height: 200px;
}
</style>
