<template>
  <PageContainer
    style="padding: 10px 10px"
    :tabList="list"
    :tabActiveKey="productStore.tabActiveKey"
    @tab-change="onTabChange"
  >
    <template #title>
      <div>
        <div style="display: flex; align-items: center">
          <AIcon type="ArrowLeftOutlined" style="font-size: 18px; margin-right: 12px" @click="goBack" />
          <Tooltip>
            <template #title>{{ productStore.current.name }}</template>
            <div class="productDetailHead">
              {{ productStore.current.name }}
            </div>
          </Tooltip>
          <div style="margin: -5px 0 0 20px">
            <Popconfirm
              title="确认禁用"
              @confirm="handleUndeploy"
              v-if="productStore.current.state === 1"
              okText="确定"
              cancelText="取消"
            >
              <Switch :checked="productStore.current.state === 1" checked-children="正常" un-checked-children="禁用" />
            </Popconfirm>
            <Popconfirm
              title="确认启用"
              @confirm="handleDeploy"
              v-if="productStore.current.state === 0"
              okText="确定"
              cancelText="取消"
            >
              <Switch
                :unCheckedValue="productStore.current.state === 0"
                checked-children="正常"
                un-checked-children="禁用"
              />
            </Popconfirm>
          </div>
        </div>
      </div>
    </template>
    <template #content>
      <div style="padding-top: 10px">
        <Descriptions size="small" :column="4">
          <DescriptionsItem
            label="设备数量"
            :labelStyle="{
              fontSize: '14px',
              opacity: 0.55
            }"
            :contentStyle="{
              fontSize: '14px',
              color: '#092EE7',
              cursor: 'pointer'
            }"
            ><span @click="jumpDevice">{{
              productStore.current?.count ? productStore.current?.count : 0
            }}</span></DescriptionsItem
          >
        </Descriptions>
      </div>
    </template>
    <template #extra>
      <PermissionButton
        type="primary"
        :popConfirm="{
          title: `确定应用配置?`,
          placement: 'bottomRight',
          onConfirm: handleDeploy
        }"
        :disabled="productStore.current?.state === 0"
        :tooltip="productStore.current?.state === 0 ? { title: '请先启用产品' } : undefined"
        >应用配置</PermissionButton
      >
    </template>
    <FullPage>
      <Card :bordered="false">
        <component
          :is="tabs[productStore.tabActiveKey]"
          :class="productStore.tabActiveKey === 'Metadata' ? 'metedata' : ''"
          v-bind="{ type: 'product' }"
        />
      </Card>
    </FullPage>
  </PageContainer>
</template>

<script lang="ts" setup>
  import { inject, ref, watch, onMounted } from 'vue';
  import { useProductStore } from '@jdlinker/func';
  import Info from './BasicInfo/index.vue';
  import Device from './DeviceAccess/index.vue';
  import Metadata from '../../../device/components/Metadata/index.vue';
  import { PermissionButton, FullPage } from '@jdlinker/ui';
  import DataAnalysis from './DataAnalysis/index.vue';
  import MetadataMap from './MetadataMap';
  import { _deploy, _undeploy, getProtocolDetail } from '../../../../api/device/product';
  import { onlyMessage } from '@jdlinker/utils';
  // @ts-ignore
  import {
    PageContainer,
    AIcon,
    Card,
    Descriptions,
    DescriptionsItem,
    Popconfirm,
    Tooltip,
    Switch
  } from 'linker-ui-components';

  const props = defineProps({
    id: {
      type: String,
      defult: ''
    }
  });

  const goBack = inject<any>('goBack');
  // const menuStory = useMenuStore();
  // const checked = ref<boolean>(true);
  const productStore = useProductStore();
  // const searchParams = ref({
  //   terms1: [
  //     {
  //       column: 'productId',
  //       termType: 'eq',
  //       value: productStore.current?.id,
  //     },
  //   ],
  //   terms2: undefined,
  //   type: 'and',
  // });

  const list = ref([
    {
      key: 'Info',
      tab: '配置信息'
    },
    {
      key: 'Metadata',
      tab: '物模型',
      class: 'objectModel'
    },
    {
      key: 'Device',
      tab: '设备接入'
    }
  ]);

  const tabs = {
    Info,
    Metadata,
    Device,
    DataAnalysis,
    MetadataMap
  };

  watch(
    () => props.id,
    (newId) => {
      if (newId) {
        productStore.reSet();
        productStore.tabActiveKey = 'Info';
        productStore.refresh(newId as string);
      }
    },
    { immediate: true, deep: true }
  );
  watch(
    () => productStore.current,
    () => {
      getProtocol();
    }
  );
  // const onBack = () => {
  //   history.back();
  // };

  const onTabChange = (e: string) => {
    productStore.tabActiveKey = e;
  };

  /**
   * 启用产品
   */
  const handleDeploy = async () => {
    if (productStore.current.id) {
      const resp = await _deploy(productStore.current.id);
      if (resp) {
        onlyMessage('操作成功！', 'success');
        productStore.refresh(productStore.current.id);
      }
    }
  };

  /**
   * 禁用产品
   */
  const handleUndeploy = async () => {
    if (productStore.current.id) {
      const resp = await _undeploy(productStore.current.id);
      if (resp) {
        onlyMessage('操作成功！', 'success');
        productStore.refresh(productStore.current.id);
      }
    }
  };

  /**
   * 是否显示数据解析模块
   */
  const getProtocol = async () => {
    if (productStore.current?.messageProtocol) {
      const res: any = await getProtocolDetail(productStore.current?.messageProtocol);
      if (res.code === 200) {
        // @ts-ignore
        const paring = res.result?.transports[0]?.features?.find((item: any) => item.id === 'transparentCodec');
        if (paring) {
          list.value = [
            {
              key: 'Info',
              tab: '配置信息'
            },
            {
              key: 'Metadata',
              tab: '物模型',
              class: 'objectModel'
            },
            {
              key: 'Device',
              tab: '设备接入'
            },
            {
              key: 'DataAnalysis',
              tab: '数据解析'
            }
          ];
        } else {
          list.value = [
            {
              key: 'Info',
              tab: '配置信息'
            },
            {
              key: 'Metadata',
              tab: '物模型',
              class: 'objectModel'
            },
            {
              key: 'Device',
              tab: '设备接入'
            }
          ];
        }
      }
      if (productStore.current?.accessProvider === 'plugin_gateway') {
        list.value.push({ key: 'MetadataMap', tab: '物模型映射' });
      }
    }
  };
  /**
   * 详情页跳转到设备页
   */
  const jumpDevice = () => {
    // const searchParams = {
    //   column: 'productId',
    //   termType: 'eq',
    //   value: productStore.current?.id,
    // };
    // menuStory.jumpPage('device/Instance', {
    //   target: 'device-instance',
    //   q: handleParamsToString([searchParams]),
    // });
  };
  onMounted(() => {
    // if (routerParams.params?.value.tab) {
    //     productStore.tabActiveKey = routerParams.params?.value.tab;
    // }
  });
</script>
<style scoped lang="less">
  .ant-switch-loading,
  .ant-switch-disabled {
    cursor: not-allowed;
  }
  .productDetailHead {
    max-width: 300px;
    overflow: hidden;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  :deep(.ant-card-body) {
    height: 584px;
  }
</style>
