<script lang="ts" setup>
  import { Spin, Image } from 'ant-design-vue';
  import { ref, unref, h } from 'vue';
  import { deviceConfigGetRuleChain } from '/@/api/device/deviceConfigApi';
  import { RuleChainRecord } from '/@/api/device/model/deviceConfigModel';
  import { DeviceRecord } from '/@/api/device/model/deviceModel';
  import { findDictItemByCode } from '/@/api/system/dict';
  import { SysDictItemResult } from '/@/api/system/model/dictModel';
  import { Description, useDescription } from '/@/components/Description';
  import { to } from '/@/utils/to';
  import productDefaultImage from '/@/assets/icons/product-default.svg';
  import { Button } from '/@/components/Button';
  import { useGo } from '/@/hooks/web/usePage';
  import { PageEnum } from '/@/enums/pageEnum';

  const loading = ref(false);

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

  const data = ref<DeviceRecord>({} as unknown as DeviceRecord);

  const [register, { setDescProps }] = useDescription({
    layout: 'vertical',
    column: 2,
    schema: [
      {
        field: 'image',
        label: '图片',
        span: 2,
        render: (val) => {
          return h(Image, { src: val || productDefaultImage, height: 200 });
        },
      },
      {
        field: 'deviceTypeName',
        label: '设备类型',
        render: (_, data) => {
          return h(
            Button,
            {
              type: 'link',
              style: { marginLeft: -8 + 'px' },
              size: 'small',
              onClick: () => {
                go(
                  PageEnum.DEVICE_LIST +
                    '?count=' +
                    data.deviceCount +
                    '&deviceProfileId=' +
                    data.tbProfileId
                );
              },
            },
            () => `${data.deviceTypeName}(${data.deviceCount})`
          );
        },
      },
      {
        field: 'name',
        label: '产品名称',
      },
      {
        field: 'ruleChain',
        label: '规则链',
      },
      {
        field: 'queueName',
        label: '处理队列',
      },
      {
        field: 'description',
        label: '描述',
        render(val) {
          return h('div', { class: 'min-h-6' }, val);
        },
      },
    ],
  });

  const findDeviceType = async (deviceType: string) => {
    const [error, data] = await to<SysDictItemResult[]>(
      findDictItemByCode({ dictCode: 'device_type' })
    );
    if (!error) {
      const record = data.find((item) => item.itemValue === deviceType);
      return { deviceTypeName: record?.itemText };
    }
    return {};
  };

  const findHandleQueue = async (defaultQueueName: string) => {
    const [error, data] = await to<SysDictItemResult[]>(
      findDictItemByCode({ dictCode: 'queen_execute_sequence' })
    );
    if (!error) {
      const record = data.find((item) => item.itemValue === defaultQueueName);
      return { queueName: record?.itemText };
    }
    return {};
  };

  const findRuleChain = async (ruleChain: string) => {
    const [error, data] = await to<RuleChainRecord[]>(deviceConfigGetRuleChain());
    if (!error) {
      const record = data.find((item) => item.id.id === ruleChain);
      return { ruleChain: record?.name };
    }
    return {};
  };

  const renderProductInfo = async (record: DeviceRecord) => {
    try {
      data.value = {} as unknown as DeviceRecord;
      loading.value = true;
      const { defaultRuleChainId, deviceType, defaultQueueName } = record;
      if (![defaultRuleChainId, deviceType, defaultQueueName].some(Boolean)) {
        return;
      }
      data.value = record;
      const values = await Promise.all([
        findDeviceType(deviceType),
        findHandleQueue(defaultQueueName),
        findRuleChain(defaultRuleChainId),
      ]);
      const value = values.reduce((prev, next) => ({ ...prev, ...next }), {});
      data.value = Object.assign(unref(data), value);
      setDescProps({ data: unref(data) });
    } catch (error) {
      throw error;
    } finally {
      loading.value = false;
    }
  };

  defineExpose({
    renderProductInfo,
  });
</script>

<template>
  <Spin :spinning="loading">
    <Description class="product-description" @register="register" />
  </Spin>
</template>

<style lang="less" scoped>
  .product-description:deep(.ant-image-img) {
    height: 200px !important;
  }
</style>
