<template>
    <el-dialog class="ba-operate-dialog" :close-on-click-modal="false" :model-value="baTable.form.operate == 'Add'" @close="baTable.toggleForm">
        <template #header>
            <div class="title" v-drag="['.ba-operate-dialog', '.el-dialog__header']" v-zoom="'.ba-operate-dialog'">
                {{ baTable.form.operate ? t(baTable.form.operate) : '' }}
            </div>
        </template>

        <el-scrollbar class="ba-table-form-scrollbar">
            <div
                class="ba-operate-form"
                :class="'ba-' + baTable.form.operate + '-form'"
                :style="config.layout.shrink ? '' : 'width: calc(100% - ' + baTable.form.labelWidth! / 2 + 'px)'"
            >
                <el-form
                    v-if="!baTable.form.loading"
                    ref="formRef"
                    :model="baTable.form.items"
                    :label-position="config.layout.shrink ? 'top' : 'right'"
                    :label-width="baTable.form.labelWidth + 'px'"
                    :rules="rules"
                    @keyup.enter="baTable.onSubmit(formRef)"
                >
                    <FormItem
                        type="remoteSelect"
                        prop="user_asset_id"
                        :label="t('mall.pointsLog.user_asset')"
                        v-model="baTable.form.items!.user_asset_id"
                        :placeholder="t('Click select')"
                        :input-attr="{
                            pk: 'id',
                            field: 'username',
                            remoteUrl: '/admin/mall.UserAsset/select',
                            onChange: getUserAssetInfo,
                        }"
                    />
                    <el-form-item :label="t('mall.pointsLog.playx_user_id')">
                        <el-input v-model="state.userAsset.playx_user_id" disabled />
                    </el-form-item>
                    <el-form-item :label="t('mall.pointsLog.username')">
                        <el-input v-model="state.userAsset.username" disabled />
                    </el-form-item>
                    <el-form-item :label="t('mall.pointsLog.current_points')">
                        <el-input v-model="state.userAsset.available_points" disabled />
                    </el-form-item>
                    <el-form-item prop="score_value" :label="t('mall.pointsLog.score_value')">
                        <el-input-number
                            v-model="baTable.form.items!.score_value"
                            :precision="0"
                            :step="1"
                            controls-position="right"
                            style="width: 100%"
                            @change="changeScore"
                        />
                    </el-form-item>
                    <el-form-item :label="t('mall.pointsLog.after')">
                        <el-input v-model="state.after" disabled />
                    </el-form-item>
                    <el-form-item :label="t('mall.pointsLog.memo')">
                        <el-input v-model="state.memo" type="textarea" disabled />
                    </el-form-item>
                </el-form>
            </div>
        </el-scrollbar>

        <template #footer>
            <div :style="'width: calc(100% - ' + baTable.form.labelWidth! / 1.8 + 'px)'">
                <el-button @click="baTable.toggleForm('')">{{ t('Cancel') }}</el-button>
                <el-button v-blur :loading="baTable.form.submitLoading" type="primary" @click="baTable.onSubmit(formRef)">
                    {{ t('Save') }}
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import type { FormItemRule } from 'element-plus'
import { inject, reactive, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { getUserAsset } from '/@/api/backend/mall/pointsLog'
import FormItem from '/@/components/formItem/index.vue'
import { useConfig } from '/@/stores/config'
import type baTableClass from '/@/utils/baTable'
import { buildValidatorData } from '/@/utils/validate'

interface UserAssetInfo {
    id?: number
    username?: string
    playx_user_id?: string
    available_points?: number
}

const config = useConfig()
const { t } = useI18n()
const injectedBaTable = inject<baTableClass>('baTable')
if (!injectedBaTable) {
    throw new Error('baTable is not provided')
}
const baTable = injectedBaTable
const formRef = useTemplateRef('formRef')

const state = reactive<{
    userAsset: UserAssetInfo
    after: number
    memo: string
}>({
    userAsset: {},
    after: 0,
    memo: '',
})

const validateScoreValue: FormItemRule['validator'] = (_rule, value, callback) => {
    if (typeof value !== 'number' || !Number.isInteger(value) || value === 0) {
        callback(new Error(t('mall.pointsLog.non_zero_integer_required')))
        return
    }
    if ((state.userAsset.available_points ?? 0) + value < 0) {
        callback(new Error(t('mall.pointsLog.insufficient_available_points')))
        return
    }
    callback()
}

const rules: Partial<Record<string, FormItemRule[]>> = reactive({
    user_asset_id: [buildValidatorData({ name: 'required', title: t('mall.pointsLog.user_asset') })],
    score_value: [
        {
            validator: validateScoreValue,
            trigger: 'blur',
        },
    ],
})

const changeScore = (value: number | undefined) => {
    const scoreValue = value ?? 0
    const availablePoints = state.userAsset.available_points ?? 0
    state.after = availablePoints + scoreValue
    if (scoreValue > 0) {
        state.memo = t('mall.pointsLog.admin_add_memo', { value: Math.abs(scoreValue) })
    } else if (scoreValue < 0) {
        state.memo = t('mall.pointsLog.admin_deduct_memo', { value: Math.abs(scoreValue) })
    } else {
        state.memo = ''
    }
}

const getUserAssetInfo = () => {
    const userAssetId = baTable.form.items!.user_asset_id
    if ((typeof userAssetId !== 'string' && typeof userAssetId !== 'number') || userAssetId === '') {
        state.userAsset = {}
        state.after = 0
        state.memo = ''
        return
    }

    getUserAsset(userAssetId).then((response) => {
        state.userAsset = response.data.userAsset
        changeScore(baTable.form.items!.score_value)
    })
}

watch(
    () => baTable.form.operate,
    (operate) => {
        if (operate == 'Add') {
            getUserAssetInfo()
        }
    }
)
</script>

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