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

<script setup lang="ts">
import moment from "moment";
import { onMounted, reactive, ref, toRefs } from "vue";
import { ElTable, ElForm, ElMessage, ElMessageBox } from "element-plus";
import { Plus, Delete } from "@element-plus/icons-vue";
// 自定义组件依赖
import Editor from "@/components/WangEditor/index.vue";
import { stickTopAnnounce, announceDown } from "@/api/cms";
import {
    messageAllsendList,
    messageType,
    addMessageAllsend,
    messageAllsendUpdate,
    messageAllsendDel,
} from "@/api/messageCenter/index";
import { AnnounceFormData } from "@/types/api/messageCenter/index";

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

const state = reactive({
    loading: true,
    // 选中ids数组
    ids: [],
    // 非单个禁用
    single: true,
    // 非多个禁用
    multiple: true,
    typeList: [] as any,
    queryParams: {
        currentPage: 1,
        pageSize: 15,
        messageTitle: "",
        messageTypeId: "",
    },
    list: [],
    total: 0,
    isCreate: false,
    dialog: {
        title: "",
        visible: false,
    },
    formData: {} as AnnounceFormData,
    rules: {
        messageTitle: [
            { required: true, message: "请输入公告标题", trigger: "blur" },
        ],
        messageTypeId: [
            { required: true, message: "请选择公告分类", trigger: "blur" },
        ],
        // lang: [{ required: true, message: "请选择公告语言", trigger: "blur" }],
        // isShow: [
        //     { required: true, message: "请选择公告状态", trigger: "blur" },
        // ],
    },
    sendNow: true,
});

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

function handleQuery() {
    state.loading = true;
    messageAllsendList(state.queryParams).then(({ data }) => {
        state.list = data.records;
        state.total = data.total;
        state.loading = false;
    });
    messageType().then(({ data }) => {
        state.typeList = data;
    });
}

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;
    formData.value.id = 0;
    formData.value.messageTitle = "";
    formData.value.imgUrl = "";
    formData.value.lang = "zh_CN";
    state.sendNow = true;
    formData.value.messageTypeId = 1;
    formData.value.content = "";
    formData.value.createTime = "";
}

/**
 * 提交新增/编辑
 */
function submitFormData() {
    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading.value = true;
            if (state.formData.id) {
                if (state.sendNow) {
                    state.formData.sendTime = moment().format();
                }
                console.log(state.formData);
                messageAllsendUpdate(state.formData).then(() => {
                    ElMessage.success("修改成功");
                    cancel();
                    handleQuery();
                    loading.value = false;
                });
            } else {
                addMessageAllsend(state.formData, state.sendNow).then(() => {
                    cancel();
                    ElMessage.success("添加成功");
                    handleQuery();
                    loading.value = false;
                });
            }
        }
    });
}

/**
 * 取消
 */
function cancel() {
    dialog.value.visible = false;
    formData.value.id = 0;
    formData.value.messageTitle = "";
    formData.value.imgUrl = "";
    formData.value.lang = "";
    formData.value.isShow = false;
    formData.value.messageTypeId = 0;
    formData.value.content = "";
    formData.value.createTime = "";
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
}

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

/**
 * 查看 / 编辑
 * @param row
 */
const viewEdit = (row: any) => {
    state.dialog = {
        title: "修改",
        visible: true,
    };
    state.isCreate = false;
    formData.value.id = row.id;
    formData.value.messageTitle = row.messageTitle;
    state.sendNow = row.isSend;
    formData.value.messageTypeId = row.messageTypeId;
    formData.value.content = row.content;
    formData.value.createTime = row.createdTime;
    formData.value.sendTime = row.sendTime;
};

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

/**
 * 取消置顶
 * @param row
 */
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 messageJudgment = (row: any) => {
    let type = [] as any;
    type = state.typeList.filter((item: any) => {
        if (item.id == row) {
            return item;
        }
    });
    if (type.length >= 1) {
        return type[0].messageTypeCn;
    } else {
        return "-";
    }
};

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

<template>
    <div class="app-container">
        <!-- 搜索表单 -->
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item>
                <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="80"
                align="center"
            />
            <el-table-column
                label="标题"
                prop="messageTitle"
                min-width="180"
                align="center"
            />
            <el-table-column
                label="消息类型"
                prop="messageTypeId"
                min-width="100"
                align="center"
            >
                <template #default="scope">
                    <span>{{ messageJudgment(scope.row.messageTypeId) }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="内容"
                prop="content"
                min-width="280"
                align="center"
                show-overflow-tooltip
            >
                <!-- <template #default="scope">
                    <div v-html="scope.row.content"></div>
                </template> -->
            </el-table-column>
            <!-- <el-table-column
                label="语言"
                prop="lang"
                min-width="100"
                align="center"
            >
                <template #default="scope">
                    <span v-if="scope.row.lang == 'en_US'">English</span>
                    <span v-else-if="scope.row.lang == 'ja_JP'">日语</span>
                    <span v-else-if="scope.row.lang == 'ko_KR'">韩语</span>
                    <span v-else-if="scope.row.lang == 'de_DE'">德语</span>
                    <span v-else-if="scope.row.lang == 'fr_FR'">法语</span>
                    <span v-else-if="scope.row.lang == 'it_IT'">意大利</span>
                    <span v-else-if="scope.row.lang == 'es_ES'">西班牙</span>
                    <span v-else-if="scope.row.lang == 'zh_HK'">中文繁体</span>
                    <span v-else>中文</span>
                </template>
            </el-table-column> -->
            <!-- <el-table-column
                label="显示"
                prop="isShow"
                min-width="80"
                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="isSend"
                min-width="80"
                align="center"
            >
                <template #default="scope">
                    <span v-if="scope.row.isSend">已发送</span>
                    <span v-else>未发送</span>
                </template>
            </el-table-column>
            <!-- <el-table-column
                label="置顶"
                prop="isTop"
                min-width="80"
                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="发布时间"
                prop="createdTime"
                min-width="170"
                align="center"
            />
            <el-table-column
                label="修改时间"
                prop="updatedTime"
                min-width="170"
                align="center"
            />
            <el-table-column label="操作" align="center" fixed="right">
                <template #default="scope">
                    <el-button
                        type="primary"
                        size="small"
                        @click.stop="viewEdit(scope.row)"
                        >修改</el-button
                    >
                    <!-- <el-button
                        type="danger"
                        size="small"
                        @click.stop="setTop(scope.row)"
                        >置顶</el-button
                    >
                    <el-button
                        type="danger"
                        size="small"
                        @click.stop="cancelTop(scope.row)"
                        >取消置顶</el-button
                    > -->
                </template>
            </el-table-column>
        </el-table>

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

        <!-- 表单弹窗 -->
        <el-dialog
            :title="dialog.title"
            v-model="dialog.visible"
            width="800px"
            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"
                        placeholder="请输入"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="标题" prop="title">
                    <el-input
                        v-model="formData.messageTitle"
                        placeholder="请输入"
                    />
                </el-form-item>
                <el-form-item label="消息类型" prop="messageTypeId">
                    <el-radio-group v-model="formData.messageTypeId">
                        <el-radio
                            :label="item.id"
                            v-for="(item, index) in state.typeList"
                            >{{ item.messageTypeCn }}</el-radio
                        >
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="发送类型">
                    <el-select
                        v-model="state.sendNow"
                        class="m-2"
                        placeholder="Select"
                    >
                        <el-option :value="false" label="定时发送" />
                        <el-option :value="true" label="立即发送" />
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="发送时间"
                    prop="messageTypeId"
                    v-if="!state.sendNow"
                >
                    <el-date-picker
                        v-model="formData.sendTime"
                        type="datetime"
                        placeholder="Select date and time"
                    />
                </el-form-item>
                <!-- <el-form-item label="公告语言" prop="lang">
                    <el-radio-group v-model="formData.lang">
                        <el-radio label="zh_CN">中文</el-radio>
                        <el-radio label="en_US">English</el-radio>
                        <el-radio label="ja_JP">日语</el-radio>
                        <el-radio label="ko_KR">韩语</el-radio>
                        <el-radio label="de_DE">德语</el-radio>
                        <el-radio label="fr_FR">法语</el-radio>
                        <el-radio label="it_IT">意大利</el-radio>
                        <el-radio label="es_ES">西班牙</el-radio>
                        <el-radio label="zh_HK">繁体</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-width="0" prop="content">
                    <editor v-model="formData.content" />
                </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>
