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

import ConfirmModal from '@/components/ConfirmModal.vue';
import SvgIcon from '@/components/SvgIcon.vue';
import { useRequest } from '@/hooks/request';
import { t } from '@/i18n';
import {
  gatewayLinkAdd,
  gatewayLinkDelete,
  gatewayLinkGetList,
  obtainListInterfaces,
  obtainListPhysicalInterfaces,
} from '@/api';
import { IS_USED_IN_MODAL_GUIDANCE } from '@/constants/inject-key';

import deviceInterface from '@/assets/img/device-interface.png';

import type { FormInstance } from 'ant-design-vue';
import type { Rule } from 'ant-design-vue/es/form';
import type {
  InterfaceData,
  ListInterfaces,
  ListPhysicalInterfaces,
  RegisterGatewayForm,
  UseGuideStepItemProps,
} from '@/types';

const isUsedInModalGuidance = inject(IS_USED_IN_MODAL_GUIDANCE, false);
const formRef = ref<FormInstance>();
const props = defineProps<UseGuideStepItemProps<RegisterGatewayForm>>();
const modalComponentRef = useTemplateRef('modalComponent');
const currentStep = props.steps[props.stepIndex];
const interfaceId = ref<number>();
const interfaceList = ref<ListInterfaces[]>([]);
const protocolName = ref<string>('');
const linkName = ref<string>('');

const listPhysicalInterfaces = ref<ListPhysicalInterfaces[]>([]);

const { handleRequest } = useRequest();

const rules: Record<string, Rule[]> = {
  interfaceId: [
    {
      required: true,
      message: t('registerGateway.pleaseSelectInterface'),
      trigger: 'change',
    },
  ],
  protocolId: [
    {
      required: true,
      message: t('setupProtocol.plzSelectProtocolType'),
      trigger: 'change',
    },
  ],
};
interface InterfaceStyle {
  background: string;
  backgroundSize: string;
}

interface LeftStyle {
  left: string;
}

// 定义一个响应式变量来存储样式对象
const interfaceStyle = ref<InterfaceStyle>({
  background: `url(${deviceInterface})`,
  backgroundSize: '410px 120px',
});

const leftStyle = ref<LeftStyle>({
  left: '229px',
});

const interfaceData = ref<InterfaceData[]>([]);

const postGetList = () => {
  handleRequest(async () => {
    interfaceData.value = await gatewayLinkGetList(props.form.id);

    if (interfaceData.value.length) {
      currentStep.nextStepButtonDisabled = false;
    } else {
      currentStep.nextStepButtonDisabled = true;
    }
  });
};

// 根据条件显示背景
const interfaceShow = (value: string) => {
  return value === 'LAN' ? 'background-color: rgba(54, 207, 201, 1);' : 'background-color: rgba(89, 126, 247, 1);';
};

// 添加接口列表
const addInterface = () => {
  formRef.value?.validate().then(() => {
    interfaceList.value.forEach((item) => {
      if (item.id === props.form.interfaceId) {
        linkName.value = item.name;
      }
    });

    listPhysicalInterfaces.value.forEach((item) => {
      if (item.id === props.form.protocolId) {
        protocolName.value = item.protocolName;
      }
    });

    handleRequest(async () => {
      await gatewayLinkAdd({
        interfaceId: props.form.interfaceId,
        linkName: linkName.value,
        gatewayId: props.form.id,
        protocolType: protocolName.value,
      });
      postGetList();
    });
  });
};

const confirm = () => {
  handleRequest(async () => {
    if (interfaceId.value) {
      await gatewayLinkDelete(interfaceId.value);
      modalComponentRef.value?.hideView();
      postGetList();
    }
  });
};

// 删除接口
const addDelete = (value: number) => {
  interfaceId.value = value;
  modalComponentRef.value?.showView();
};

const getListPhysicalInterfaces = (value: number) => {
  handleRequest(async () => {
    listPhysicalInterfaces.value = await obtainListPhysicalInterfaces(value);
    if (listPhysicalInterfaces.value.length) {
      props.form.protocolId = listPhysicalInterfaces.value[0].id;
    } else {
      props.form.protocolId = undefined;
    }
  });
};

watch(
  () => props.form.interfaceId,
  (count) => {
    if (count) {
      if (count === 3) {
        leftStyle.value.left = '85px';
      } else if (count === 4) {
        leftStyle.value.left = '154px';
      } else if (count === 1) {
        leftStyle.value.left = '186px';
      } else if (count === 2) {
        leftStyle.value.left = '218px';
      }
      getListPhysicalInterfaces(count);
    }
  },
);

onMounted(() => {
  handleRequest(async () => {
    interfaceList.value = await obtainListInterfaces(props.form.modelId);
    if (interfaceList.value.length) {
      props.form.interfaceId = interfaceList.value[0].id;
      leftStyle.value.left = '85px';
      getListPhysicalInterfaces(interfaceList.value[0].id);
    }
    postGetList();
  });
});
</script>

<template>
  <div>
    <AFlex>
      <div class="interface-width">
        <AForm ref="formRef" :model="form" label-align="left" :rules="rules" :label-col="{ span: 8 }">
          <AFormItem :label="$t('registerGateway.selectInterface')" name="interfaceId">
            <ASelect
              ref="select"
              v-model:value="form.interfaceId"
              class="interface-select"
              :options="interfaceList"
              :field-names="{ label: 'name', value: 'id' }"
            />
          </AFormItem>

          <AFormItem :label="$t('setupProtocol.selectProtocolType')" name="protocolId">
            <ASelect
              ref="select"
              v-model:value="form.protocolId"
              class="interface-select"
              :field-names="{ label: 'protocolName', value: 'id' }"
              :options="listPhysicalInterfaces"
            />
          </AFormItem>
        </AForm>
      </div>

      <div :style="interfaceStyle" class="interface-img">
        <div v-if="form.interfaceId" class="interface-bgc" :style="leftStyle"></div>
      </div>
    </AFlex>
    <AButton class="dev-but" type="primary" @click="addInterface">{{ $t('common.add') }}</AButton>

    <div class="use-guide-title">{{ $t('registerGateway.interfaceList') }}</div>
    <AFlex v-if="interfaceData.length === 0" justify="center" align="center" class="empty-data">
      <div>
        <img src="@/assets/img/no-data.png" alt="" />
        <div class="empty-text">{{ $t('common.noData') }}</div>
      </div>
    </AFlex>
    <AFlex v-else :justify="isUsedInModalGuidance ? 'space-between' : ''" wrap="wrap">
      <AFlex
        v-for="item in interfaceData"
        :key="item.id"
        :class="isUsedInModalGuidance ? 'interface-modal' : 'interface-list'"
        align="center"
      >
        <AFlex class="interface-div" justify="space-between" align="center">
          <AFlex align="center">
            <AFlex class="interface-div1" :style="interfaceShow(item.interfaceType)" justify="center" align="center">
              <span class="interface-div1-span">{{ item.interfaceType }}</span>
            </AFlex>
            <div class="interface-div2">{{ item.linkName }}</div>
          </AFlex>

          <AFlex align="center">
            <div class="interface-agreement">{{ item.protocolType }}</div>
          </AFlex>
        </AFlex>

        <div @click="addDelete(item.id)">
          <AFlex class="interface-but" justify="center" align="center">
            <SvgIcon class="interface-but-icon" name="delete" />
          </AFlex>
        </div>
      </AFlex>
    </AFlex>
    <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>
.empty-text {
  margin-top: 16px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: #ccc;
}

.empty-data {
  width: 814px;
  height: 40vh;
  text-align: center;
}

.interface-width {
  width: 364px;
}

.interface-but-icon {
  font-size: 14px;
  color: #f56e6e;
}

.use-guide-title {
  margin-top: 40px;
  margin-bottom: 16px;
  font-size: 16px;
  font-style: normal;
  font-weight: 500;
  line-height: 24px;
  color: rgb(0 0 0 / 85%);
  text-align: left;
}

.dev-but {
  width: 96px;
  height: 40px;
  margin-top: 10px;
  border-radius: 3px;
}

.interface-select {
  width: 256px;
}

.interface-bgc {
  position: relative;
  top: 46px;
  width: 36px;
  height: 36px;
  background-color: rgb(82 196 26 / 35%);
  border-radius: 8px;
}

.interface-div {
  width: 458px;
  height: 72px;
  background: #f5f7fa;
  border-radius: 8px;
}

.interface-img {
  position: 'static';
  width: 410px;
  height: 120px;
  margin-left: 32px;
}

.interface-div1 {
  width: 48px;
  height: 48px;
  margin-left: 20px;
  border-radius: 4px;
}

.interface-div1-span {
  font-size: 16px;
  font-style: normal;
  font-weight: 400;
  line-height: 18px;
  color: rgb(255 255 255 / 97%);
}

.interface-div2 {
  margin-left: 20px;
  font-size: 16px;
  font-style: normal;
  font-weight: 500;
  line-height: 17px;
  color: var(--antd-color-text-secondary);
  text-align: left;
}

.interface-agreement {
  margin-top: 6px;
  margin-right: 24px;
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: 22px;
  color: #666;
  text-align: right;
}

.interface-but {
  width: 32px;
  height: 32px;
  margin-left: 16px;
  cursor: pointer;
  background: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
}

.interface-container {
  width: 565px;
  height: 410px;
}

.interface-list {
  margin-right: 80px;
  margin-bottom: 16px;
}

.interface-modal {
  margin-bottom: 16px;
}
</style>
