import { onUnmounted, reactive, ref, shallowRef, provide } from 'vue'
import type { DrawingFormType } from '@/api/drawing'
import { drawing, drawingDelete, drawingDetail } from '@/api/drawing'
import { useUserStore } from '@/stores/user'
import usePolling from '@/hooks/usePolling'
import { onUnload } from '@dcloudio/uni-app'
import { isNewDay } from '@/utils/validate'
import { DRAW_LIMIT_KEY } from '@/enums/constantEnums'

export const useIndexEffect = () => {
    const userStore = useUserStore()

    // pageIndex
    const pageIndex = ref<number>(0)
    // 消耗绘画次数
    const consumptionCount = ref<number>(0)

    // 绘画数据
    const drawForm: DrawingFormType = reactive({
        prompt: '',
        action: 'generate',
        imageBase: '',
        other: '',
        imageId: '',
        model: '',
        scale: '1:1',
        no_content: '',
        version: '',
        style: 'default',
        engine: '',
        quality: 'standard'
    })
    // 是否生成中
    const isReceiving = ref<boolean>(false)
    // 记录ID（用于请求轮询的ID
    const recordIds: any = ref<number[]>([])

    // 绘画列表即索引
    const taskIndex = ref<number | string>(3)
    const taskLists = [
        { name: '全部', value: '' },
        { name: '绘画完成', value: 3 },
        { name: '进行中', value: 1 },
        { name: '绘画失败', value: 2 }
    ]

    // 任务记录
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const paging: any = shallowRef(null)
    const dataList = ref<any>([])

    /**
     *  删除记录
     *  ids: { number[] } : 删除的id数组
     **/
    const deleteDrawing = async (ids: number[]) => {
        try {
            const res = await uni.showModal({
                title: '温馨提示',
                content: '是否确认删除当前绘画?',
                confirmColor: '#FFC94D'
            })
            if (res.confirm) {
                await drawingDelete(ids)
                getRecordLists()
            }
        } catch (error) {
            console.log('删除失败绘画记录', error)
        }
    }

    /**
     *  获取分页列表
     *  **/
    const getRecordLists = async () => {
        paging?.value?.reload()
    }

    /**
     *  获取生成中的ids数组
     *  **/
    const getDrawingIds = (arr: any[]) => {
        return arr
            .filter((item: any) => item.status === 1)
            .map((item: any) => item.id)
    }

    /**
     *  设置分页数据
     *  pager: { any[] } : 分页列表
     *  getLists: { func } : 获取分页列表函数
     **/
    const setTaskRecordFunc = async (data: any) => {
        end()
        paging.value = data.reload
        dataList.value = data.lists
        recordIds.value = getDrawingIds(data.lists)
        setTimeout(() => {
            if (recordIds.value.length) { start() }
        }, 100)
    }

    /**
     *  使用获取详情（轮训请求
     **/
    const useDetails = () => {
        const check = async () => {
            try {
                const data = await drawingDetail(recordIds.value)
                const res = data.filter((item: any) => {
                    return item.status == 3 || item.status == 2
                })
                if (res.length) {
                    end()
                    endCallback()
                }

                return data
            } catch (error: any) {
                end()
                console.log('获取详情失败=>', error)
            }
        }
        const endCallback = async () => {
            await getRecordLists()
            await userStore.getUser()
        }
        const { start, end, result } = usePolling(check, {
            totalTime: 480 * 1000,
            time: 2000,
            count: 96,
            callback: endCallback
        })

        return {
            start,
            end,
            result
        }
    }
    const { start, end } = useDetails()

    onUnmounted(() => {
        end()
    })

    onUnload(() => {
        pageIndex.value = 0
        end()
    })

    /**
     *  绘制请求
     *  options: { drawing } : 绘制参数
     *  options: { isClear } : 是否清空绘制参数
     **/
    const drawingHandler = async (options: {
        drawing: DrawingFormType
        isClear: boolean
    }) => {
        if (!userStore.isLogin) {
            return uni.navigateTo({ url: '/pages/login/login' })
        }
        if (!options.drawing.prompt) return uni.$u.toast('请输入绘画描述！')
        if (
            userStore.userInfo.drawLimit &&
            isNewDay(true, DRAW_LIMIT_KEY)
        ) {
            const res = await uni.showModal({
                title: '绘画上限提示',
                content: '已超过会员绘画上限次数，继续绘画将会消耗账户的绘画余额',
                confirmText: '继续',
                cancelText: '关闭'
            })
            if (res.cancel) return
        }
        uni.showLoading({ title: '请求中' })

        // 改为生成中
        taskIndex.value = ''
        isReceiving.value = true
        dataList.value.unshift({ status: 1 })
        paging?.value.complete(dataList.value)

        try {
            end()
            await drawing(options.drawing)
            // 重置参数
            if (options.isClear) {
                drawForm.prompt = ''
                drawForm.imageBase = ''
                drawForm.no_content = ''
                drawForm.other = ''
            }
            await getRecordLists()
            pageIndex.value = 1
        } catch (error) {
            dataList.value.splice(0, 1)
            paging?.value.complete(dataList.value)
            if (error === '绘画余额不足!') {
                const res = await uni.showModal({
                    title: '绘画余额不足',
                    content: '绘画余额不足，请前往充值',
                    confirmText: '前往充值'
                })
                if (res.confirm) {
                    if (userStore.isLogin) {
                        uni.navigateTo({ url: '/packages/pages/recharge/recharge' })
                    } else {
                        uni.navigateTo({ url: '/pages/login/login' })
                    }
                }
                return
            }
            console.log('绘制失败=>', error)
            await getRecordLists()
        } finally {
            uni.hideLoading()
            isReceiving.value = false
        }
    }

    provide('drawForm', drawForm)
    provide('pageIndex', pageIndex)
    provide('consumptionCount', consumptionCount)
    provide('isReceiving', isReceiving)
    provide('taskIndex', taskIndex)
    provide('taskLists', taskLists)
    provide('deleteDrawing', deleteDrawing)
    provide('setTaskRecordFunc', setTaskRecordFunc)
    provide('drawingHandler', drawingHandler)

    return {
        pageIndex,
        isReceiving,
        taskIndex,
        taskLists,
        deleteDrawing,
        setTaskRecordFunc,
        useDetails,
        drawingHandler
    }
}
