<!-- eslint-disable unicorn/prefer-ternary -->
<script setup lang="ts">
import { bindService } from '#/api/service/user/bind'
import {
  mj_form_input,
  mj_form_radio_group,
  mj_form_text,
} from '#/components/mj/mj-table'
import hud from '#/utils/hud'

defineOptions({ name: 'TransferToSp' })
const props = withDefaults(
  defineProps<{
    childAccount?: any
    modelValue?: boolean
    parentAccount?: any
    simSerialNumber?: any
  }>(),
  {
    parentAccount: undefined,
    childAccount: undefined,
    modelValue: false,
    simSerialNumber: undefined,
  },
)

const emits = defineEmits(['update:modelValue'])
// 表单
const formRef = ref()
const form = {
  titleWidth: 150,
  items: [
    {
      required: true,
      field: 'parentAccount',
      title: '家长账号',
      span: 24,
      itemRender: {
        name: mj_form_input,
      },
    },
    {
      required: true,
      field: 'simSerialNumber',
      title: '设备编号',
      span: 24,
      itemRender: {
        name: mj_form_text,
      },
    },
    {
      required: true,
      field: 'childAccount',
      title: '孩子账号',
      span: 24,
      itemRender: {
        name: mj_form_text,
      },
    },
    {
      field: 'forceBind',
      title: '强制绑定',
      span: 12,
      itemRender: {
        name: mj_form_radio_group,
        options: [
          {
            label: '是',
            value: 1,
          },
          {
            label: '否',
            value: 0,
          },
        ],
      },
    },
  ],
} as any

const show = computed({
  get() {
    return props.modelValue
  },
  set(newVal) {
    emits('update:modelValue', newVal)
    if (newVal) {
      const formDom = formRef.value
      if (props.simSerialNumber) {
        formDom.showItems('simSerialNumber')
        formDom.hideItems('childAccount')
      } else if (props.childAccount) {
        formDom.showItems('childAccount')
        formDom.hideItems('simSerialNumber')
      }

      formDom.setData({
        forceBind: 0,
        parentAccount: props.parentAccount,
        simSerialNumber: props.simSerialNumber,
        childAccount: props.childAccount,
      })
    }
  },
})

const submit = () => {
  const data = formRef.value?.getData()
  hud.confirmLoad(`确认绑定吗？`, {
    task: async () => {
      await bindService.bind(data)
      emits('update:modelValue', false)
    },
    option: '绑定',
    hideError: true,
    hideSuccess: false,
  })
}
</script>

<template>
  <mj-modal
    v-model="show"
    :options="{
      title: '绑定设备',
      width: 600,
    }"
  >
    <mj-form ref="formRef" :options="form" @submit="submit" />
  </mj-modal>
</template>
