<template>
  <PageContainer
    style="padding: 10px 10px"
    :tabList="list"
    :showBack="true"
    :tabActiveKey="instanceStore.tabActiveKey"
    @tab-change="onTabChange"
  >
    <template #title>
      <div style="display: flex; align-items: center">
        <JAIcon type="ArrowLeftOutlined" style="font-size: 18px; margin-right: 12px" @click="goBack" />
        <Tooltip :title="instanceStore.current?.name">
          <div class="deviceDetailHead">
            {{ instanceStore.current?.name }}
          </div>
        </Tooltip>
        <Divider type="vertical" />
        <Space>
          <span style="font-size: 14px; color: rgba(0, 0, 0, 0.85)">
            状态：
            <Badge :status="statusMap.get(instanceStore.current?.state?.value)" />
            {{ instanceStore.current?.state?.text }}
          </span>
          <PermissionButton
            v-if="instanceStore.current?.state?.value === 'notActive'"
            type="link"
            style="margin-top: -5px; padding: 0 20px"
            :popConfirm="{
              title: '确认启用设备',
              onConfirm: handleAction
            }"
          >
            启用设备
          </PermissionButton>
          <PermissionButton
            v-if="instanceStore.current?.state?.value === 'online'"
            type="link"
            style="margin-top: -5px; padding: 0 20px"
            :popConfirm="{
              title: '确认断开连接？',
              onConfirm: handleDisconnect
            }"
          >
            断开连接
          </PermissionButton>
          <Tooltip
            v-if="
              instanceStore.current?.accessProvider === 'child-device' && instanceStore.current?.state?.value === 'offline'
            "
            :title="
              instanceStore.current?.features?.find((item) => item?.id === 'selfManageState')
                ? '该设备的在线状态与父设备(网关设备)保持一致'
                : '该设备在线状态由设备自身运行状态决定，不继承父设备（网关设备）的在线状态'
            "
          >
            <JAIcon type="QuestionCircleOutlined" style="font-size: 14px" />
          </Tooltip>
        </Space>
      </div>
    </template>
    <template #content>
      <Descriptions size="small" :column="4">
        <DescriptionsItem label="ID" style="width: 220px">{{ instanceStore.current?.id }}</DescriptionsItem>
        <DescriptionsItem label="所属产品">
          <PermissionButton type="link" style="margin-top: -5px; padding: 0" @click="jumpProduct">
            {{ instanceStore.current?.productName }}
          </PermissionButton>
        </DescriptionsItem>
      </Descriptions>
    </template>
    <template #extra>
      <img @click="handleRefresh" :src="getImage('/device/button.png')" style="margin-right: 20px; cursor: pointer" />
    </template>
    <FullPage>
      <Card :bordered="false">
        <component :is="tabs[instanceStore.tabActiveKey]" v-bind="{ type: 'device' }" @on-jump="onTabChange" />
      </Card>
    </FullPage>
  </PageContainer>
</template>

<script lang="ts" setup>
  import { useInstanceStore, useMenuStore, useSocketStore } from '@jdlinker/func';
  import Info from './Info/index.vue';
  import Running from './Running/index.vue';
  import Metadata from '../../../device/components/Metadata/index.vue';
  import MetadataMap from './MetadataMap/index.vue';
  import ChildDevice from './ChildDevice/index.vue';
  import Diagnose from './Diagnose/index.vue';
  import Function from './Function/index.vue';
  import Modbus from './Modbus/index.vue';
  import OPCUA from './OPCUA/index.vue';
  import EdgeMap from './EdgeMap/index.vue';
  import Parsing from './Parsing/index.vue';
  import GateWay from './GateWay/index.vue';
  import Log from './Log/index.vue';
  import { _deploy, _disconnect } from '../../../../api/device/instance';
  import { getImage, onlyMessage } from '@jdlinker/utils';
  import { PermissionButton, FullPage } from '@jdlinker/ui';
  import { ref, watch, inject, onMounted, onUnmounted } from 'vue';
  import { useRoute } from "vue-router";
  // @ts-ignore
  import { PageContainer, AIcon as JAIcon, Card, Tooltip, Divider, Space, Badge, Descriptions, DescriptionsItem } from 'linker-ui-components';

  const menuStory = useMenuStore();
  const props = defineProps({
    id: {
      type: String,
      defult: ''
    }
  });
  const goBack = inject<any>('goBack');
  const route = useRoute();
  const instanceStore = useInstanceStore();
  const webSocketStore = useSocketStore();

  const statusMap = new Map();
  statusMap.set('online', 'success');
  statusMap.set('offline', 'error');
  statusMap.set('notActive', 'warning');

  const deviceStatus = new Map();
  deviceStatus.set('online', '在线');
  deviceStatus.set('offline', '离线');
  deviceStatus.set('notActive', '禁用');

  const initList = [
    {
      key: 'Info',
      tab: '实例信息'
    },
    {
      key: 'Running',
      tab: '运行状态'
    },
    {
      key: 'Metadata',
      tab: '物模型'
    },
    {
      key: 'Function',
      tab: '设备功能'
    },
    {
      key: 'Log',
      tab: '日志管理'
    }
  ];

  const list = ref([...initList]);
  const tabs = {
    Info,
    Metadata,
    Running,
    ChildDevice,
    Diagnose,
    Function,
    Modbus,
    OPCUA,
    EdgeMap,
    Parsing,
    Log,
    MetadataMap,
    GateWay
  };

  const topic = '/dashboard/device/status/change/realTime';

  const getStatus = (id: string) => {
    const stompClient = webSocketStore.$state.stompClient;
    const params = {
      deviceId: id
    };
    const headers = {
      id: `instance-editor-info-status-${id}`,
      topic: topic,
      parameter: JSON.stringify(params)
    };
    // 消息订阅
    stompClient.subscribe(
      topic,
      (msg) => {
        const payload = JSON.parse(msg.body).payload;
        instanceStore.setCurrent({
          ...instanceStore.current,
          state: {
            value: payload.value.type,
            text: deviceStatus.get(payload.value.type)
          }
        });
        // instanceStore.refresh(id);
      },
      headers
    );
  };

  const getDetail = () => {
    const keys: any = list.value.map((i) => i.key);
    if (
      instanceStore.current?.protocol &&
      !['modbus-tcp', 'opc-ua'].includes(instanceStore.current?.protocol) &&
      !keys.includes('Diagnose')
    ) {
      list.value.push({
        key: 'Diagnose',
        tab: '设备诊断'
      });
    }
    if (instanceStore.current?.features?.find((item: any) => item?.id === 'transparentCodec') && !keys.includes('Parsing')) {
      list.value.push({
        key: 'Parsing',
        tab: '数据解析'
      });
    }
    if (instanceStore.current?.protocol === 'modbus-tcp' && !keys.includes('Modbus')) {
      list.value.push({
        key: 'Modbus',
        tab: '数采映射'
      });
    }
    if (instanceStore.current?.protocol === 'opc-ua' && !keys.includes('OPCUA')) {
      list.value.push({
        key: 'OPCUA',
        tab: '数采映射'
      });
    }
    if (instanceStore.current?.protocol === 'collector-gateway' && !keys.includes('GateWay')) {
      list.value.push({
        key: 'GateWay',
        tab: '数采映射'
      });
    }
    if (instanceStore.current?.deviceType?.value === 'gateway' && !keys.includes('ChildDevice')) {
      // 产品类型为网关的情况下才显示此模块
      list.value.push({
        key: 'ChildDevice',
        tab: '子设备'
      });
    }
    if (
      instanceStore.current?.accessProvider === 'edge-child-device' &&
      instanceStore.current?.parentId &&
      !keys.includes('EdgeMap')
    ) {
      list.value.push({
        key: 'EdgeMap',
        tab: '边缘端映射'
      });
    }

    if (
      instanceStore.current?.features?.find((item: any) => item?.id === 'diffMetadataSameProduct') &&
      !keys.includes('MetadataMap')
    ) {
      list.value.push({ key: 'MetadataMap', tab: '物模型映射' });
    }
  };

  const initPage = async (newId: any) => {
    await instanceStore.refresh(String(newId));
    getStatus(String(newId));
    list.value = [...initList];
    getDetail();
    instanceStore.tabActiveKey = 'Info';
  };
  // onBeforeRouteUpdate((to: any) => {
  //   if (to.params?.id) {
  //     initPage(to.params?.id)
  //   }
  // })

  watch(
    () => props.id,
    () => {
      if (props.id) {
        initPage(props.id);
      }
    },
    { immediate: true }
  );

  const getDetailFn = async () => {
    const _id = route.params?.id;
    if (_id) {
      await instanceStore.refresh(String(_id));
      getStatus(String(_id));
      list.value = [...initList];
      getDetail();
    }
    instanceStore.tabActiveKey = 'Info';
  };

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

  const onTabChange = (e: string) => {
    if (instanceStore.tabActiveKey === 'Metadata') {
      // EventEmitter.emit('MetadataTabs', () => {
      instanceStore.tabActiveKey = e;
      // });
    } else {
      instanceStore.tabActiveKey = e;
    }
  };

  const handleAction = async () => {
    if (instanceStore.current?.id) {
      const resp = await _deploy(instanceStore.current?.id);
      if (resp.code === 200) {
        onlyMessage('操作成功！');
        instanceStore.refresh(instanceStore.current?.id);
      }
    }
  };

  const handleDisconnect = async () => {
    if (instanceStore.current?.id) {
      const resp = await _disconnect(instanceStore.current?.id);
      if (resp.code === 200) {
        onlyMessage('操作成功！');
        instanceStore.refresh(instanceStore.current?.id);
      }
    }
  };

  const handleRefresh = async () => {
    if (instanceStore.current?.id) {
      await instanceStore.refresh(instanceStore.current?.id);
      onlyMessage('操作成功');
    }
  };

  const jumpProduct = () => {
    menuStory.jumpPage('/iot/device/Product', {
      id: instanceStore.current?.productId
    });
    //menuStory.jumpPage(`/iot/device/Product/${instanceStore.current?.productId}`, {});
  };

  onUnmounted(() => {
    instanceStore.current = {} as any;
    if (webSocketStore) {
      webSocketStore.webSocket_unsub(webSocketStore.$state, topic);
    }
  });
</script>

<style lang="less" scoped>
  .deviceDetailHead {
    max-width: 400px;
    overflow: hidden;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  :deep(.ant-card-body) {
    min-height: 589px;
  }
</style>
