<script setup>
import {computed, h, reactive} from 'vue';
import Filter from "../../../../components/Filter/index.vue";
import TooltipTag from "../../../../components/TooltipTag/index.vue";
import useTableQuery from "../../../../hooks/useTableQuery.js";
import Api from "../../../../api/index.js";
import {toPath} from "../../../../utils/index.js";
import {Message, Modal} from "@arco-design/web-vue";
import {usePayTask} from "../../../../hooks/usePayTask.js";
import SaveTemplate from "./components/SaveTemplate.vue";
import TaskTemplate from "./components/TaskTemplate.vue";

const columns = [
    {
        title: '任务编号',
        dataIndex: 'code',
    },
    {
        title: '任务名称',
        dataIndex: 'goods_name',
    },
    {
        title: '发布渠道',
        dataIndex: 'name',
    },
    {
        title: '创建时间',
        dataIndex: 'createtime',
    },
    {
        title: '当前状态',
        dataIndex: 'status',
        slotName: 'status',
    },
    {
        title: '子任务进度',
        dataIndex: 'end_ratio',
    },
    {
        title: '消耗金额',
        dataIndex: 'money',
        slotName: 'money',
    },
    {
        title: '是否开始',
        dataIndex: 'start',
        slotName: 'start',
    },
    {
        title: '操作',
        dataIndex: 'action',
        slotName: 'action',
        width: 200,
    },
    {
        title: '',
        dataIndex: 'exp',
        slotName: 'exp'
    },
];
const FilterConfig = computed(() => [
    {
        key: 'code',
        type: 'input',
        label: '任务编号',
        placeholder: '请输入集合编号'
    },
    {
        key: 'name',
        type: 'input',
        label: '任务名称',
        placeholder: '请输入集合名称'
    },
    {
        key: 'platform',
        type: 'select',
        label: '任务渠道',
        placeholder: '全部',
        api: async () => Api.merchant.getTaskPlatformList(),
    },
    {
        key: 'status',
        type: 'select',
        label: '任务状态',
        placeholder: '全部',
        api: async () => Api.merchant.getTaskStatusList(),
    },
    {
        key: 'datetime',
        start: 'start_time',
        end: 'end_time',
        type: 'datetime',
        label: '创建时间',
        placeholder: '全部',
    },
]);
const vo = reactive({
    page: '',
    rows: [],
    total: 0,
});
const po = reactive({
    wd: null,
});

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

const {open: openPayTask} = usePayTask();

const startTask = async (_value, record) => {
    const {status, id} = record;

    if (status === 2) {
        Modal.error({
            title: '请等待子任务审核通过',
            content: '检测到子任务素材尚未提交或者尚未审核通过，请等待子任务素材审核通过后，再次点击开始任务',
            okText: '查看子任务',
            onOk: () => {
                viewMiniTask(record);
            }
        });
        return;
    }

    const showMessageAndFetch = async (msg) => {
        Message.success(msg);
        await fetchData();
    };

    if (status === -2 || status === 4) {
        const {msg} = await Api.merchant.endTask(id);
        await showMessageAndFetch(msg);
    } else {
        const {data} = await Api.merchant.startTask({id});
        openPayTask({
            props: {payInfo: data},
            success: async () => {
                const {msg} = await Api.merchant.moneyToTask(id);
                await showMessageAndFetch(msg);
            },
        });
    }
};

const stopTask = async (id) => {
    Modal.error({
        width: 460,
        title: '确认终止任务',
        content: h('div', {}, [
            h('div', {}, '终止任务后，后续达人将无法接单，但不影响已经接单的达人'),
            h('div', {class: 'text-[#4E5969] text-[14px] mt-[4px]'}, '*请商家及时处理已经被接单的子任务，处理完毕后，剩余任务金额将返款至您钱包')
        ]),
        okText: '确认终止',
        okButtonProps: {status: "danger"},
        hideCancel: false,
        onOk: async () => {
            const {msg} = await Api.merchant.stopTask(id);
            Message.success(msg);
            await fetchData();
        }
    })
}

const viewMiniTask = (record) => {
    if (record.status === 0 || record.status === 1 || record.status === -1) {
        Modal.error({
            title: '无法查看子任务',
            content: '检测到任务尚未审核通过，请等待任务审核通过后，再点击查看子任务'
        });
    } else {
        toPath('/home/task-center/look-min-task', {id: record.id})
    }
}
</script>

<template>
    <a-card>
        <!-- 悬赏任务 -->
        <Filter v-model:from="po" :config="FilterConfig" @search="initFetchData"></Filter>

        <div class="flex gap-[16px] mb-[20px]">
            <a-button type="primary" @click="toPath('/home/task-center/new-task')">
                <template #icon>
                    <icon-plus/>
                </template>
                新建任务
            </a-button>
            <task-template @success="initFetchData">
                <a-button>
                    <template #icon>
                        <icon-plus/>
                    </template>
                    从模板快速创建
                </a-button>
            </task-template>
        </div>

        <div class="mt-[20px] flex-grow">
            <a-table
                class="h-full"
                :columns="columns"
                :data="vo.rows"
                :loading="loading"
                @page-change="(e) => pagination.current = e"
                :pagination="pagination">
                <template v-slot:status="{record}">
                    <TooltipTag v-if="record.status === 0" color="cyan" :content="record.check_remark">待完善
                    </TooltipTag>
                    <TooltipTag v-if="record.status === 1" color="red" :content="record.check_remark">审核中
                    </TooltipTag>
                    <TooltipTag v-if="record.status === -1" color="red" :content="record.check_remark">未通过
                    </TooltipTag>
                    <TooltipTag v-if="record.status === 2" color="magenta" :content="record.check_remark">请完善子任务
                    </TooltipTag>
                    <TooltipTag v-if="record.status === 3" color="magenta" :content="record.check_remark">待付款
                    </TooltipTag>
                    <TooltipTag v-if="record.status === 4" color="blue" :content="record.check_remark">投放中
                    </TooltipTag>
                    <TooltipTag v-if="record.status === -2" color="orangered" :content="record.check_remark">暂停中
                    </TooltipTag>
                    <TooltipTag v-if="record.status === -3" color="purple" :content="record.check_remark">终止
                    </TooltipTag>
                    <TooltipTag v-if="record.status === 5" color="green" :content="record.check_remark">已完成
                    </TooltipTag>
                </template>
                <template v-slot:start="{record}">
                    <a-switch
                        @change="startTask($event, record)"
                        :disabled="record.status !== -2 && record.status !== 3 && record.status !== 4 && record.status !== 2"
                        :model-value="record.status === 4">
                    </a-switch>
                </template>
                <template v-slot:money="{record}">
                    <div class="flex flex-col gap-[8px]">
                        <div>{{ record.end_money.toFixed(2) }} / {{ record.total.toFixed(2) }}（元）</div>
                        <a-progress
                            :percent="record.end_money/record.total"
                            :show-text="false">
                        </a-progress>
                    </div>
                </template>
                <template v-slot:action="{record}">
                    <div class="flex gap-[16px]">
                        <a-link
                            :hoverable="false"
                            @click="toPath('/home/task-center/new-task', {id: record.id})">
                            编辑
                        </a-link>
                        <a-link :hoverable="false"
                                @click="viewMiniTask(record)">
                            查看子任务
                        </a-link>
                        <a-link @click="stopTask(record.id)" :disabled="!(record.status === 4 || record.status === -2)"
                                :hoverable="false"
                                status="danger">
                            终止
                        </a-link>
                    </div>
                </template>
                <template v-slot:exp="{record}">
                    <a-trigger trigger="click" :unmount-on-close="false">
                        <a-link :hoverable="false">更多
                            <icon-down/>
                        </a-link>
                        <template #content>
                            <div class="demo-basic">
                                <SaveTemplate :id="record.id">
                                    <a-button
                                        type="text"
                                        :disabled="record.status===0 || record.status===1 || record.status===-1">
                                        存为模板
                                    </a-button>
                                </SaveTemplate>
                            </div>
                        </template>
                    </a-trigger>
                </template>
            </a-table>
        </div>
    </a-card>
</template>

<style scoped>

</style>
