<script lang="ts" setup>
import { ref } from 'vue';
import { useVbenDrawer } from '@vben/common-ui';
import { VbenIcon } from '../../../../../../packages/@core/ui-kit/shadcn-ui';
import { Timeline } from 'ant-design-vue';
import { copywritingscript,copyonlinescript } from '#/api/core/scripts';
import type { scriptsRecord } from '#/model/type';
const data = ref();
const timestamp = ref(0);
const title = ref('');
const end = ref(false);
const pendinglabel = ref('脚本运行中...');
const stepList = ref<scriptsRecord[]>([]);
const [Drawer, drawerApi] = useVbenDrawer({
    onCancel() {
        drawerApi.close();
    },
    onConfirm() {
        drawerApi.close();
    },
    onOpenChange(open: boolean) {
        if (open) {
            data.value = drawerApi.getData<Record<string, any>>();
            stepList.value = [];
            end.value = false;
            title.value = `脚本执行详情 - ${data.value.scriptName || ''}`;
            drawerApi.setState({
                title: title.value,
            });
            pendinglabel.value = '脚本运行中...';
            // 使用 nextTick 确保状态重置后再执行脚本
            // 重置计时器
            timestamp.value = Date.now();
            const timer = setInterval(() => {
                const elapsed = Math.floor((Date.now() - timestamp.value) / 1000);
                drawerApi.setState({
                    title: `${title.value} - 运行时间: ${elapsed}秒`,
                });
                if (end.value) {
                    clearInterval(timer);
                }
            }, 1000);
            setTimeout(() => {
                switch (data.value.scriptInstanceId) {
                    case 1:
                        console.log('running script copywriting');
                        runningStep(copywritingscript, stepList.value.length);
                        break;
                    case 2:
                        console.log('running script copyonline');
                        runningStep(copyonlinescript, stepList.value.length);
                        break;
                }
            }, 0);
        }
        // switch (data.value.scriptInstanceId) {
        //     case 1:
        //         // load data or do something
        //         console.log('running script copywriting');
        //         runningStep(copywritingscript, stepList.value.length);
        //         break;
        // }
    },

});

function runningStep(func: Function, step: number) {
    func({ step: step }).then((res: scriptsRecord) => {
        if (res.step != 1) {
            stepList.value?.push({
                step: res.step - 1,
                label: pendinglabel.value,
                tips: res.tips || [],
                code: res.code,
            });
            if (res.code !== 0) {
                // 出错，结束
                end.value = true;
                pendinglabel.value = '';
                stepList.value = stepList.value.map((item, index) => ({
                    ...item,
                    color: index === stepList.value.length - 1 ? 'red' : 'blue'
                }));
                return;
            }
        }
        if (res.step !== -1) {
            // 合并当前步骤的tips到上一个record
            stepList.value = stepList.value.map((item, index) => ({
                ...item,
                color: index === stepList.value.length ? 'gray' : 'blue'
            }));
            pendinglabel.value = res.label;
            runningStep(func, res.step);
        } else {
            stepList.value = stepList.value.map((item, index) => ({
                ...item,
                color: 'blue'
            }));
            end.value = true;
            pendinglabel.value = '';
        }
    });
}


</script>
<template>
    <Drawer>
        <Timeline :pending="pendinglabel">
            <Timeline.Item v-for="item in stepList" :key="item.step" :pending="false" :color="item.color || 'blue'">
                <template #dot>
                    <VbenIcon :icon="item.code == 0?'system-uicons:check-circle':'system-uicons:cross-circle'" />
                </template>
                <span>{{ item.label }}</span>
                <div>
                    <ul class="list-disc ml-5">
                        <li v-for="tip in item.tips">{{ tip }}</li>
                    </ul>
                </div>
            </Timeline.Item>
            <Timeline.Item v-if="end" color="blue">
                <template #dot>
                    <VbenIcon icon="system-uicons:check-circle" />
                </template>
                completed
            </Timeline.Item>
            <template #pendingDot>
                <VbenIcon icon="svg-spinners:12-dots-scale-rotate" />
            </template>
        </Timeline>
    </Drawer>
</template>
