<script lang="ts">
export default {
    name: "announce",
};
</script>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from "vue";
import { ElTable, ElForm, ElMessage, ElMessageBox } from "element-plus";
import { Plus, Delete, Search, RefreshLeft } from "@element-plus/icons-vue";
import Editor from "@/components/WangEditor/index.vue";
import {
    announceManage,
    addAnnounce,
    updateAnnounce,
    delAnnounce,
    stickTopAnnounce,
    announceDown,
    announcePopupOn,
    announcePopupOff,
} from "@/api/cms";
import {
    AnnounceQueryParam,
    AnnounceItem,
    AnnounceFormData,
    AnnounceLangContent,
} from "@/types/api/cms";

const LANGS = [
    { key: "zh_CN", label: "简体" },
    { key: "zh_HK", label: "繁体" },
    { key: "en_US", label: "English" },
    { key: "ko_KR", label: "韩语" },
    { key: "ja_JP", label: "日语" },
    { key: "hi_IN", label: "印地语" },
    { key: "id_ID", label: "印尼语" },
] as const;

type LangKey = "zh_CN" | "zh_HK" | "en_US" | "ko_KR" | "ja_JP" | "hi_IN" | "id_ID";

const emit = defineEmits(["AnnounceClick"]);
const dataTableRef = ref(ElTable);
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

function emptyLangContent(): AnnounceLangContent {
    return { zh_CN: "", zh_HK: "", en_US: "", ko_KR: "", ja_JP: "", hi_IN: "", id_ID: "" };
}

function parseLangJson(raw: string | null | undefined): AnnounceLangContent {
    if (!raw) return emptyLangContent();
    try {
        const parsed = JSON.parse(raw);
        return {
            zh_CN: parsed.zh_CN ?? "",
            zh_HK: parsed.zh_HK ?? "",
            en_US: parsed.en_US ?? "",
            ko_KR: parsed.ko_KR ?? "",
            ja_JP: parsed.ja_JP ?? "",
            hi_IN: parsed.hi_IN ?? "",
            id_ID: parsed.id_ID ?? "",
        };
    } catch {
        // 兼容旧数据（纯文本）— 放到中文
        return { zh_CN: raw, zh_HK: "", en_US: "", ko_KR: "", ja_JP: "", hi_IN: "", id_ID: "" };
    }
}

const state = reactive({
    loading: true,
    ids: [],
    single: true,
    multiple: true,
    queryParams: {
        pageNo: 1,
        pageSize: 15,
    } as AnnounceQueryParam,
    list: [] as AnnounceItem[],
    total: 0,
    isCreate: false,
    dialog: {
        title: "",
        visible: false,
    },
    activeLangTab: "zh_CN",
    formData: {
        id: 0,
        titles: emptyLangContent(),
        contents: emptyLangContent(),
        imgUrl: "",
        isTop: "1",
        isShow: true,
        announcementClassification: 0,
        sort: 0,
        createTime: "",
        isPopup: false,
        publishTime: "",
    } as AnnounceFormData,
    rules: {
        announcementClassification: [
            { required: true, message: "请选择公告分类", trigger: "blur" },
        ],
        isShow: [
            { required: true, message: "请选择公告状态", trigger: "blur" },
        ],
        isPopup: [
            { required: true, message: "请选择弹窗状态", trigger: "blur" },
        ],
    },
});

const {
    loading,
    multiple,
    queryParams,
    list,
    total,
    isCreate,
    dialog,
    formData,
    rules,
    activeLangTab,
} = toRefs(state);

function handleQuery() {
    emit("AnnounceClick", {});
    state.loading = true;
    announceManage(state.queryParams).then(({ data }) => {
        state.list = data.content;
        state.total = data.totalElements;
        state.loading = false;
    });
}

function handleReset() {
    state.queryParams = { pageNo: 1, pageSize: 15 } as AnnounceQueryParam;
    handleQuery();
}

function handleSelectionChange(selection: any) {
    state.ids = selection.map((item: any) => item.id);
    state.single = selection.length !== 1;
    state.multiple = !selection.length;
}

function handleAdd() {
    state.dialog = { title: "添加公告", visible: true };
    state.isCreate = true;
    state.activeLangTab = "zh_CN";
    state.formData = {
        id: 0,
        titles: emptyLangContent(),
        contents: emptyLangContent(),
        imgUrl: "",
        isTop: "1",
        isShow: true,
        announcementClassification: 0,
        sort: 0,
        createTime: "",
        isPopup: false,
        publishTime: "",
    };
}

function submitFormData() {
    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading.value = true;
            const payload = {
                ...state.formData,
                title: JSON.stringify(state.formData.titles),
                content: JSON.stringify(state.formData.contents),
            };
            if (state.formData.id) {
                updateAnnounce(state.formData.id, payload).then(() => {
                    ElMessage.success("修改成功");
                    cancel();
                    handleQuery();
                    loading.value = false;
                });
            } else {
                addAnnounce(payload).then(() => {
                    cancel();
                    ElMessage.success("添加成功");
                    handleQuery();
                    loading.value = false;
                });
            }
        }
    });
}

function cancel() {
    dialog.value.visible = false;
    state.activeLangTab = "zh_CN";
    state.formData = {
        id: 0,
        titles: emptyLangContent(),
        contents: emptyLangContent(),
        imgUrl: "",
        isTop: "1",
        isShow: false,
        announcementClassification: 0,
        sort: 0,
        createTime: "",
        isPopup: false,
        publishTime: "",
    };
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
}

function handleDelete() {
    const ids = [state.ids].join(",");
    ElMessageBox.confirm(
        "确认删除已选中的" + state.ids.length + "条数据项?",
        "警告",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(() => {
            delAnnounce({ ids: ids }).then(() => {
                ElMessage.success("删除成功");
                handleQuery();
            });
        })
        .catch(() => ElMessage.info("已取消删除"));
}

const viewEdit = (row: any) => {
    state.dialog = { title: "查看/编辑", visible: true };
    state.isCreate = false;
    state.activeLangTab = "zh_CN";
    state.formData = {
        id: row.id,
        titles: parseLangJson(row.title),
        contents: parseLangJson(row.content),
        imgUrl: row.imgUrl ?? "",
        isTop: row.isTop ?? "1",
        isShow: row.isShow,
        announcementClassification: row.announcementClassification,
        sort: row.sort ?? 0,
        createTime: row.createTime ?? "",
        isPopup: row.isPopup,
        publishTime: row.publishTime ?? "",
    };
};

const setTop = (row: any) => {
    stickTopAnnounce({ id: row.id }).then((res: any) => {
        if (!res.code) {
            ElMessage.success(res.message);
            handleQuery();
        } else {
            ElMessage.error(res.message);
        }
    });
};

const cancelTop = (row: any) => {
    announceDown({ id: row.id }).then((res: any) => {
        if (!res.code) {
            ElMessage.success(res.message);
            handleQuery();
        } else {
            ElMessage.error(res.message);
        }
    });
};

const openPopup = (row: any) => {
    announcePopupOn(row.id).then((res: any) => {
        if (!res.code) {
            ElMessage.success("已开启弹窗");
            handleQuery();
        } else {
            ElMessage.error(res.message);
        }
    });
};

const closePopup = (row: any) => {
    announcePopupOff(row.id).then((res: any) => {
        if (!res.code) {
            ElMessage.success("已关闭弹窗");
            handleQuery();
        } else {
            ElMessage.error(res.message);
        }
    });
};

/** 列表里显示公告标题：优先取中文，fallback 到第一个有内容的语言 */
function displayTitle(rawTitle: string): string {
    const t = parseLangJson(rawTitle);
    return t.zh_CN || t.zh_HK || t.en_US || t.ko_KR || t.ja_JP || t.hi_IN || t.id_ID || rawTitle;
}

onMounted(() => {
    handleQuery();
});
</script>

<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="标题">
                <el-input
                    v-model="queryParams.title"
                    placeholder="公告标题"
                    clearable
                    style="width: 160px"
                    @keyup.enter="handleQuery"
                />
            </el-form-item>
            <el-form-item label="分类">
                <el-select
                    v-model="queryParams.announcementClassification"
                    clearable
                    placeholder="全部"
                    style="width: 120px"
                >
                    <el-option label="一般公告" :value="0" />
                    <el-option label="活动公告" :value="1" />
                    <el-option label="充提公告" :value="2" />
                    <el-option label="系统公告" :value="3" />
                    <el-option label="上币公告" :value="4" />
                    <el-option label="投票公告" :value="5" />
                    <el-option label="合约公告" :value="7" />
                    <el-option label="其他" :value="6" />
                </el-select>
            </el-form-item>
            <el-form-item label="弹窗">
                <el-select
                    v-model="queryParams.isPopup"
                    clearable
                    placeholder="全部"
                    style="width: 100px"
                >
                    <el-option label="是" :value="true" />
                    <el-option label="否" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item label="状态">
                <el-select
                    v-model="queryParams.isShow"
                    clearable
                    placeholder="全部"
                    style="width: 100px"
                >
                    <el-option label="显示" :value="true" />
                    <el-option label="不显示" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
                <el-button :icon="RefreshLeft" @click="handleReset">重置</el-button>
                <el-button type="success" :icon="Plus" @click="handleAdd">添加</el-button>
                <el-button
                    type="danger"
                    :icon="Delete"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除</el-button>
            </el-form-item>
        </el-form>

        <!-- 数据表格 -->
        <el-table
            ref="dataTableRef"
            v-loading="loading"
            :data="list"
            @selection-change="handleSelectionChange"
            highlight-current-row
            border
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="编号" prop="id" min-width="70" align="center" />
            <el-table-column label="标题" min-width="200" align="center">
                <template #default="scope">
                    {{ displayTitle(scope.row.title) }}
                </template>
            </el-table-column>
            <el-table-column label="分类" prop="announcementClassification" min-width="100" align="center">
                <template #default="scope">
                    <span v-if="scope.row.announcementClassification == 0">一般公告</span>
                    <span v-else-if="scope.row.announcementClassification == 1">活动公告</span>
                    <span v-else-if="scope.row.announcementClassification == 2">充提公告</span>
                    <span v-else-if="scope.row.announcementClassification == 3">系统公告</span>
                    <span v-else-if="scope.row.announcementClassification == 4">上币公告</span>
                    <span v-else-if="scope.row.announcementClassification == 5">投票公告</span>
                    <span v-else-if="scope.row.announcementClassification == 7">合约公告</span>
                    <span v-else-if="scope.row.announcementClassification == 6">其他</span>
                </template>
            </el-table-column>
            <el-table-column label="显示" prop="isShow" min-width="70" align="center">
                <template #default="scope">
                    <span v-if="scope.row.isShow">是</span>
                    <span v-else>否</span>
                </template>
            </el-table-column>
            <el-table-column label="弹窗" prop="isPopup" min-width="70" align="center">
                <template #default="scope">
                    {{ scope.row.isPopup ? "是" : "否" }}
                </template>
            </el-table-column>
            <el-table-column label="置顶" prop="isTop" min-width="70" align="center">
                <template #default="scope">
                    <span v-if="scope.row.isTop === '0'">是</span>
                    <span v-else>否</span>
                </template>
            </el-table-column>
            <el-table-column label="发布时间" min-width="160" align="center">
                <template #default="scope">
                    {{ scope.row.publishTime || scope.row.createTime }}
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="340" fixed="right">
                <template #default="scope">
                    <el-button type="primary" size="small" @click.stop="viewEdit(scope.row)">查看/编辑</el-button>
                    <el-button
                        v-if="scope.row.isTop !== '0'"
                        type="warning"
                        size="small"
                        @click.stop="setTop(scope.row)"
                    >置顶</el-button>
                    <el-button
                        v-if="scope.row.isTop === '0'"
                        type="info"
                        size="small"
                        @click.stop="cancelTop(scope.row)"
                    >取消置顶</el-button>
                    <el-button
                        v-if="!scope.row.isPopup"
                        type="success"
                        size="small"
                        @click.stop="openPopup(scope.row)"
                    >开启弹窗</el-button>
                    <el-button
                        v-if="scope.row.isPopup"
                        type="danger"
                        size="small"
                        @click.stop="closePopup(scope.row)"
                    >关闭弹窗</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页工具条 -->
        <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
        />

        <!-- 表单弹窗 -->
        <el-dialog
            :title="dialog.title"
            v-model="dialog.visible"
            width="860px"
            destroy-on-close
        >
            <el-form
                ref="dataFormRef"
                :model="formData"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="创建时间" prop="createTime" v-if="!isCreate">
                    <el-input v-model="formData.createTime" disabled />
                </el-form-item>
                <el-form-item label="发布时间" prop="publishTime">
                    <el-date-picker
                        v-model="formData.publishTime"
                        type="datetime"
                        placeholder="选择发布时间（不填则默认当前时间）"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item label="公告类型" prop="announcementClassification">
                    <el-radio-group v-model="formData.announcementClassification">
                        <el-radio :label="0">一般公告</el-radio>
                        <el-radio :label="1">活动公告</el-radio>
                        <el-radio :label="2">充提公告</el-radio>
                        <el-radio :label="3">系统公告</el-radio>
                        <el-radio :label="4">上币公告</el-radio>
                        <el-radio :label="5">投票公告</el-radio>
                        <el-radio :label="7">合约公告</el-radio>
                        <el-radio :label="6">其他</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="公告状态" prop="isShow">
                    <el-radio-group v-model="formData.isShow">
                        <el-radio :label="true">显示</el-radio>
                        <el-radio :label="false">不显示</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="弹窗状态" prop="isPopup">
                    <el-radio-group v-model="formData.isPopup">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 多语言 Tab：标题 + 内容 -->
                <el-form-item :label-width="0">
                    <el-tabs v-model="activeLangTab" style="width: 100%">
                        <el-tab-pane
                            v-for="lang in LANGS"
                            :key="lang.key"
                            :label="lang.label"
                            :name="lang.key"
                        >
                            <el-form-item
                                :label="lang.label + ' 标题'"
                                label-width="100px"
                                style="margin-top: 12px"
                            >
                                <el-input
                                    v-model="formData.titles[lang.key as keyof typeof formData.titles]"
                                    :placeholder="'请输入 ' + lang.label + ' 标题'"
                                />
                            </el-form-item>
                            <el-form-item label-width="0" style="margin-top: 4px">
                                <editor
                                    v-model="formData.contents[lang.key as keyof typeof formData.contents]"
                                />
                            </el-form-item>
                        </el-tab-pane>
                    </el-tabs>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitFormData">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
