<template>
    <uv-popup ref="popup" mode="bottom" round="16" closeable @change="handleChange">
        <view class="fx-row fx-cen-cen h-[50px]">
            <view class="text-lg font-bold text-main">修改分数/批次</view>
        </view>
        <score-form ref="form" :model="modelCopy"/>
        <view class="px-20">
            <uv-line margin="5px 0 0 0"/>
            <uv-cell title="选择批次：" is-link title-style="font-size: 14px; color: #333333;" @click="openBatchList">
                <template #value>
                    <view v-if="batchCopy.batch" class="fx-row items-center text-lg">
                        {{ batchCopy.name }}
                        <uv-tags v-if="batchCopy.recommand" text="重点推荐" size="tiny" type="error" shape="circle"
                                 class="ml-5 pointer-events-none"/>
                    </view>
                </template>
            </uv-cell>
        </view>
        <view class="px-40 h-[60px] fx-row fx-cen-cen">
            <uv-button class="!flex-1" shape="circle" type="primary" text="确认修改" @click="handleConfirm"/>
        </view>
    </uv-popup>
    <uv-action-sheet ref="actionSheet" :actions="formatList" @select="handleBatchSelection"/>
</template>

<script setup>
import {ref, computed, watch} from 'vue';
import _ from 'lodash';
import ScoreForm from "@/pagesOther/pages/voluntary/index/components/score-form.vue";
import {useInjectVoluntaryForm} from "@/pagesOther/pages/voluntary/hooks/useVoluntaryFormInjection";
import {useInjectVoluntaryCart} from "@/pagesOther/pages/voluntary/hooks/useVoluntaryCartInjection";
import {toast} from "@/uni_modules/uv-ui-tools/libs/function";
import {confirmAsync} from "@/utils/uni-helper";

const emits = defineEmits(['change'])

const popup = ref(null)
const form = ref(null)
const show = ref(false)
const actionSheet = ref(null)
const modelCopy = ref({})
const batchCopy = ref({})
const listCopy = ref([])
const {model, batch, batchList, getBatchList} = useInjectVoluntaryForm()
const {selectedList} = useInjectVoluntaryCart()

const formatList = computed(() => {
    return listCopy.value.map(i => ({...i, subname: i.recommand ? '重点推荐' : ''}))
})

const openBatchList = () => {
    actionSheet.value.open()
}
const handleBatchSelection = (item) => {
    batchCopy.value = item
}

const reloadBatchListDebounce = _.debounce(async (score) => {
    // score for debounce validation
    if (score != modelCopy.value.score) return
    const list = await getBatchList(modelCopy.value)
    if (score != modelCopy.value.score) return
    listCopy.value = list
    // validate current batch
    const fired = list.find(b => b.batch == batchCopy.value.batch) || {}
    batchCopy.value = fired
}, 800)

const handleConfirm = async () => {
    await form.value.validate()
    if (!batchCopy.value?.batch) return toast('请选择批次')
    // wait user confirm
    const change = batch.value.batch != batchCopy.value.batch ||
        model.value.score != modelCopy.value.score ||
        model.value.seatInput != modelCopy.value.seatInput
    if (change && selectedList.value.length) await confirmAsync('修改将清空当前志愿表')
    // apply to real models
    _.assign(model.value, modelCopy.value)
    batch.value = batchCopy.value
    batchList.value = listCopy.value
    // popup hidden
    close()
}

const open = () => {
    // make copy from real models
    modelCopy.value = _.clone(model.value)
    batchCopy.value = batch.value
    listCopy.value = [...batchList.value]
    popup.value.open()
}

const close = () => {
    popup.value.close()
}

const handleChange = (e) => show.value = e.show

watch(() => modelCopy.value.score, (score) => {
    if (!score) return
    reloadBatchListDebounce(score)
})

defineExpose({open, close, show})
// export default {
//     name: "score-batch-popup",
//     components: {ScoreStep},
//     props: {
//         show: {
//             type: Boolean,
//             default: false
//         },
//         form: {
//             type: Object,
//             default: () => {
//             }
//         },
//         batch: {
//             type: Number | String,
//             default: ''
//         },
//         batchList: {
//             type: Array,
//             default: () => []
//         }
//     },
//     data() {
//         return {
//             openBatchList: false
//         }
//     },
//     computed: {
//         firedBatch() {
//             return this.batchList.find(b => this.batch == b.batch)
//         },
//         formatBatchList() {
//             return this.batchList.map(b => ({
//                 ...b,
//                 subname: b.recommand ? '重点推荐' : ''
//             }))
//         }
//     },
//     methods: {
//         handleBatchSelection(item) {
//             this.$emit('update:batch', item.batch)
//         },
//         async validate() {
//             await this.$refs.score.validate()
//             if (!this.firedBatch) {
//                 const error = '请选择批次'
//                 this.$message.error(error)
//                 return Promise.reject(error)
//             }
//         },
//         async handleConfirm() {
//             await this.validate()
//             this.$emit('confirm')
//         }
//     }
// }
</script>

<style scoped lang="scss">
::v-deep(.uv-cell) {
    .uv-cell__body {
        padding: 10px 5px;
    }
}
</style>
