<template>
  <div ref="mod">
    <a-modal
      :get-container="() => $refs.mod"
      :open="open"
      :title="title"
      :mask-closable="false"
      @cancel="cancel"
      :footer="null"
    >
      <a-form ref="formRef" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item
          label="设备ID"
          name="deviceId"
          :rules="[
            {
              required: true,
              validator: deviceIdValidator,
              trigger: ['blur'],
            },
          ]"
        >
          <a-input
            v-model:value="formState.deviceId"
            placeholder="请输入设备ID"
            :maxlength="12"
            show-count
            allow-clear
          />
        </a-form-item>
        <a-form-item
          label="设备类型"
          name="deviceType"
          :rules="[{ required: true, message: '请选择设备类型' }]"
        >
          <a-select v-model:value="formState.deviceType" placeholder="请选择设备类型">
            <a-select-option value="1">LNA</a-select-option>
            <a-select-option value="2">LNB</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          label="固件版本"
          name="firmwareVersion"
          :rules="[{ required: true, message: '请输入固件版本' }]"
        >
          <a-input v-model:value="formState.firmwareVersion" placeholder="请输入固件版本" />
        </a-form-item>

        <a-form-item
          label="归属租户"
          name="tenantId"
          :rules="[{ required: true, message: '请选择归属租户' }]"
        >
          <a-select
            v-model:value="formState.tenantId"
            placeholder="请选择归属租户"
            :options="props.options"
          >
          </a-select>
        </a-form-item>
      </a-form>

      <div class="footer">
        <a-space>
          <a-button @click="cancel">取消</a-button>
          <a-button type="primary" :loading="submitLoading" @click="submit">确定</a-button>
        </a-space>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message, type FormInstance } from 'ant-design-vue'
import * as deviceApi from '@/api/device'
import type { Rule } from 'ant-design-vue/es/form'

defineOptions({
  name: 'addDevice',
})

const formRef = ref<FormInstance>()

type Props = {
  open: boolean
  title: string
  options?: {
    value: string
    label: string
  }[]
}
const emit = defineEmits<{
  (e: 'update:open', value: boolean): void
  (e: 'success', value: void): void
}>()

const props = withDefaults(defineProps<Props>(), {
  open: false,
  title: '',
  options: () => [],
})

const formState = reactive({
  deviceId: '',
  deviceType: 'LNA',
  softVersion: '',
  firmwareVersion: '',
  tenantId: null as null | string,
})

const cancel = () => {
  formRef?.value?.resetFields()
  emit('update:open', false)
}

// 设备ID校验，16进制12个字符
const deviceIdValidator = async (_rule: Rule, value: string) => {
  if (!value) {
    return Promise.reject(new Error('请输入设备ID'))
  }
  if (!/^[0-9a-fA-F]{12}$/.test(value)) {
    return Promise.reject(new Error('设备ID不合法'))
  }

  return Promise.resolve()
}

const submitLoading = ref(false)
// 确定
const submit = () => {
  formRef?.value
    ?.validate()
    .then(() => {
      console.log('校验通过', formState)
      submitLoading.value = true
      deviceApi
        .addDevice({
          clientId: formState.deviceId,
          devType: formState.deviceType,
          hardware: formState.firmwareVersion,
          tenantId: formState.tenantId,
        })
        .then((res) => {
          console.log('添加成功', res)
          submitLoading.value = false
          message.success('添加成功')
          emit('success')
          cancel()
        })
        .catch(() => {
          submitLoading.value = false
        })
    })
    .catch((err) => {
      console.log('校验失败', err)
    })
}
</script>

<style scoped lang="less">
:deep(.ant-modal) {
  .footer {
    text-align: right;
  }
}
</style>
