<script lang="ts" setup>
  import { Button, Tag } from 'ant-design-vue';
  import { h, onMounted, ref, unref } from 'vue';
  import { DeviceRecord } from '/@/api/device/model/deviceModel';
  import { ScriptRecord } from '/@/api/scriptmanage/model/scriptModel';
  import { getScriptManageMeList } from '/@/api/scriptmanage/scriptManager';
  import { Description, useDescription } from '/@/components/Description';
  import { useModal } from '/@/components/Modal';
  import CoverScriptModal from '/@/views/scriptmanage/converscript/ConverScriptModal.vue';

  const props = defineProps<{
    record: DeviceRecord['profileData']['transportConfiguration'];
  }>();

  const scriptInfo = ref<ScriptRecord>({} as unknown as ScriptRecord);

  const [register, { setDescProps }] = useDescription({
    layout: 'vertical',
    column: 2,
    data: props.record,
    schema: [
      {
        field: 'type',
        label: '接入协议',
        span: 2,
      },
      {
        field: 'scriptName',
        label: '转换脚本',
        render: (value: string) => {
          return (
            value &&
            h('div', [
              h(Tag, { color: 'blue' }, () => value),
              h(Button, { type: 'link', onClick: handleTestScript }, () => '测试脚本'),
            ])
          );
        },
      },
    ],
  });

  const [registerModal, { openModal }] = useModal();

  const handleTestScript = () => {
    openModal(true, {
      isUpdate: false,
      isTest: true,
      record: unref(scriptInfo).id,
      isText: 'test',
      isTitle: 'test',
    });
  };

  onMounted(() => {
    getTransforScriptInfo();
  });

  const getTransforScriptInfo = async () => {
    try {
      const list = await getScriptManageMeList();
      const record = list.find((item) => item.id === props.record.scriptId);
      scriptInfo.value = record!;
      setDescProps({
        data: Object.assign(props.record, record, { scriptName: record?.name || '' }),
      });
    } catch (error) {}
  };
</script>

<template>
  <section>
    <Description @register="register" />
    <CoverScriptModal @register="registerModal" />
  </section>
</template>
