<script setup lang="ts">
import { onMounted, ref } from 'vue';

import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import { gatewayLinkGetList, gatewayLinkList, gatewayParameterList } from '@/api';

import type { Key } from 'ant-design-vue/es/table/interface';
import type {
  GatewayParameterItem,
  InterfaceData,
  RegisterGatewayForm,
  UseGuideStepItemProps,
  VerificationAgreement,
} from '@/types';

const activeKey = ref();

const interfaceValue = ref<number>(0);

const { handleRequest } = useRequest();

let interfaceList: InterfaceData[];

interface InterfaceItem {
  id: number;
  baudRate: number;
  dataBit: number;
  stopBit: string;
  parityBit: string;
  protocolType: string;
}

interface ItemList {
  value: number;
  payload: string;
  id: number;
  baudRate: number;
  dataBit: number;
  stopBit: string;
  parityBit: string;
  protocolType: string;
}

const interfaceData = ref<ItemList[]>([]);
const interfaceItem = ref<InterfaceItem>();
const verificationAgreement = ref<VerificationAgreement[]>([]);

const protocolList = ref<GatewayParameterItem[]>([]);

const props = defineProps<UseGuideStepItemProps<RegisterGatewayForm>>();

const protocolColumns = [
  {
    title: t('setupProtocol.protocolParamFields.paramName'),
    dataIndex: 'gatewayParamName',
    key: 'gatewayParamName',
    ellipsis: true,
  },
  {
    title: t('setupProtocol.protocolParamFields.paramCode'),
    dataIndex: 'gatewayParamCode',
    key: 'gatewayParamCode',
    ellipsis: true,
  },
  {
    title: t('registerGateway.monitoringResults'),
    dataIndex: 'monitorStatus',
    key: 'monitorStatus',
    ellipsis: true,
  },
  {
    title: t('registerGateway.resultData'),
    dataIndex: 'value',
    key: 'value',
    ellipsis: true,
  },
];

const interfaceAdd = (value: number | string) => {
  interfaceList.forEach((item) => {
    if (item.id === value) {
      const { baudRate, dataBit, stopBit, parityBit, id, protocolType } = item;
      interfaceItem.value = {
        baudRate,
        dataBit,
        stopBit,
        parityBit,
        id,
        protocolType,
      };
    }
  });
  if (interfaceItem.value) {
    postVerificationAgreement(interfaceItem.value.id);
  }
};

const addList = (key: Key | Key[]) => {
  if (key) {
    postGatewayLinkProtocolList(Number(activeKey.value));
  }
};

const postGatewayLinkProtocolList = (value: number) => {
  protocolList.value = [];
  handleRequest(async () => {
    const { records } = await gatewayParameterList({
      pageIndex: 1,
      pageSize: 10,
      gatewayLinkProtocolId: value,
      gatewayId: props.form.id,
    });
    protocolList.value = records;
  });
};

const postVerificationAgreement = (id: number) => {
  handleRequest(async () => {
    verificationAgreement.value = await gatewayLinkList(id);
    if (verificationAgreement.value.length) {
      activeKey.value = verificationAgreement.value[0].id;
      postGatewayLinkProtocolList(activeKey.value);
    }
  });
};

const addRefresh = (id: number) => {
  if (id) {
    postGatewayLinkProtocolList(id);
  }
};

onMounted(() => {
  handleRequest(async () => {
    interfaceList = await gatewayLinkGetList(props.form.id);
    if (interfaceList.length) {
      const { baudRate, dataBit, stopBit, parityBit, id, protocolType } = interfaceList[0];
      interfaceItem.value = {
        baudRate,
        dataBit,
        stopBit,
        parityBit,
        id,
        protocolType,
      };
      interfaceValue.value = id;
      interfaceList.forEach((item) => {
        const { baudRate, dataBit, stopBit, parityBit, id, protocolType, linkName } = item;
        interfaceData.value.push({
          value: id,
          payload: linkName,
          baudRate,
          dataBit,
          stopBit,
          parityBit,
          id,
          protocolType,
        });
      });

      postVerificationAgreement(id);
    }
  });
});
</script>

<template>
  <div class="verification-agreement">
    <ARow>
      <ACol :span="12">
        <ASegmented
          class="agreement-segmented"
          v-model:value="interfaceValue"
          :options="interfaceData"
          @change="interfaceAdd"
          size="large"
        >
          <template #label="{ payload }">
            <div class="agreement-padding">
              <div>{{ payload }}</div>
            </div>
          </template>
        </ASegmented>
      </ACol>
    </ARow>

    <div class="agreement-text">
      <span>{{ $t('setupProtocol.protocolType') }}：</span> <span>{{ interfaceItem?.protocolType }}</span>
      <span v-if="interfaceItem?.protocolType === 'ModbusRTU'"
        ><span class="agreement-text1">{{ $t('setupProtocol.baudRate') }}：</span>
        <span>{{ interfaceItem?.baudRate }}</span>
        <span class="agreement-text1">{{ $t('setupProtocol.dataBit') }}：</span>
        <span>{{ interfaceItem?.dataBit }}</span>
        <span class="agreement-text1">{{ $t('setupProtocol.stopBit') }}：</span>
        <span>{{ interfaceItem?.stopBit }}</span>
        <span class="agreement-text1">{{ $t('setupProtocol.parityBit') }}：</span>
        <span>{{ interfaceItem?.parityBit }}</span></span
      >
    </div>
    <ACollapse
      v-model:active-key="activeKey"
      class="protocol-collapse"
      @change="addList"
      accordion
      collapsible="header"
    >
      <ACollapsePanel v-for="item in verificationAgreement" :key="item.id">
        <template #header>
          <span class="header-text">{{ $t('registerGateway.station') }}{{ item.station }}</span>
          <span class="header-text1">{{ $t('registerGateway.communicationProtocol') }}:{{ item.protocolName }}</span>
        </template>
        <template #extra>
          <AFlex align="center">
            <span class="header-text2">
              <span>{{ $t('registerGateway.regularReportingFrequency') }}: </span>
              <span>{{ item.dataSendInterval }}s</span>
            </span>
            <span class="header-text2">
              <span>{{ $t('registerGateway.highFrequencyReportingFrequency') }}: </span>
              <span>{{ item.highFreqSendInterval }}s</span>
            </span>
            <AButton class="icon-button but-text" type="text" @click="addRefresh(item.id)">
              <SvgIcon name="refresh-o" />
              {{ $t('registerGateway.refreshData') }}
            </AButton>
          </AFlex>
        </template>
        <AFlex>
          <ATable row-key="id" :columns="protocolColumns" :data-source="protocolList" :pagination="false">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'monitorStatus'">
                <AFlex align="center">
                  <div v-if="record.monitorStatus === 1" class="monitor-status-div monitor-status-success"></div>
                  <div v-else class="monitor-status-div monitor-status-failure"></div>
                  {{ record.monitorStatus === 1 ? $t('common.success') : $t('common.failure') }}
                </AFlex>
              </template>
            </template>
          </ATable>
        </AFlex>
      </ACollapsePanel>
    </ACollapse>
  </div>
</template>

<style lang="scss" scoped>
:deep(.ant-segmented .ant-segmented-group) {
  padding: 4px;
}

.monitor-status-failure {
  background: #f56c6c;
}

.monitor-status-success {
  background: #67c23a;
}

.monitor-status-div {
  width: 6px;
  height: 6px;
  margin-right: 8px;
  border-radius: 50%;
}

.agreement-segmented {
  color: var(--antd-color-primary-hover);
  background-color: #e1f5f6;
}

:deep(.agreement-segmented) {
  .ant-segmented-item-selected {
    color: #fff;
    background-color: var(--antd-color-primary-hover);
    border-radius: 8px;
  }
}

.agreement-content-left {
  width: 240px;
  border-right: 2px solid #e4e7ed; /* 只设置右边框 */
}

.gateway-log {
  color: var(--antd-color-primary-hover);
}

.remote-debugging {
  margin-right: 16px;
}

.agreement-text {
  margin-top: 20px;
  margin-bottom: 15px;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 24px;
  color: #333;
  text-align: left;
}

.agreement-text1 {
  margin-left: 40px;
}

.header-text {
  margin-right: 15px;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 24px;
  color: #333;
  text-align: left;
}

.header-text1 {
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 24px;
  color: #666;
  text-align: left;
}

.header-text2 {
  margin-right: 32px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
  color: #666;
  text-align: left;
}

.but-text {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 108px;
  height: 32px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
  color: var(--antd-color-primary-hover);
  text-align: left;
  cursor: pointer;
}
</style>
