<!-- eslint-disable unicorn/prefer-ternary -->
<!-- eslint-disable unicorn/explicit-length-check -->
<script setup lang="ts">
import { throttle } from 'lodash-es'

import { studentService } from '#/api/service/org/student'
import { spStaffService } from '#/api/service/sp/sp-staff'
import { mj_form_money, mj_form_radio_group } from '#/components/mj/mj-table'
import { rangeValidator } from '#/components/mj/mj-table/fmt'
import { user_type_sp_staff } from '#/hooks/user'
import hud from '#/utils/hud'
import obj from '#/utils/obj'

defineOptions({ name: 'UserRenew' })
const props = withDefaults(
  defineProps<{
    modelValue?: boolean
    user: {
      id: any
      name: any
      type: any
    }
  }>(),
  {
    modelValue: false,
  },
)
const emits = defineEmits(['update:modelValue', 'success'])

const type_month = 1
const type_year = 2
const typeOptions = ref([
  {
    label: '月',
    value: type_month,
  },
  {
    label: '年',
    value: type_year,
  },
])
const typeMap = obj.options2map(typeOptions.value)

const show = computed({
  get() {
    return props.modelValue
  },
  async set(newVal) {
    emits('update:modelValue', newVal)
    const defaultData = {
      type: type_month,
    }
    if (newVal) {
      formRef.value?.setData(defaultData)
    }
  },
})

const title = computed(() => {
  return `【${props.user?.name}】续费`
})

const formRef = ref()
const form = {
  titleWidth: 100,
  items: [
    {
      required: true,
      span: 24,
      field: 'type',
      title: '单位',
      itemRender: {
        name: mj_form_radio_group,
        options: typeOptions,
      },
    },
    {
      required: true,
      span: 24,
      validator: rangeValidator(1, 12),
      message: '请输入1~12之间的整数',
      field: 'size',
      title: '数量',
      itemRender: {
        name: 'VxeNumberInput',
      },
    },
    {
      required: true,
      message: '请选择单位和输入数量',
      span: 24,
      field: 'fee',
      title: '费用',
      itemRender: {
        name: mj_form_money,
        props: {
          disabled: true,
          placeholder: '',
          showPrefix: false,
        },
      },
    },
  ],
} as any

const buildParams = () => {
  const params = { userId: props.user.id } as any
  const data = formRef.value?.getData()
  if (!data) return
  if (data.type === type_month) {
    params.months = data.size
  } else {
    params.years = data.size
  }
  return params
}

const calFee = throttle(async () => {
  const data = formRef.value?.getData()
  if (!data) return
  if (!data.type || !data.size) {
    data.fee = ''
    return
  }
  let res: any
  if (props.user.type === user_type_sp_staff) {
    res = await spStaffService.calRenewFee(buildParams())
  } else {
    res = await studentService.calRenewFee(buildParams())
  }
  data.fee = res.amount
}, 500)

watch(
  [() => formRef.value?.getData()?.type, () => formRef.value?.getData()?.size],
  calFee,
  { immediate: true },
)

// 编辑表单事件
const submit = async () => {
  const data = formRef.value?.getData()
  const coin = hud.highlight(`${data.fee}乐贝`)
  const name = hud.highlight(props.user.name)
  const time = hud.highlight(`${data.size}个${typeMap[data.type]}`)
  hud.confirmLoad(`扣除${coin}为${name}续费${time}？`, {
    task: async () => {
      if (props.user.type === user_type_sp_staff) {
        await spStaffService.renew(buildParams())
      } else {
        await studentService.renew(buildParams())
      }
      emits('success')
      emits('update:modelValue', false)
    },
    option: '续费',
    hideSuccess: false,
  })
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title,
    }"
  >
    <mj-form ref="formRef" :options="form" @submit="submit" />
  </mj-modal>
</template>

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