<template>
  <v-card class="pa-5 card-box" style="height: 500px;">
    <div class="resume-header mb-3">
      <div class="resume-title">推荐人佣金比例设置</div>
    </div>
    <div class="d-flex flex-column align-center justify-center" style="height: 350px;">
      <CtForm ref="formPageRef" :items="items" style="width: 500px;"></CtForm>
      <v-btn class="buttons" color="primary" @click="handleSubmit">{{ $t('common.submit') }}</v-btn>
    </div>
  </v-card>
</template>

<script setup>
defineOptions({ name: 'public-recruitment-commission'})
import { ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { getHireCommissionRatio, updateHireCommissionRatio } from '@/api/recruit/public/commission'
import Snackbar from '@/plugins/snackbar'

const { t } = useI18n()
const formPageRef = ref()
const items = ref({
  options: [
    {
      type: 'number',
      key: 'rate',
      value: null,
      suffix: '%',
      label: '推荐人佣金比例 *',
      rules: [v => !!v || '请填写推荐人佣金比例']
    }
  ]
})

// 效验数值
const validateNumber = (input) => {
  let number = parseFloat(input)
  if (isNaN(number) || !isFinite(number)) {
    return false
  }
  if (number < 0.01 || number > 100.00) {
    return false
  }
  let parts = input.split('.')
  if (parts.length > 1 && parts[1].length > 2) {
    return false
  }
  return true
}

// 获取佣金比例
const getData = async () => {
  const data = await getHireCommissionRatio()
  if (!data) return
  items.value.options.find(e => e.key === 'rate').value = data.rate
}
getData()

const handleSubmit = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return
  const rate = items.value.options.find(e => e.key === 'rate').value
  if (!validateNumber(rate)) return Snackbar.warning('请填写正确格式的数值')
  await updateHireCommissionRatio(rate)
  Snackbar.success(t('common.submittedSuccessfully'))
  getData()
}
</script>

<style scoped lang="scss">

</style>
