<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 {watch} from 'vue';
import MxConfig from "@/common/mxConfig";
import {createPropDefine} from "@/utils";
import {useUserStore} from "@/hooks/useUserStore";
import {useInjectTransfer} from "@/hooks/useTransfer";
import {useInjectVoluntaryData} from "@/hooks/useVoluntaryDataInjection";
import CourseSelector from "@/pages/voluntary/index/components/course-selector.vue";
import debounce from "@/uni_modules/uv-ui-tools/libs/function/debounce";
import {useCacheStore} from "@/hooks/useCacheStore";
import {getRankByScore} from "@/api/webApi/volunteer";
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";

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

const {isScoreLocked, isScoreUnlocked} = useUserStore()
const {transferTo} = useInjectTransfer()
const {validate, voluntaryData} = useInjectVoluntaryData()
const {dispatchCache} = useCacheStore()

const goQuerySegment = () => {
    transferTo('/pages/career/query-segment/query-segment')
}

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 dispatchCache(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) {
        toast(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>