<script lang="ts" setup>
import { ref } from 'vue'
import { Modal } from 'ant-design-vue'
import { EyeOutlined } from '@ant-design/icons-vue'
import { useAsyncState } from '@vueuse/core'
import { getMqttConnectParams } from '@/api/device-manage/device'
import type { DescItem } from '@/components/Description'
import { Description } from '@/components/Description'
import { noop } from '@/utils'
import { copyText } from '@/utils/copyTextToClipboard'

const props = defineProps<{ deviceId: string }>()

const { state, execute, isLoading } = useAsyncState(() => getMqttConnectParams(props.deviceId), undefined, { immediate: false })

const open = ref(false)
function handleOpen() {
  if (state.value)
    return open.value = true

  execute()
    .then(() => {
      open.value = true
    })
    .catch(noop)
}

const schema: DescItem[] = [
  {
    label: '服务器地址 (hostUrl)',
    field: 'hostUrl',
  },
  {
    label: '端口 (port)',
    field: 'port',
  },
  {
    label: 'ClientID (clientId)',
    field: 'clientId',
  },
  {
    label: '用户名 (username)',
    field: 'username',
  },
  {
    label: '密码 (password)',
    field: 'password',
  },
]

function handleCopy() {
  const data = schema.map((item) => {
    return {
      key: item.field,
      keyName: item.label,
      value: state.value[item.field],
    }
  })
  copyText(JSON.stringify(data))
}
</script>

<template>
  <a-button size="small" :loading="isLoading" @click="handleOpen">
    <EyeOutlined />
    查看参数
  </a-button>

  <Modal v-model:open="open" title="MQTT 连接参数" :footer="null">
    <Description :data="state" :schema="schema" :column="1" />
    <div text="center" mt="10px">
      <a-button size="small" @click="handleCopy">
        一键复制
      </a-button>
    </div>
  </Modal>
</template>