<script lang="ts">
export default {
    name: "banner",
};
</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 {
    bannerList,
    createBanner,
    deleteBanner,
    updateBanner,
    enableBanner,
    disableBanner,
} from "@/api/cms";
import { BannerQueryParam, BannerItem, BannerFormData } from "@/types/api/cms";
import { getAccessToken } from "@/utils/auth-token";

// APP 内部跳转 URI 预设列表
const internalUriOptions = [
    { label: "首页", value: "/" },
    { label: "行情", value: "/market" },
    { label: "合约交易-BTCUSDT", value: "/futures/BTCUSDT" },
    { label: "合约交易-ETHUSDT", value: "/futures/ETHUSDT" },
    { label: "跟单广场", value: "/copy-trading" },
    { label: "我的跟单", value: "/my-copy-trading" },
    { label: "申请带单", value: "/trader-apply" },
    { label: "我的带单", value: "/my-trades" },
    { label: "资产总览", value: "/asset" },
    { label: "充币", value: "/asset/deposit" },
    { label: "提币", value: "/asset/withdraw" },
    { label: "划转", value: "/asset/transfer" },
    { label: "资产记录", value: "/asset/history" },
    { label: "邀请返佣", value: "/user/referral" },
    { label: "个人中心", value: "/user" },
    { label: "账户设置", value: "/user/account" },
    { label: "身份认证(KYC)", value: "/user/kyc" },
    { label: "API管理", value: "/user/api-keys" },
    { label: "帮助中心", value: "/user/help" },
    { label: "经纪商", value: "/broker" },
    { label: "自定义URI", value: "__custom__" },
];

const dataTableRef = ref(ElTable);
const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const state = reactive({
    loading: true,
    ids: [] as number[],
    multiple: true,
    queryParams: {
        pageNo: 1,
        pageSize: 15,
    } as BannerQueryParam,
    list: [] as BannerItem[],
    total: 0,
    isCreate: false,
    dialog: {
        title: "",
        visible: false,
    },
    formData: {
        title: "",
        imageUrl: "",
        linkType: "internal",
        linkUrl: "",
        sort: 0,
        status: 1,
        startTime: "",
        endTime: "",
    } as BannerFormData,
    // 内部跳转下拉选中值（可能是预设 URI 或 "__custom__"）
    selectedInternalUri: "/",
    // 自定义 URI 输入
    customLinkUrl: "",
    rules: {
        title: [
            { required: true, message: "请输入Banner标题", trigger: "blur" },
        ],
        imageUrl: [
            { required: true, message: "请上传Banner图片", trigger: "change" },
        ],
        linkType: [
            {
                required: true,
                message: "请选择跳转类型",
                trigger: "change",
            },
        ],
        linkUrl: [
            { 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() {
    state.loading = true;
    bannerList(state.queryParams).then(({ data }) => {
        state.list = data.content;
        state.total = data.totalElements;
        state.loading = false;
    });
}

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

function resetFormData() {
    state.formData = {
        title: "",
        imageUrl: "",
        linkType: "internal",
        linkUrl: "/",
        sort: 0,
        status: 1,
        startTime: "",
        endTime: "",
    };
    state.selectedInternalUri = "/";
    state.customLinkUrl = "";
}

function handleAdd() {
    state.dialog = { title: "添加Banner", visible: true };
    state.isCreate = true;
    resetFormData();
}

function viewEdit(row: any) {
    state.dialog = { title: "查看/编辑", visible: true };
    state.isCreate = false;
    state.formData = {
        id: row.id,
        title: row.title,
        imageUrl: row.imageUrl,
        linkType: row.linkType,
        linkUrl: row.linkUrl,
        sort: row.sort,
        status: row.status,
        startTime: row.startTime || "",
        endTime: row.endTime || "",
    };
    if (row.linkType === "internal") {
        const preset = internalUriOptions.find(
            (o) => o.value === row.linkUrl && o.value !== "__custom__"
        );
        if (preset) {
            state.selectedInternalUri = row.linkUrl;
            state.customLinkUrl = "";
        } else {
            state.selectedInternalUri = "__custom__";
            state.customLinkUrl = row.linkUrl;
        }
    }
}

function onLinkTypeChange() {
    state.formData.linkUrl = "";
    state.selectedInternalUri = "/";
    state.customLinkUrl = "";
    if (state.formData.linkType === "internal") {
        state.formData.linkUrl = "/";
        state.selectedInternalUri = "/";
    }
}

function onInternalUriChange(val: string) {
    if (val !== "__custom__") {
        state.formData.linkUrl = val;
        state.customLinkUrl = "";
    } else {
        state.formData.linkUrl = state.customLinkUrl;
    }
}

function onCustomUriInput(val: string) {
    state.formData.linkUrl = val;
}

function submitFormData() {
    dataFormRef.value.validate((valid: any) => {
        if (valid) {
            loading.value = true;
            if (state.formData.id) {
                updateBanner(state.formData).then(() => {
                    ElMessage.success("修改成功");
                    cancel();
                    handleQuery();
                    loading.value = false;
                });
            } else {
                createBanner(state.formData).then(() => {
                    ElMessage.success("添加成功");
                    cancel();
                    handleQuery();
                    loading.value = false;
                });
            }
        }
    });
}

function cancel() {
    dialog.value.visible = false;
    resetFormData();
    dataFormRef.value.resetFields();
    dataFormRef.value.clearValidate();
}

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

function handleToggleStatus(row: any) {
    const isEnable = row.status === 0;
    const action = isEnable ? enableBanner : disableBanner;
    const label = isEnable ? "启用" : "禁用";
    ElMessageBox.confirm(`确认${label}该Banner?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            action({ id: row.id }).then(() => {
                ElMessage.success(`${label}成功`);
                handleQuery();
            });
        })
        .catch(() => {});
}

const beforeImgUpload: UploadProps["beforeUpload"] = (rawFile) => {
    if (
        !["image/jpeg", "image/png", "image/bmp", "image/gif"].includes(
            rawFile.type
        )
    ) {
        ElMessage.error("请上传图片格式文件");
        return false;
    }
    if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error("上传的图片大小不能超过 10MB!");
        return false;
    }
    return true;
};

const handleImgSuccess: UploadProps["onSuccess"] = (response) => {
    state.formData.imageUrl = response.data;
};

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

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="ID" prop="id" width="70" align="center" />
            <el-table-column label="Banner图片" width="120" align="center">
                <template #default="scope">
                    <el-image
                        :src="scope.row.imageUrl"
                        style="width: 80px; height: 40px; object-fit: cover"
                        loading="lazy"
                        :preview-src-list="[scope.row.imageUrl]"
                        preview-teleported
                    />
                </template>
            </el-table-column>
            <el-table-column label="标题" prop="title" align="center" />
            <el-table-column label="跳转类型" prop="linkType" width="100" align="center">
                <template #default="scope">
                    <el-tag
                        :type="
                            scope.row.linkType === 'internal'
                                ? 'primary'
                                : 'warning'
                        "
                    >
                        {{
                            scope.row.linkType === "internal"
                                ? "内部页面"
                                : "外部网页"
                        }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column
                label="跳转地址"
                prop="linkUrl"
                align="center"
                show-overflow-tooltip
            />
            <el-table-column label="排序" prop="sort" width="70" align="center" />
            <el-table-column label="状态" prop="status" width="80" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                        {{ scope.row.status === 1 ? "启用" : "禁用" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column
                label="有效时间"
                min-width="160"
                align="center"
            >
                <template #default="scope">
                    <p v-if="scope.row.startTime">
                        开始：{{ scope.row.startTime }}
                    </p>
                    <p v-if="scope.row.endTime">
                        结束：{{ scope.row.endTime }}
                    </p>
                    <span v-if="!scope.row.startTime && !scope.row.endTime"
                        >不限</span
                    >
                </template>
            </el-table-column>
            <el-table-column
                label="创建时间"
                prop="createTime"
                width="160"
                align="center"
            />
            <el-table-column
                label="操作"
                align="center"
                width="180"
                fixed="right"
            >
                <template #default="scope">
                    <el-button
                        type="primary"
                        size="small"
                        @click.stop="viewEdit(scope.row)"
                        >编辑</el-button
                    >
                    <el-button
                        :type="scope.row.status === 1 ? 'warning' : 'success'"
                        size="small"
                        @click.stop="handleToggleStatus(scope.row)"
                    >
                        {{ scope.row.status === 1 ? "禁用" : "启用" }}
                    </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="560px"
            destroy-on-close
        >
            <el-form
                ref="dataFormRef"
                :model="formData"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="Banner标题" prop="title">
                    <el-input
                        v-model="formData.title"
                        placeholder="请输入Banner标题"
                    />
                </el-form-item>

                <el-form-item label="Banner图片" prop="imageUrl">
                    <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.imageUrl"
                            :src="formData.imageUrl"
                            class="banner-preview"
                        />
                        <el-button v-else size="default" :icon="UploadFilled"
                            >上传图片</el-button
                        >
                    </el-upload>
                    <div class="img-tip">建议尺寸 750×300，支持 jpg/png，≤10MB</div>
                </el-form-item>

                <el-form-item label="图片地址" prop="imageUrl">
                    <el-input
                        v-model="formData.imageUrl"
                        placeholder="图片URL（上传后自动填入）"
                    />
                </el-form-item>

                <el-form-item label="跳转类型" prop="linkType">
                    <el-radio-group
                        v-model="formData.linkType"
                        @change="onLinkTypeChange"
                    >
                        <el-radio label="internal">APP内部页面</el-radio>
                        <el-radio label="external">外部网页</el-radio>
                    </el-radio-group>
                </el-form-item>

                <!-- 内部跳转：下拉选择预设 URI -->
                <el-form-item
                    v-if="formData.linkType === 'internal'"
                    label="内部页面"
                    prop="linkUrl"
                >
                    <el-select
                        v-model="state.selectedInternalUri"
                        placeholder="请选择跳转页面"
                        style="width: 100%"
                        @change="onInternalUriChange"
                    >
                        <el-option
                            v-for="item in internalUriOptions"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                    <el-input
                        v-if="state.selectedInternalUri === '__custom__'"
                        v-model="state.customLinkUrl"
                        placeholder="请输入自定义 URI，如 /futures/SOLUSDT"
                        style="margin-top: 8px"
                        @input="onCustomUriInput"
                    />
                    <div class="uri-tip" v-if="formData.linkUrl">
                        当前地址：<b>{{ formData.linkUrl }}</b>
                    </div>
                </el-form-item>

                <!-- 外部链接：文本框 -->
                <el-form-item
                    v-if="formData.linkType === 'external'"
                    label="外部链接"
                    prop="linkUrl"
                >
                    <el-input
                        v-model="formData.linkUrl"
                        placeholder="请输入完整URL，如 https://example.com"
                    />
                </el-form-item>

                <el-form-item label="排序" prop="sort">
                    <el-input-number
                        v-model="formData.sort"
                        :min="0"
                        :max="9999"
                    />
                    <span class="sort-tip">数值越大越靠前</span>
                </el-form-item>

                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="formData.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker
                        v-model="formData.startTime"
                        style="width: 100%"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        type="datetime"
                        placeholder="不填则不限制开始时间"
                        clearable
                    />
                </el-form-item>

                <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker
                        v-model="formData.endTime"
                        style="width: 100%"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        type="datetime"
                        placeholder="不填则不限制结束时间"
                        clearable
                    />
                </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>
.banner-preview {
    max-width: 200px;
    max-height: 80px;
    object-fit: contain;
    display: block;
}
.img-tip {
    color: #999;
    font-size: 12px;
    margin-top: 4px;
}
.sort-tip {
    color: #999;
    font-size: 12px;
    margin-left: 8px;
}
.uri-tip {
    color: #666;
    font-size: 12px;
    margin-top: 4px;
}
</style>
