<script setup>
import {reactive} from "vue";
import useTableQuery from "../../../../../hooks/useTableQuery.js";
import Api from "../../../../../api/index.js";
import SequenceAdjustment from "../../../../../components/SequenceAdjustment/index.vue";
import {Message} from "@arco-design/web-vue";

const columns = [
    {
        title: 'ID',
        dataIndex: 'id',
        width: 120,
    },
    {
        title: '内容',
        dataIndex: 'title',
        slotName: 'content',
    },
    {
        title: '排序',
        dataIndex: 'sort',
        slotName: 'sort',
        width: 140,
    },
    {
        title: '操作',
        dataIndex: 'action',
        slotName: 'action',
        width: 60,
    },
];

const po = reactive({});
const vo = reactive({
    page: '',
    rows: [],
    total: 0,
});

const {loading, pagination, initFetchData, fetchData} = useTableQuery({
    parameter: po,
    api: Api.admin.getBarragelist,
    callback: (data) => {
        Object.assign(vo, data);
    }
});

const success = async (item) => {
    if (item.id !== null) {
        const {msg, code} = await Api.admin.editBarrage({
            id: item.id,
            title: item.title
        });
        if (code === 1) Message.success(msg);
    } else {
        const {msg, code} = await Api.admin.addBarrage({
            title: item.title
        });
        if (code === 1) Message.success(msg);
    }
    await initFetchData();
}

const addContext = () => {
    vo.rows.push({
        id: null,
        title: null,
    })
}

const barrageDel = async (id) => {
    const {code, msg} = await Api.admin.barrageDel({
        id: id
    });
    if (code === 1) Message.success(msg);
    await fetchData();
}
</script>

<template>
    <a-button type="primary" @click="addContext">
        <template #icon>
            <icon-plus/>
        </template>
        新建
    </a-button>

    <a-table
        :loading="loading"
        @page-change="(e) => pagination.current = e"
        :pagination="pagination"
        :data="vo.rows"
        :columns="columns"
        class="flex-grow mt-[20px] w-full">
        <template v-slot:content="{record}">
            <a-textarea
                @blur="success(record)"
                v-model:model-value="record.title"
                auto-size>
            </a-textarea>
        </template>
        <template v-slot:sort="{record}">
            <SequenceAdjustment
                @success="fetchData"
                :api="Api.admin.barrageWeigh"
                :id="record.id">
            </SequenceAdjustment>
        </template>
        <template v-slot:action="{record}">
            <a-popconfirm content="您确认删除吗?" @ok="barrageDel(record.id)">
                <a-link :hoverable="false" status="danger">删除</a-link>
            </a-popconfirm>
        </template>
    </a-table>
</template>

<style scoped lang="scss">

</style>
