<template>
  <div>
    <div>
      <Typography>
        <TypographyParagraph>
          <blockquote class="bg-gray-50">{{ useBlockContent }}</blockquote>
        </TypographyParagraph>
      </Typography>
    </div>
    <div>
      <Tabs type="card" v-model:active-key="activeKey" @change="handleSwitchTsl">
        <Tabs.TabPane :key="FunctionType.PROPERTIES" tab="属性" />
        <Tabs.TabPane :key="FunctionType.SERVICE" tab="服务" />
        <Tabs.TabPane :key="FunctionType.EVENTS" tab="事件" />
        <template #tabBarExtraContent>
          <Button class="ml-2" @click="handleCopy">
            <template #icon>
              <CopyOutlined />
            </template>
            copy
          </Button>
        </template>
      </Tabs>
    </div>
    <div class="relative">
      <Spin :spinning="loading">
        <Input.TextArea
          :disabled="true"
          :auto-size="{ minRows: 20, maxRows: 20 }"
          :value="jsonValue"
        />
      </Spin>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref, onMounted } from 'vue';
  import { CopyOutlined } from '@ant-design/icons-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { Button, Typography, TypographyParagraph, Tabs, Spin, Input } from 'ant-design-vue';
  import { FunctionType } from './config';
  import useCommon from '../hook/useCommon';
  import { DeviceRecord } from '/@/api/device/model/deviceModel';
  import { getModelTsl } from '/@/api/device/modelOfMatter';
  import { useCopyToClipboard } from '/@/hooks/web/useCopyToClipboard';

  const props = defineProps<{
    record: DeviceRecord;
  }>();

  const loading = ref(false);

  const { createMessage } = useMessage();

  const { useBlockContent } = useCommon();

  const jsonValue = ref();

  const activeKey = ref(FunctionType.PROPERTIES);

  const { clipboardRef, isSuccessRef } = useCopyToClipboard(jsonValue.value);
  const handleCopy = () => {
    try {
      if (!jsonValue.value) {
        createMessage.warning('请输入要拷贝的内容！');
        return;
      }
      clipboardRef.value = jsonValue.value;
      if (unref(isSuccessRef)) createMessage.success('复制成功！');
      else createMessage.error('复制失败！');
    } catch (e) {
      console.log(e);
    }
  };

  const getFormData = () => {
    return JSON.parse(jsonValue.value);
  };

  const resetFormData = () => {
    jsonValue.value = null;
  };

  const handleSwitchTsl = async (functionType: FunctionType) => {
    try {
      loading.value = true;
      const record = await getModelTsl({ deviceProfileId: props.record.id, functionType });
      jsonValue.value = JSON.stringify(record, null, 2);
    } catch (error) {
    } finally {
      loading.value = false;
    }
  };

  onMounted(() => {
    activeKey.value = FunctionType.PROPERTIES;
    handleSwitchTsl(FunctionType.PROPERTIES);
  });

  defineExpose({
    getFormData,
    resetFormData,
  });
</script>
