<template>
    <view class="p-20 text-sm text-main">
        <uv-text v-if="isScoreLocked&&false" type="error" :text="MxConfig.scoreLockedTips"/>
        <uv-text v-if="isScoreUnlocked&&false" type="error" :text="MxConfig.scoreRuleTips"/>
        <course-selector/>
        <uv-line margin="15px 0 0 0"/>
        <uv-input v-model="model.score" :disabled="isScoreLocked" placeholder="请输入您的分数"
                  v-bind="inputCommon">
            <template #prefix>您的分数：</template>
        </uv-input>
        <uv-input v-if="false" v-model="model.rank.lowestRank" disabled v-bind="inputCommon">
            <template #prefix>匹配位次：</template>
        </uv-input>
        <uv-input v-model="model.seatInput" placeholder="输入成绩单位次" v-bind="inputCommon">
            <template #prefix>填写位次：</template>
        </uv-input>
        <view class="font-[PingFang] text-content text-2xs mt-20">
            <uv-icon name="info-circle" class="mr3" style="display: inline-block"/>
            已根据最新位次表获取分数的最低位次，您也可以修改为成绩单上的位次
            <template v-if="model.rank&&isScoreLocked">，位次区间[{{
                    model.rank.highestRank
                }}~{{ model.rank.lowestRank }}]
            </template>
            。
            <text class="underline text-primary" @click="goQuerySegment">查看位次</text>
        </view>
    </view>
</template>

<script setup>
import CourseSelector from "@/pagesOther/pages/vhs/index/components/course-selector.vue";
import debounce from "@/uni_modules/uv-ui-tools/libs/function/debounce";
import {getRankByScore} from "@/api/modules/vhs";
import {useInjectVoluntaryData} from "@/pagesOther/hooks/useVoluntaryDataInjection";
import {useTransferPage} from "@/hooks/useTransferPage";
import {useUserStore} from "@/store/userStore";
import {routes} from "@/common/routes";

const props = defineProps({
    model: {
        type: Object,
        default: () => ({})
    }
})
const inputCommon = {
    type: 'number',
    border: 'bottom',
    fontSize: '18px',
    customStyle: {height: '30px'}
}

const {isScoreLocked, isScoreUnlocked} = storeToRefs(useUserStore())
const {transferTo} = useTransferPage()
const {validate, voluntaryData} = useInjectVoluntaryData()

const goQuerySegment = () => {
    transferTo(routes.pageRanking)
}

const setRankByScore = async () => {
    const {firstSubject, score} = props.model
    if (!score) {
        props.model.seatInput = ''
        props.model.rank = {}
        return
    }

    const payload = {mode: firstSubject, scoreRank: score}
    const res = await getRankByScore(payload)
    // 2次校验，防止串分
    if (payload.scoreRank != props.model.score) return
    props.model.rank = res.data
    const {lowestRank, highestRank} = res.data
    const {seatInput} = props.model
    if (seatInput >= highestRank && seatInput <= lowestRank) return
    props.model.seatInput = lowestRank
}

const validateForm = async function () {
    const {score, seatInput, rank} = props.model
    // score validate
    await validate(score)
    // seat validate
    let error = ''
    if (!seatInput) error = '请输入位次'
    else if (seatInput && !/^[1-9]\d*$/.test(seatInput)) error = '请输入合法的位次'
    else if (!isScoreUnlocked.value && (seatInput < rank.highestRank || seatInput > rank.lowestRank)) error = `位次必须在[${rank.highestRank}~${rank.lowestRank}]之间`
    if (error) {
        uni.$ie.showError(error)
        return Promise.reject(error)
    }
}

watch([() => props.model.firstSubject, () => props.model.score * 1], async ([firstSubject, score]) => {
    // console.log('watch firstSubject and score', firstSubject, score)
    if (/*!firstSubject || */!score) return // 单招没有firstSubject
    // error input fix, when props.model.score assigned, watch will be triggered again.
    if (score > voluntaryData.value.maxScore) return props.model.score = voluntaryData.value.maxScore
    else if (score < 0) return props.model.score = 0
    // silence validation
    await validate(score, true)

    debounce(setRankByScore)
})

defineExpose({validate: validateForm})
</script>

<style scoped>

</style>