<template>
    <div class="app-container">
        <el-row>
            <el-col :span="22">
                <el-form ref="queryFormRef" :model="queryParams" :inline="true">
                    <el-form-item prop="coinSymbol">
                        <el-input
                            v-model="queryParams.coinSymbol"
                            placeholder="币种"
                            style="width: 200px"
                            clearable
                            @keyup.enter="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item prop="startTime">
                        <el-date-picker
                            v-model="queryParams.startTime"
                            type="date"
                            placeholder="更新开始时间"
                            value-format="YYYY-MM-DD"
                            style="width: 200px"
                        />
                    </el-form-item>
                    <el-form-item prop="endTime">
                        <el-date-picker
                            v-model="queryParams.endTime"
                            type="date"
                            placeholder="更新结束时间"
                            value-format="YYYY-MM-DD"
                            style="width: 200px"
                        />
                    </el-form-item>
                    <el-form-item>
                        <el-button
                            type="primary"
                            :icon="Search"
                            @click="handleQuery"
                            >搜索</el-button
                        >
                        <el-button :icon="Refresh" @click="resetQuery"
                            >重置</el-button
                        >
                    </el-form-item>
                </el-form>
            </el-col>
            <el-col :span="2">
                <el-button type="success" @click="openDialog('add')"
                    >新增币种</el-button
                >
            </el-col>
        </el-row>
        <el-table
            :data="listdata"
            v-loading="loading"
            highlight-current-row
            border
        >
            <el-table-column
                label="图标"
                prop="icon"
                width="70"
                align="center"
            >
                <template #default="scope">
                    <img
                        v-if="scope.row.icon"
                        :src="scope.row.icon"
                        style="width: 32px; height: 32px; object-fit: contain; border-radius: 4px;"
                    />
                    <span v-else>-</span>
                </template>
            </el-table-column>
            <el-table-column
                align="center"
                prop="coinSymbol"
                label="币种"
            />
            <el-table-column align="center" prop="isOpen" label="是否启用">
                <template #default="scope">
                    {{ scope.row.isOpen == 1 ? '是' : '否' }}
                </template>
            </el-table-column>
            <el-table-column align="center" prop="mtime" label="最近更新时间" min-width="160" />
            <el-table-column
                fixed="right"
                align="center"
                label="操作"
                min-width="180"
            >
                <template #default="scope">
                    <el-button
                        type="primary"
                        size="small"
                        @click="openDialog('update', scope.row)"
                        >编辑</el-button
                    >
                    <el-button
                        :type="scope.row.isOpen == 1 ? 'warning' : 'success'"
                        size="small"
                        @click="toggleStatus(scope.row)"
                    >
                        {{ scope.row.isOpen == 1 ? '关闭' : '启用' }}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            width="700px"
        >
            <el-form ref="formRef" :model="form" :inline="true">
                <el-form-item prop="coinSymbol" label="币种简称" label-width="120px">
                    <el-input
                        v-model="form.coinSymbol"
                        placeholder="如：BTC、USDT"
                        style="width: 200px"
                    />
                </el-form-item>
                <el-form-item prop="name" label="币种别名" label-width="120px">
                    <el-input
                        v-model="form.name"
                        placeholder="前台展示名称"
                        style="width: 200px"
                    />
                </el-form-item>
                <el-form-item prop="icon" label="币种LOGO" label-width="120px">
                    <el-upload
                        class="avatar-uploader"
                        :show-file-list="false"
                        :http-request="handleUpload"
                        :before-upload="beforeIconUpload"
                    >
                        <img
                            v-if="form.icon"
                            :src="form.icon"
                            style="width: 48px; height: 48px; object-fit: contain; border-radius: 4px;"
                        />
                        <el-button v-else size="default" :icon="UploadFilled">上传图标</el-button>
                    </el-upload>
                </el-form-item>
                <el-form-item prop="isOpen" label="是否开启" label-width="120px">
                    <el-select
                        v-model="form.isOpen"
                        placeholder="请选择"
                        style="width: 200px"
                    >
                        <el-option label="是" :value="1" />
                        <el-option label="否" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="isQuote" label="是否为计价货币" label-width="120px">
                    <el-select
                        v-model="form.isQuote"
                        placeholder="请选择"
                        style="width: 200px"
                    >
                        <el-option label="是" :value="1" />
                        <el-option label="否" :value="0" />
                    </el-select>
                </el-form-item>
                <el-form-item prop="sort" label="排序" label-width="120px">
                    <el-input
                        v-model="form.sort"
                        placeholder="排序值"
                        style="width: 200px"
                    />
                </el-form-item>
                <el-form-item prop="showPrecision" label="显示精度" label-width="120px">
                    <el-input
                        v-model="form.showPrecision"
                        placeholder="显示精度"
                        style="width: 200px"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button type="primary" @click="submitForm">确认</el-button>
                <el-button @click="closeDialog">取消</el-button>
            </template>
        </el-dialog>
        <pagination
            v-if="total > 0"
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
        />
    </div>
</template>
<script lang="ts">
name: "coinSymbolConfig";
</script>
<script lang="ts" setup>
import { reactive, onMounted, ref } from "vue";
import { Search, Refresh, UploadFilled } from "@element-plus/icons-vue";
import { ElForm, ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import {
    configCoinSymbolPage,
    configCoinSymbolCreate,
    configCoinSymbolUpdate,
    configCoinSymbolToggle,
} from "@/api/coinSpot";
import { uploadFile } from "@/api/system/file";
import { CoinSymbolConfig } from "@/types/api/coinspot";

const queryFormRef = ref(ElForm);
const formRef = ref(ElForm);

const loading = ref(true);
const total = ref(0);
const listdata = ref<CoinSymbolConfig[]>([]);
const dialogVisible = ref(false);
const dialogTitle = ref("新增");

const handleUpload: UploadProps["httpRequest"] = (options) => {
    uploadFile(options.file).then((res: any) => {
        if (res.code === 0 && res.data) {
            form.icon = res.data;
            ElMessage.success("上传成功");
        } else {
            ElMessage.error(res.message || "上传失败");
        }
    }).catch(() => {
        ElMessage.error("上传失败");
    });
};

const queryParams = reactive({
    coinSymbol: "",
    startTime: "",
    endTime: "",
    pageNo: 1,
    pageSize: 15,
});

const form = reactive<Partial<CoinSymbolConfig>>({
    coinSymbol: "",
    name: "",
    icon: "",
    isOpen: 1,
    isQuote: 0,
    sort: 0,
    showPrecision: undefined,
    contractPrecision: undefined,
    tokenBase: "",
});

function handleQuery() {
    loading.value = true;
    configCoinSymbolPage({
        pageNo: queryParams.pageNo,
        pageSize: queryParams.pageSize,
        coinSymbol: queryParams.coinSymbol || undefined,
        startTime: queryParams.startTime || undefined,
        endTime: queryParams.endTime || undefined,
    }).then((res: any) => {
        listdata.value = res.data.content;
        total.value = res.data.totalElements;
        loading.value = false;
    });
}

function resetQuery() {
    queryFormRef.value.resetFields();
    handleQuery();
}

function openDialog(type: string, row?: CoinSymbolConfig) {
    dialogVisible.value = true;
    dialogTitle.value = type === "add" ? "新增" : "修改";
    if (row) {
        Object.assign(form, {
            id: row.id,
            coinSymbol: row.coinSymbol,
            name: row.name,
            icon: row.icon || "",
            isOpen: row.isOpen,
            isQuote: row.isQuote,
            sort: row.sort,
            showPrecision: row.showPrecision,
            contractPrecision: row.contractPrecision,
            tokenBase: row.tokenBase || "",
        });
    } else {
        Object.assign(form, {
            id: undefined,
            coinSymbol: "",
            name: "",
            icon: "",
            isOpen: 1,
            isQuote: 0,
            sort: 0,
            showPrecision: undefined,
            contractPrecision: undefined,
            tokenBase: "",
        });
    }
}

function closeDialog() {
    dialogVisible.value = false;
    formRef.value.resetFields();
}

async function submitForm() {
    const api = form.id ? configCoinSymbolUpdate : configCoinSymbolCreate;
    const data: any = {
        coinSymbol: form.coinSymbol,
        name: form.name,
        icon: form.icon || undefined,
        isOpen: form.isOpen,
        isQuote: form.isQuote,
        sort: Number(form.sort),
        showPrecision: Number(form.showPrecision),
        contractPrecision: form.contractPrecision != null ? Number(form.contractPrecision) : undefined,
        tokenBase: form.tokenBase || undefined,
    };
    if (form.id) data.id = form.id;
    const res: any = await api(data);
    if (res.code === 0) {
        closeDialog();
        ElMessage.success("操作成功");
        handleQuery();
    } else {
        ElMessage.error("操作失败");
    }
}

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

function toggleStatus(row: CoinSymbolConfig) {
    const action = row.isOpen == 1 ? '关闭' : '启用';
    ElMessageBox.confirm(`确认${action}币种 ${row.coinSymbol}？`, "提示", {
        type: "warning",
    }).then(() => {
        configCoinSymbolToggle(row.id).then((res: any) => {
            if (res.code === 0) {
                ElMessage.success("操作成功");
                handleQuery();
            } else {
                ElMessage.error("操作失败");
            }
        });
    });
}

onMounted(() => handleQuery());
</script>
<style lang="less" scoped>
.avatar-uploader {
    :deep(.el-upload) {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        overflow: hidden;
        &:hover {
            border-color: #409eff;
        }
    }
}
</style>
