<template>
    <ie-page>
        <z-paging ref="paging" v-model="list" bg-color="#F6F8FA" safe-area-inset-bottom :scrollable="!isSorting"
                  :refresher-enabled="!isSorting" @query="handleQuery">
            <template #top>
                <ie-navbar title="志愿表"/>
            </template>
            <view class="mt-20 bg-warning-light p-28 text-23 leading-38 text-fore-title">
                <text class="font-bold">说明：</text>
                目前志愿计划为2025年，排序前两个为第一、二志愿，可通过修改排序重新选择第一、二志愿
            </view>
            <view class="p-28 flex flex-col gap-28">
                <voluntary-item v-for="(item, i) in list" :key="i" :data="item" :index="i" @more="showActions(item)"
                                @error="handleError" @deleted="handleDeleted"/>
            </view>
        </z-paging>
        <ie-safe-toolbar :height="84" :shadow="false">
            <view class="px-30 py-16">
                <ie-button @click="handleAdd">添加志愿</ie-button>
            </view>
        </ie-safe-toolbar>
        <uv-action-sheet ref="actionSheet" :actions="moreActions" safe-area-inset-bottom close-on-click-overlay
                         cancel-text="取消" @select="handleActionSelect"/>
    </ie-page>
</template>

<script setup lang="ts">
import {SelectedUniversityMajor, VoluntaryRecord} from "@/types/voluntary";
import VoluntaryItem from "@/pagesOther/pages/voluntary/list/components/voluntary-item.vue";
import {VOLUNTARY_SORTING} from "@/types/injectionSymbols";
import {
    addVoluntary,
    getVoluntaryList,
    removeVoluntaryByUniversity,
    sortVoluntaryByUniversity
} from "@/api/modules/voluntary";
import UvActionSheet from "@/uni_modules/uv-action-sheet/components/uv-action-sheet/uv-action-sheet.vue";
import {useTransferPage} from "@/hooks/useTransferPage";
import {UniversityPickerPageOptions} from "@/types/transfer";
import {routes} from "@/common/routes";

interface ActionItem {
    id: string;
    name: string;
    icon?: string;
    color?: string;
    iconColor?: string;
    disabled?: boolean;
}

const {transferTo} = useTransferPage()
const list = ref<VoluntaryRecord[]>([])
const paging = ref<ZPagingInstance>()
const isSorting = ref<boolean>(false)
const actionSheet = ref<InstanceType<typeof UvActionSheet>>()
const actionRecord = ref<VoluntaryRecord>()
const moreActions = computed<ActionItem[]>(() => {
    const records = list.value
    const current = actionRecord.value
    const idx = current ? records.indexOf(current) : -1
    const enableTop = records.length > 1 && idx > 0
    const enableUp = records.length > 1 && idx > 0
    const enableDown = records.length > 1 && idx < records.length - 1
    return [{
        id: 'top',
        name: '置顶',
        icon: 'pushpin-fill',
        color: 'var(--primary-color)',
        iconColor: enableTop ? 'primary' : 'info',
        disabled: !enableTop
    }, {
        id: 'up',
        name: '上移',
        icon: 'arrow-upward',
        iconColor: enableUp ? '' : 'info',
        disabled: !enableUp
    }, {
        id: 'down',
        name: '下移',
        icon: 'arrow-downward',
        iconColor: enableDown ? '' : 'info',
        disabled: !enableDown
    }, {
        id: 'delete',
        name: '删除',
        icon: 'trash',
        color: 'var(--danger)',
        iconColor: 'error'
    }]
})

const handleQuery = () => {
    getVoluntaryList().then(res => {
        paging.value?.completeByNoMore(res.data, true)
    }).catch(e => paging.value?.completeByError(e))
}

const showActions = (record: VoluntaryRecord) => {
    actionRecord.value = record
    actionSheet.value?.open()
}

const handleActionSelect = async (e: ActionItem) => {
    const record = actionRecord.value
    const recordList = list.value
    if (!record) return
    const idx = recordList.findIndex(r => r == record)
    if (['top', 'up', 'down'].includes(e.id)) {
        try {
            switch (e.id) {
                case 'top':
                    if (idx > 0) {
                        recordList.splice(idx, 1)
                        recordList.unshift(record)
                        await sortVoluntaryByUniversity(recordList.map(r => r.universityId))
                        uni.$ie.showSuccess('保存成功')
                    }
                    break;
                case 'up':
                    if (idx > 0) {
                        recordList.splice(idx, 1)
                        recordList.splice(idx - 1, 0, record)
                        await sortVoluntaryByUniversity(recordList.map(r => r.universityId))
                        uni.$ie.showSuccess('保存成功')
                    }
                    break;
                case 'down':
                    if (idx < recordList.length - 1) {
                        recordList.splice(idx, 1)
                        recordList.splice(idx + 1, 0, record)
                        await sortVoluntaryByUniversity(recordList.map(r => r.universityId))
                        uni.$ie.showSuccess('保存成功')
                    }
                    break;
            }
        } catch (e) {
            console.log('action ex', e)
            paging.value?.reload() // 发生异常时，重新加载列表
        }
    } else if (e.id === 'delete') {
        await uni.$ie.showConfirm({
            title: '志愿删除提醒',
            content: `删除'${record.universityName}'，将同时删除该院校下所有意向专业。\n确认删除？！`
        })
        await removeVoluntaryByUniversity(record.universityId)
        uni.$ie.showSuccess('删除成功')
        paging.value?.reload()
    } else {
        throw new Error('Unsupported action id: ' + e.id)
    }
}

const handleError = () => {
    // 内部异常，重新取数
    paging.value?.reload()
}

const handleDeleted = () => {
    paging.value?.reload()
}

const handleAdd = async () => {
    const option: UniversityPickerPageOptions = {
        title: '选择你的意向院校专业',
        fromVoluntary: true
    }
    const picked = await transferTo(routes.targetPicker, {data: option})
    if (!picked) return
    await addVoluntary(picked)
    uni.$ie.showSuccess('保存成功')
    paging.value?.reload()
}

provide(VOLUNTARY_SORTING, isSorting)
</script>

<style lang="scss"></style>
