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

<script setup lang="ts">
import { onMounted, reactive, ref, computed, toRefs } from "vue";
import {
    ElTable,
    ElForm,
    ElMessage,
    ElMessageBox,
    UploadProps,
} from "element-plus";
import { Plus, Delete, UploadFilled } from "@element-plus/icons-vue";
import { manageAd, createAd, deleteAd, updateAd } from "@/api/cms";
import { AdQueryParam, AdItem, AdFormData } from "@/types/api/cms";
import { getAccessToken } from "@/utils/auth-token";

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

const state = reactive({
    loading: true,
    // 选中serialNumber数组
    serialNumbers: [],
    // 非单个禁用
    single: true,
    // 非多个禁用
    multiple: true,
    queryParams: {
        pageNo: 1,
        pageSize: 15,
    } as AdQueryParam,
    list: [] as AdItem[],
    total: 0,
    isCreate: false,
    dialog: {
        title: "",
        visible: false,
    },
    formData: {} as AdFormData,
    rules: {
        name: [{ required: true, message: "请输入广告名称", trigger: "blur" }],
        status: [
            { required: true, message: "请选择广告状态", trigger: "blur" },
        ],
        sysAdvertiseLocation: [
            { required: true, message: "请选择广告位置", trigger: "blur" },
        ],
        startTime: [
            { required: true, message: "请输入广告开始时间", trigger: "blur" },
        ],
        endTime: [
            { required: true, message: "请输入广告结束时间", trigger: "blur" },
        ],
        url: [{ required: true, message: "请上传广告图片", trigger: "blur" }],
        sort: [{ required: true, message: "请输入排序数值", trigger: "blur" }],
        lang: [{ required: true, message: "请选择广告语言", trigger: "blur" }],
    },
    uploadImageAction: `${
        import.meta.env.VITE_APP_BASE_API
    }/admin/common/upload/oss/image`,
});

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

const uploadHeaders = computed(() => {
    const token = getAccessToken();
    return token ? { Authorization: token } : {};
});

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

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

function handleAdd() {
    state.dialog = {
        title: "添加广告",
        visible: true,
    };
    state.isCreate = true;
    formData.value.serialNumber = "";
    formData.value.name = "";
    formData.value.status = 0;
    formData.value.sysAdvertiseLocation = 0;
    formData.value.startTime = "";
    formData.value.endTime = "";
    formData.value.remark = "";
    formData.value.url = "";
    formData.value.linkUrl = "";
    formData.value.sort = 1;
    formData.value.lang = "zh_CN";
    formData.value.createTime = "";
}

/**
 * 提交新增/编辑
 */
function submitFormData() {
    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading.value = true;
            if (state.formData.serialNumber) {
                updateAd(state.formData).then(() => {
                    ElMessage.success("修改成功");
                    cancel();
                    handleQuery();
                    loading.value = false;
                });
            } else {
                createAd(state.formData).then(() => {
                    cancel();
                    ElMessage.success("添加成功");
                    handleQuery();
                    loading.value = false;
                });
            }
        }
    });
}

/**
 * 取消
 */
function cancel() {
    dialog.value.visible = false;
    formData.value.serialNumber = "";
    formData.value.name = "";
    formData.value.status = 0;
    formData.value.sysAdvertiseLocation = 0;
    formData.value.startTime = "";
    formData.value.endTime = "";
    formData.value.remark = "";
    formData.value.url = "";
    formData.value.linkUrl = "";
    formData.value.sort = 0;
    formData.value.lang = "";
    formData.value.createTime = "";
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
}

/**
 *  删除
 */
function handleDelete() {
    const ids = [state.serialNumbers].join(",");
    ElMessageBox.confirm(
        "确认删除已选中的" + state.serialNumbers.length + "条数据项?",
        "警告",
        {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        }
    )
        .then(() => {
            deleteAd({ 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.serialNumber = row.serialNumber;
    formData.value.name = row.name;
    formData.value.status = row.status;
    formData.value.sysAdvertiseLocation = row.sysAdvertiseLocation;
    formData.value.startTime = row.startTime;
    formData.value.endTime = row.endTime;
    formData.value.remark = row.remark;
    formData.value.url = row.url;
    formData.value.linkUrl = row.linkUrl;
    formData.value.sort = row.sort;
    formData.value.lang = row.lang;
    formData.value.createTime = row.createTime;
};

/**
 * 上传前，检查是否图片文件，且大小不能操作10MB
 */
const beforeImgUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (
        rawFile.type !== "image/jpeg" &&
        rawFile.type !== "image/png" &&
        rawFile.type !== "image/bmp" &&
        rawFile.type !== "image/gif"
    ) {
        ElMessage.error("请上传图片格式文件");
        return false;
    } else if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error("上传的图片文件大小不能超过 10MB!");
        return false;
    }
    return true;
};

/**
 * 上传成功
 * @param response
 * @param uploadFile
 */
const handleImgSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
    state.formData.url = response.data; //URL.createObjectURL(uploadFile.raw!)
};

/**
 * 上传失败
 */
const errorImgUpload = () => {
    ElMessage.error("上传失败");
};

/**
 * 上传中
 * @param evt
 * @param uploadFile
 */
const progressImgUpload: UploadProps["onProgress"] = (
    evt,
    uploadFile,
    uploadFiles
) => {
    ElMessage.info("上传中..");
};

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="name" align="center" />
            <el-table-column
                label="广告位置"
                prop="sysAdvertiseLocation"
                align="center"
            >
                <template #default="scope">
                    <span v-if="scope.row.sysAdvertiseLocation == 0"
                        >APP轮播</span
                    >
                    <span v-else-if="scope.row.sysAdvertiseLocation == 1"
                        >PC轮播</span
                    >
                    <span v-else-if="scope.row.sysAdvertiseLocation == 2"
                        >PC分类</span
                    >
                    <span v-else></span>
                </template>
            </el-table-column>
            <el-table-column label="语言" prop="lang" 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="url" align="center">
                <template #default="scope">
                    <el-image :src="scope.row.url" loading="lazy" />
                </template>
            </el-table-column>
            <el-table-column label="跳转链接" prop="linkUrl" align="center">
                <template #default="scope">
                    <a :href="scope.row.linkUrl" target="_blank">{{
                        scope.row.linkUrl
                    }}</a>
                </template>
            </el-table-column>
            <el-table-column
                label="时间"
                prop="startTime"
                min-width="160"
                align="center"
            >
                <template #default="scope">
                    <p>开始时间：{{ scope.row.startTime }}</p>
                    <p>结束时间：{{ scope.row.endTime }}</p>
                </template>
            </el-table-column>
            <el-table-column label="上线/下线" prop="status" align="center">
                <template #default="scope">
                    <span v-if="scope.row.status == 0">上线</span>
                    <span v-else-if="scope.row.status == 1">下线</span>
                    <span v-else></span>
                </template>
            </el-table-column>
            <el-table-column
                label="操作"
                align="center"
                width="160"
                fixed="right"
            >
                <template #default="scope">
                    <el-button
                        type="primary"
                        size="small"
                        @click.stop="viewEdit(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="500px"
            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="serialNumber"
                    v-if="!isCreate"
                >
                    <el-input
                        v-model="formData.serialNumber"
                        placeholder="请输入"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="广告排序" prop="sort">
                    <el-input-number
                        v-model="formData.sort"
                        :min="1"
                        :max="100"
                    />
                </el-form-item>
                <el-form-item label="广告名称" prop="name">
                    <el-input
                        v-model="formData.name"
                        placeholder="请输入广告名称"
                    />
                </el-form-item>
                <el-form-item label="广告状态" prop="status">
                    <el-radio-group v-model="formData.status">
                        <el-radio :label="0">上线</el-radio>
                        <el-radio :label="1">下线</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="广告位置" prop="sysAdvertiseLocation">
                    <el-radio-group v-model="formData.sysAdvertiseLocation">
                        <el-radio :label="0">APP轮播</el-radio>
                        <el-radio :label="1">PC轮播</el-radio>
                        <el-radio :label="2">PC分类</el-radio>
                    </el-radio-group>
                </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="startTime">
                    <el-date-picker
                        v-model="formData.startTime"
                        style="width: 210px"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        type="datetime"
                        placeholder="开始时间"
                    />
                </el-form-item>
                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                        v-model="formData.endTime"
                        style="width: 210px"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        type="datetime"
                        placeholder="结束时间"
                    />
                </el-form-item>
                <el-form-item label="广告图片" prop="url">
                    <el-upload
                        class="avatar-uploader"
                        :action="uploadImageAction"
                        :headers="uploadHeaders"
                        :show-file-list="false"
                        :before-upload="beforeImgUpload"
                        :on-success="handleImgSuccess"
                        :on-error="errorImgUpload"
                    >
                        <img
                            v-if="formData.url"
                            :src="formData.url"
                            class="reshow-img"
                        />
                        <el-button v-else size="default" :icon="UploadFilled"
                            >添加图片</el-button
                        >
                    </el-upload>
                </el-form-item>
                <el-form-item label="图片地址" prop="url">
                    <el-input
                        v-model="formData.url"
                        placeholder="图片地址"
                        disabled
                    />
                </el-form-item>
                <el-form-item label="跳转地址" prop="linkUrl">
                    <el-input
                        type="text"
                        v-model="formData.linkUrl"
                        placeholder="请输入跳转地址"
                    />
                </el-form-item>
                <el-form-item label="广告备注" prop="remark">
                    <el-input
                        type="textarea"
                        v-model="formData.remark"
                        placeholder="添加广告备注..."
                    />
                </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>

<style lang="scss" scoped>
.reshow-img {
    max-width: 80px;
    max-height: 80px;
}
</style>
