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

import ModalGuidance from '@/layout/ModalGuidance.vue';
import ConfirmModal from '@/components/ConfirmModal.vue';
import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import {
  addGatewayLinkBatchUpdate,
  gatewayList,
  getGatewayLinks,
  obtainListInterfaces,
  obtainListPhysicalInterfaces,
  orgGatewayUnregister,
} from '@/api';

import RegisterGateway from '../register-gateway/RegisterGateway.vue';

import type { DefaultOptionType, SelectValue } from 'ant-design-vue/es/select';
import type {
  BatchUpdate,
  GatewayListItem,
  GatewayQuery,
  InterfaceData,
  InterfaceLsit,
  ListInterfaces,
  ListPhysicalInterfaces,
} from '@/types';

const gatewayColumns = [
  {
    title: t('common.serialNumber'),
    dataIndex: 'index',
    key: 'index',
  },
  {
    title: t('common.sequenceNumber'),
    dataIndex: 'snCode',
    key: 'snCode',
    ellipsis: true,
  },
  {
    title: t('createDevice.modelNumber'),
    dataIndex: 'modelName',
    key: 'modelName',
    ellipsis: true,
  },
  {
    title: t('registerGateway.onlineStatus'),
    dataIndex: 'state',
    key: 'state',
    ellipsis: true,
  },
  {
    title: t('common.operation'),
    dataIndex: 'action',
    key: 'action',
    width: 80,
  },
];

const agreementColumns = [
  // {
  //   title: t('registerGateway.stationNumber'),
  //   dataIndex: 'station',
  //   key: 'station',
  //   ellipsis: true,
  // },
  {
    title: t('registerGateway.agreement'),
    dataIndex: 'protocolName',
    key: 'protocolName',
    ellipsis: true,
  },
  {
    title: t('registerGateway.associatedEquipment'),
    dataIndex: 'deviceName',
    key: 'deviceName',
    ellipsis: true,
  },
];

const gatewayData = ref<GatewayListItem[]>([]);
const interfaceList = ref<InterfaceLsit[]>([]);
const interfaceOriginalData = ref<InterfaceLsit[]>([]);

const gatewayId = ref<number>();
const gatewayEditor = ref<boolean>(false);
const interfaceSelectList = ref<ListInterfaces[]>([]);
const listPhysicalInterfaces = ref<ListPhysicalInterfaces[]>([]);
const gatewayLinks = ref<BatchUpdate[]>([]);
// 添加选中状态
const selectedRowId = ref<string | null>(null);
const modalGuidanceRef = useTemplateRef('modalGuidance');
const activeKey = ref();
const gatewayQuery = ref<GatewayQuery>({
  pageIndex: 1,
  pageSize: 10,
  searchContent: '',
  state: -1,
  total: 0,
});

const modalComponentRef = useTemplateRef('modalComponent');

const { handleRequest } = useRequest();

const getGatewayList = () => {
  handleRequest(async () => {
    const { records, total } = await gatewayList(gatewayQuery.value);
    gatewayData.value = records;
    gatewayQuery.value.total = total;
    if (records.length) {
      getObtainListInterfaces(gatewayData.value[0].modelId);
      postLinkGetList(gatewayData.value[0].id);
      selectedRowId.value = String(gatewayData.value[0].id);
    } else {
      interfaceList.value = [];
    }
  });
};

const addGatewayList = () => {
  gatewayQuery.value.pageIndex = 1;
  getGatewayList();
};

const addReset = () => {
  gatewayQuery.value.searchContent = '';
  gatewayQuery.value.state = -1;
  addGatewayList();
};

const rowClick = (record: GatewayListItem) => {
  return {
    onClick: () => {
      // 更新选中行ID
      selectedRowId.value = String(record.id);

      gatewayId.value = record.id;
      getObtainListInterfaces(record.modelId);
      postLinkGetList(record.id);
    },
  };
};

// 动态行类名
const rowClassName = (record: GatewayListItem) => {
  return String(record.id) === selectedRowId.value ? 'selected-row' : '';
};

const getObtainListInterfaces = (id: number) => {
  handleRequest(async () => {
    interfaceSelectList.value = await obtainListInterfaces(id);
  });
};

const getObtainListPhysicalInterfaces = (id: number, value?: InterfaceData) => {
  handleRequest(async () => {
    listPhysicalInterfaces.value = await obtainListPhysicalInterfaces(id);
    if (value) {
      if (listPhysicalInterfaces.value.length) {
        value.protocolType = listPhysicalInterfaces.value[0].protocolName;
      } else {
        value.protocolType = '';
      }
    }
  });
};

const choosePhysicalInterface = (
  selectValue: SelectValue,
  option: DefaultOptionType,
  id: number,
  value: InterfaceData,
  index: number,
) => {
  interfaceList.value[index].interfaceType = option.interfaceType;
  interfaceList.value[index].linkName = option.name;

  getObtainListPhysicalInterfaces(id, value);
};

const postLinkGetList = (id: number) => {
  handleRequest(async () => {
    interfaceOriginalData.value = await getGatewayLinks(id);
    if (interfaceOriginalData.value.length) {
      interfaceList.value = interfaceOriginalData.value;
      activeKey.value = interfaceList.value[0].id;
      getObtainListPhysicalInterfaces(interfaceList.value[0].interfaceId);
    } else {
      interfaceList.value = [];
    }
  });
};

const switchPages = () => {
  getGatewayList();
};

const refreshData = () => {
  gatewayQuery.value.pageIndex = 1;
  getGatewayList();
};

const confirm = () => {
  handleRequest(async () => {
    if (gatewayId.value) {
      await orgGatewayUnregister(gatewayId.value);
      modalComponentRef.value?.hideView();
      getGatewayList();
    }
  });
};

const addGatewayDelete = (id: number) => {
  gatewayId.value = id;
  modalComponentRef.value?.showView();
};

const cancelSave = () => {
  gatewayEditor.value = false;
  if (gatewayId.value) {
    postLinkGetList(gatewayId.value);
  }
};

const addSave = () => {
  handleRequest(async () => {
    interfaceList.value.forEach((item) => {
      const {
        id,
        linkName,
        gatewayId,
        interfaceId,
        protocolType,
        bindState,
        dataBit,
        parityBit,
        stopBit,
        baudRate,
        readTimeout,
        nextDataReadDelay,
        nextRoundDataReadDelay,
      } = item;

      gatewayLinks.value.push({
        link: {
          id,
          linkName,
          gatewayId,
          interfaceId,
          protocolType,
          bindState,
          dataBit,
          parityBit,
          stopBit,
          baudRate,
          readTimeout,
          nextDataReadDelay,
          nextRoundDataReadDelay,
        },
        protocols: item.protocols,
      });
    });
    await addGatewayLinkBatchUpdate(gatewayLinks.value);

    gatewayEditor.value = false;
  });
};

const addGateway = () => {
  modalGuidanceRef.value?.showView();
};

const getProtocolData = () => {
  getGatewayList();
};

onMounted(() => {
  addGatewayList();
});
</script>

<template>
  <div>
    <AFlex justify="space-between">
      <div class="text-top">{{ $t('navigation.gatewayManage') }}</div>
      <div>
        <AButton type="primary" class="icon-button" @click="addGateway">
          <AFlex align="center">
            <SvgIcon name="plus" />
            <span> {{ $t('common.add') }} </span>
          </AFlex>
        </AButton>
      </div>
    </AFlex>

    <div class="gateway-content">
      <ARow>
        <ACol :span="12" class="gateway-left">
          <AFlex justify="space-between" align="center" class="gateway-left-top">
            <div class="gateway-left-top-text">{{ $t('navigation.gatewayList') }}</div>
            <AButton type="text" @click="refreshData" class="icon-button gateway-left-top-icon">
              <AFlex align="center">
                <SvgIcon name="refresh-o" />
                <span> {{ $t('registerGateway.refreshData') }} </span>
              </AFlex>
            </AButton>
          </AFlex>

          <AFlex justify="space-between" align="center" class="input-bottom">
            <div>
              <span class="gateway-left-text">{{ $t('common.search') }}</span>
              <AInput v-model:value="gatewayQuery.searchContent" placeholder="请输入序列号、型号" class="input-width" />
            </div>
            <div>
              <span class="gateway-left-text">{{ $t('common.status') }}</span>
              <ASelect class="select-width" v-model:value="gatewayQuery.state" placeholder="请选择">
                <ASelectOption :value="-1">{{ $t('common.all') }}</ASelectOption>
                <ASelectOption :value="1">{{ $t('common.online') }}</ASelectOption>
                <ASelectOption :value="0">{{ $t('common.offline') }}</ASelectOption>
              </ASelect>
            </div>
          </AFlex>

          <AFlex justify="flex-end">
            <AButton type="primary" class="query-button" @click="addGatewayList">{{ $t('common.query') }}</AButton>
            <AButton @click="addReset" class="default-button">{{ $t('common.reset') }}</AButton>
          </AFlex>

          <ATable
            :columns="gatewayColumns"
            :data-source="gatewayData"
            :row-key="(record) => record.id"
            :custom-row="rowClick"
            :pagination="false"
            :row-class-name="rowClassName"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.key === 'index'">
                {{ index + 1 }}
              </template>
              <template v-else-if="column.key === 'state'">
                <div v-if="record.state === 0" class="tag-style default">{{ $t('common.offline') }}</div>
                <div v-else class="tag-style success">{{ $t('common.online') }}</div>
              </template>
              <template v-else-if="column.key === 'action'">
                <SvgIcon @click="addGatewayDelete(record.id)" class="icon-delete" name="delete" />
              </template>
            </template>
          </ATable>

          <AFlex justify="flex-end" class="gateway-left-footer">
            <APagination
              v-model:current="gatewayQuery.pageIndex"
              v-model:page-size="gatewayQuery.pageSize"
              :total="gatewayQuery.total"
              :show-size-changer="true"
              @change="switchPages"
              show-quick-jumper
              :show-total="(total) => $t('common.pageTotal', { total })"
            />
          </AFlex>
        </ACol>
        <ACol :span="12" class="gateway-right">
          <AFlex justify="space-between" align="center" class="gateway-right-top">
            <div class="gateway-left-top-text">{{ $t('registerGateway.gatewayConfiguration') }}</div>
            <!-- 注释编辑功能 -->
            <div v-if="false">
              <div v-if="gatewayEditor">
                <AButton v-if="gatewayEditor" type="text" class="icon-button gateway-left-top-icon" @click="cancelSave">
                  <AFlex align="center">
                    <SvgIcon name="close" />
                    <span> {{ $t('common.cancel') }} </span>
                  </AFlex>
                </AButton>
                <AButton v-if="gatewayEditor" type="text" class="icon-button gateway-left-top-icon" @click="addSave">
                  <AFlex align="center">
                    <SvgIcon name="edit-o" />
                    <span> {{ $t('common.save') }} </span>
                  </AFlex>
                </AButton>
              </div>
              <div v-else>
                <AButton
                  v-if="!gatewayEditor"
                  type="text"
                  class="icon-button gateway-left-top-icon"
                  @click="gatewayEditor = true"
                  :disabled="!interfaceList.length"
                >
                  <AFlex align="center">
                    <SvgIcon name="edit-o" />
                    <span> {{ $t('common.editor') }} </span>
                  </AFlex>
                </AButton>
              </div>
            </div>
          </AFlex>
          <ACollapse v-model:active-key="activeKey" accordion v-if="interfaceList.length" collapsible="icon">
            <ACollapsePanel v-for="(item, index) in interfaceList" :key="item.id">
              <template #header>
                <span class="interface-text-right">{{ $t('createDevice.physicalInterface') }}: </span>
                <span v-if="!gatewayEditor">{{ item.linkName }}</span>
                <ASelect
                  v-else
                  v-model:value="item.interfaceId"
                  class="interface-select"
                  :options="interfaceSelectList"
                  :field-names="{ label: 'name', value: 'id' }"
                  @change="(value, option) => choosePhysicalInterface(value, option, item.interfaceId, item, index)"
                />
              </template>
              <AFlex align="center" class="gateway-type-bottom">
                <div class="gateway-right-text">{{ $t('setupProtocol.protocolType') }}:</div>
                <div>
                  <span v-if="!gatewayEditor">{{ item.protocolType }}</span>
                  <ASelect
                    v-else
                    v-model:value="item.protocolType"
                    class="interface-select"
                    :options="listPhysicalInterfaces"
                    :field-names="{ label: 'protocolName', value: 'protocolName' }"
                  />
                </div>
              </AFlex>

              <ATable :columns="agreementColumns" :data-source="item.protocols" :pagination="false">
                <!-- <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'station'">
                    <AInputNumber v-if="gatewayEditor" v-model:value="record.station" :min="0" />
                  </template>
                </template> -->
              </ATable>
            </ACollapsePanel>
          </ACollapse>
        </ACol>
      </ARow>
    </div>
    <ModalGuidance ref="modalGuidance" @finish="getProtocolData">
      <RegisterGateway />
    </ModalGuidance>
    <ConfirmModal
      ref="modalComponent"
      :title="$t('common.deleteConfirmation')"
      :description-text="$t('common.confirmDeletion')"
      :icon="{ name: 'delete' }"
      :icon-bg-color="'#F56C6C'"
      @confirm="confirm"
    />
  </div>
</template>

<style lang="scss" scoped>
.success {
  width: 40px;
  color: #52c41a;
  background: #f6ffed;
  border: 1px solid #b7eb8f;
}

.default {
  width: 40px;
  color: #666;
  background: #f8f8f8;
  border: 1px solid #e5e5e5;
}

.tag-style {
  display: flex;
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  height: 24px;
  font-size: 12px;
  border-radius: 4px;
}

/* 添加选中行样式 */
:deep(.selected-row) td {
  background-color: #e0f5f5 !important;
}

.gateway-type-bottom {
  margin-bottom: 12px;
}

.interface-text-right {
  margin-right: 10px;
}

.interface-select {
  width: 192px;
}

.icon-delete {
  font-size: 21px;
  color: var(--antd-color-primary-hover);
  cursor: pointer;
}

.gateway-left-footer {
  margin-top: 24px;
}

.gateway-right-text {
  margin-right: 10px;
  font-size: 14px;
  font-style: normal;
  font-weight: 500;
  line-height: 24px;
  color: rgb(0 0 0 / 85%);
  text-align: left;
}

.gateway-right-top {
  margin-bottom: 16px;
}

.query-button {
  margin-right: 12px;
  margin-bottom: 16px;
}

.input-bottom {
  margin-bottom: 16px;
}

.select-width {
  width: 192px;
}

.input-width {
  width: 192px;
}

.gateway-left-text {
  margin-right: 12px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: rgb(0 0 0 / 85%);
  text-align: right;
}

.gateway-left-top-icon {
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
  color: #666;
  text-align: left;
}

.gateway-left-top-text {
  font-size: 16px;
  font-style: normal;
  font-weight: 600;
  line-height: 24px;
  color: #333;
  text-align: left;
}

.gateway-left-top {
  margin-bottom: 24px;
}

.gateway-left {
  padding: 24px;
}

.gateway-right {
  padding: 24px;
  border-left: 1px solid #e4e7ed;
}

.gateway-content {
  margin-top: 24px;
  background: #fff;
  border-radius: 16px;
}

.text-top {
  font-size: 20px;
  font-style: normal;
  font-weight: 500;
  line-height: 28px;
  color: rgb(0 0 0 / 85%);
  text-align: left;
}

.deletion-button {
  width: 84px;
  height: 32px;
  margin-right: 16px;
}
</style>
