<script setup lang="ts">
import { Modal, message } from 'ant-design-vue/lib';
import { onMounted, reactive, toRaw } from 'vue';
import {
  addNeInfo,
  delNeInfo,
  listAllNeInfo,
  updateNeInfo,
} from '@/api/ne/neInfo';
import { neHostAuthorizedRSA, testNeHost } from '@/api/ne/neHost';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { NE_TYPE_LIST } from '@/constants/ne-constants';
import { regExpIPv4, regExpIPv6 } from '@/utils/regular-utils';
import { fnToStepName } from '../hooks/useStep';
import useI18n from '@/hooks/useI18n';
import useDictStore from '@/store/modules/dict';
const { getDict } = useDictStore();
const { t } = useI18n();

/**字典数据 */
let dict: {
  /**主机类型 */
  neHostType: DictType[];
  /**分组 */
  neHostGroupId: DictType[];
  /**认证模式 */
  neHostAuthMode: DictType[];
} = reactive({
  neHostType: [],
  neHostGroupId: [],
  neHostAuthMode: [],
});

/**标签对象信息状态类型 */
type TabStateType = {
  /**激活选中 */
  activeKey: string;
  /**页签数据 */
  panes: Record<string, any>[];
  /**等待loading */
  confirmLoading: boolean;
};

/**标签对象信息状态 */
const tabState: TabStateType = reactive({
  activeKey: 'neType@neId',
  panes: [],
  confirmLoading: false,
});

/**
 * 导航标签关闭
 * @param id 标签的key
 */
function fnTabClose(key: string) {
  // 获取当前项下标
  const tabIndex = tabState.panes.findIndex(tab => tab.key === key);
  if (tabIndex === -1) return;
  const item = tabState.panes[tabIndex];
  Modal.confirm({
    title: t('common.tipTitle'),
    content: `${item.data.neName} ${t('views.ne.neInfo.delTip')}`,
    onOk() {
      if (item.data.id) delNeInfo(item.data.id);

      tabState.panes.splice(tabIndex, 1);
      // 激活前一项标签
      const idx = tabIndex === 0 ? 0 : tabIndex - 1;
      tabState.activeKey = tabState.panes[idx].id;
    },
  });
}

/**新建网元信息 */
function fnTabCreate() {
  const neId = `${new Date().getMilliseconds()}`.padStart(3, '0');
  tabState.panes.push({
    key: `New@${neId}`,
    data: {
      id: undefined,
      neId: neId,
      neType: '',
      neName: `New_${neId}`,
      ip: '',
      port: 33030,
      pvFlag: 'PNF',
      rmUid: `4400HXNew${neId}`,
      neAddress: '',
      dn: '-',
      vendorName: '-',
      province: '-',
      // 主机
      hosts: [
        {
          hostId: undefined,
          hostType: 'ssh',
          groupId: '1',
          title: 'SSH_NE_22',
          addr: '',
          port: 22,
          user: '',
          authMode: '0',
          password: '',
          privateKey: '',
          passPhrase: '',
          remark: '',
        },
        {
          hostId: undefined,
          hostType: 'telnet',
          groupId: '1',
          title: 'Telnet_NE_4100',
          addr: '',
          port: 4100,
          user: 'admin',
          authMode: '0',
          password: 'admin',
          remark: '',
        },
      ],
    },
    status: false,
  });
  tabState.activeKey = `New@${neId}`;
}

/**
 * 测试主机连接
 */
function fnHostTest(row: Record<string, any>) {
  if (tabState.confirmLoading || !row.addr) return;
  tabState.confirmLoading = true;
  const hide = message.loading(t('common.loading'), 0);
  testNeHost(row)
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success({
          content: `${row.addr}:${row.port} ${t('views.ne.neHost.testOk')}`,
          duration: 2,
        });
      } else {
        message.error({
          content: `${row.addr}:${row.port} ${res.msg}`,
          duration: 2,
        });
      }
    })
    .finally(() => {
      hide();
      tabState.confirmLoading = false;
    });
}

/**测试主机连接-免密直连 */
function fnHostAuthorized(row: Record<string, any>) {
  if (tabState.confirmLoading || !row.addr) return;

  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.ne.neHost.authRSATip'),
    onOk: () => {
      tabState.confirmLoading = true;
      neHostAuthorizedRSA(row).then(res => {
        tabState.confirmLoading = false;
        if (res.code === RESULT_CODE_SUCCESS) {
          message.success(t('common.operateOk'), 3);
        } else {
          message.error(t('common.operateErr'), 3);
        }
      });
    },
  });
}

/**
 * 表单修改网元类型
 */
function fnNeTypeChange(v: any, data: any) {
  const hostsLen = data.hosts.length;
  // 网元默认只含22和4100
  if (hostsLen === 3 && v !== 'UPF') {
    data.hosts.pop();
  }
  // UPF标准版本可支持5002
  if (hostsLen === 2 && v === 'UPF') {
    data.hosts.push({
      hostId: undefined,
      hostType: 'telnet',
      groupId: '1',
      title: 'Telnet_NE_5002',
      addr: '',
      port: 5002,
      user: 'admin',
      authMode: '0',
      password: 'admin',
      remark: '',
    });
  }
}

/**
 * 表单修改网元IP
 */
function fnNeIPChange(e: any, data: any) {
  const v = e.target.value;
  if (v.length < 7) return;
  for (const host of data.hosts) {
    host.addr = v;
  }
}

/**表单验证IP地址是否有效 */
function modalStateFromEqualIPV4AndIPV6(
  rule: Record<string, any>,
  value: string,
  callback: (error?: string) => void
) {
  if (!value) {
    return Promise.reject(t('views.ne.common.ipAddrPlease'));
  }

  if (value.indexOf('.') === -1 && value.indexOf(':') === -1) {
    return Promise.reject(t('valid.ipPlease'));
  }
  if (value.indexOf('.') !== -1 && !regExpIPv4.test(value)) {
    return Promise.reject(t('valid.ipv4Reg'));
  }
  if (value.indexOf(':') !== -1 && !regExpIPv6.test(value)) {
    return Promise.reject(t('valid.ipv6Reg'));
  }
  return Promise.resolve();
}

/**保存信息 */
function fnSaveFinish(pane: any) {
  tabState.confirmLoading = true;
  const from = toRaw(pane);
  from.rmUid = `4400HX${from.neType}${from.neId}`; // 4400HX1AMF001
  from.neName = `${from.neType}_${from.neId}`; // AMF_001
  const result = from.id ? updateNeInfo(from) : addNeInfo(from);
  const hide = message.loading(t('common.loading'), 0);
  result
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        if (res.data) {
          pane.id = res.data;
        }

        const tabItem = tabState.panes.find(
          tab => tab.key === tabState.activeKey
        );
        if (tabItem) {
          tabItem.status = false;
          tabItem.data.neName = from.neName;
          tabItem.status = true;
        }
        message.success({
          content: t('common.operateOk'),
          duration: 3,
        });
      } else {
        const tabItem = tabState.panes.find(
          tab => tab.key === tabState.activeKey
        );
        if (tabItem) {
          tabItem.status = true;
          tabItem.data.neName = from.neName;
          tabItem.status = false;
        }
        message.error({
          content: `${res.msg}`,
          duration: 3,
        });
      }
    })
    .finally(() => {
      hide();
      tabState.confirmLoading = false;
    });
}

/**保存信息有错误的情况 */
function fnSaveFinishFailed(e: any) {
  message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
}

/**返回上一步 */
function fnStepPrev() {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.system.quickStart.stepNeInfoStepPrev'),
    onOk() {
      fnToStepName('SystemConfig');
    },
  });
}

/**下一步操作 */
function fnStepNext(stepName: 'NeInfoConfigPara5G') {
  if (stepName === 'NeInfoConfigPara5G') {
    Modal.confirm({
      title: t('common.tipTitle'),
      content: t('views.system.quickStart.stepNeInfoStepNext'),
      onOk() {
        fnToStepName('NeInfoConfigPara5G');
      },
    });
  }
}

/**获取列表 */
function fnGetList() {
  listAllNeInfo({
    bandHost: true,
  }).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
      for (const item of res.data) {
        if (item.neType === 'OMC' || !Array.isArray(item.hosts)) continue;
        tabState.panes.push({
          key: `${item.neType}@${item.neId}`,
          data: item,
          status: false,
        });
      }
      // 没有终端信息时，新建一个占位
      if (tabState.panes.length === 0) {
        fnTabCreate();
      }
      // 选择首个
      if (tabState.panes.length > 0) {
        tabState.activeKey = tabState.panes[0].key;
      }
    }
  });
}

onMounted(() => {
  // 初始字典数据
  Promise.allSettled([
    getDict('ne_host_type'),
    getDict('ne_host_groupId'),
    getDict('ne_host_authMode'),
  ])
    .then(resArr => {
      if (resArr[0].status === 'fulfilled') {
        dict.neHostType = resArr[0].value;
      }
      if (resArr[1].status === 'fulfilled') {
        dict.neHostGroupId = resArr[1].value;
      }
      if (resArr[2].status === 'fulfilled') {
        dict.neHostAuthMode = resArr[2].value;
      }
    })
    .finally(() => {
      fnGetList();
    });
});
</script>

<template>
  <div class="ne">
    <a-tabs
      class="neinfo-tabs"
      hide-add
      tab-position="top"
      type="editable-card"
      :tab-bar-gutter="8"
      :tab-bar-style="{ margin: '0' }"
      v-model:activeKey="tabState.activeKey"
      @edit="(key:any) => fnTabClose(key as string)"
    >
      <template #rightExtra>
        <a-space :size="8" align="center">
          <a-tooltip placement="topRight">
            <template #title>
              {{ t('views.ne.neInfo.addTitle') }}
            </template>
            <a-button type="default" shape="circle" @click="fnTabCreate()">
              <template #icon><PlusOutlined /></template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>

      <a-tab-pane
        v-for="pane in tabState.panes"
        :key="pane.key"
        :closable="tabState.panes.length > 1"
      >
        <template #tab>
          <a-badge
            :status="pane.status ? 'success' : 'default'"
            :text="pane.data.neName"
          />
        </template>

        <!-- {{ pane.data }} -->
        <a-form
          :name="pane.key"
          layout="horizontal"
          :model="pane.data"
          :label-col="{ span: 6 }"
          :labelWrap="true"
          autocomplete="off"
          @finish="fnSaveFinish(pane.data)"
          @finishFailed="fnSaveFinishFailed"
        >
          <a-row :gutter="16">
            <a-col :lg="12" :md="12" :xs="24">
              <a-form-item
                :label="t('views.ne.common.neType')"
                name="neType"
                :rules="{
                  required: true,
                  message: t('views.ne.common.neTypePlease'),
                }"
              >
                <a-auto-complete
                  v-model:value="pane.data.neType"
                  :options="
                    NE_TYPE_LIST.filter(s => s !== 'OMC').map(v => ({
                      value: v,
                    }))
                  "
                  @change="(v:any) => fnNeTypeChange(v, pane.data)"
                >
                  <a-input
                    allow-clear
                    :placeholder="t('views.ne.common.neTypePlease')"
                    :maxlength="32"
                  >
                    <template #prefix>
                      <a-tooltip placement="topLeft">
                        <template #title>
                          {{ t('views.ne.common.neTypeTip') }}
                        </template>
                        <InfoCircleOutlined
                          style="color: rgba(0, 0, 0, 0.45)"
                        />
                      </a-tooltip>
                    </template>
                  </a-input>
                </a-auto-complete>
              </a-form-item>
            </a-col>
            <a-col :lg="12" :md="12" :xs="24">
              <a-form-item
                :label="t('views.ne.common.neId')"
                name="neId"
                :rules="{
                  required: true,
                  message: t('views.ne.common.neIdPlease'),
                }"
              >
                <a-input
                  v-model:value="pane.data.neId"
                  allow-clear
                  :placeholder="t('views.ne.common.neIdPlease')"
                  :maxlength="24"
                >
                  <template #prefix>
                    <a-tooltip placement="topLeft">
                      <template #title>
                        {{ t('views.ne.common.neIdTip') }}
                      </template>
                      <InfoCircleOutlined style="color: rgba(0, 0, 0, 0.45)" />
                    </a-tooltip>
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :lg="12" :md="12" :xs="24">
              <a-form-item
                :label="t('views.ne.common.ipAddr')"
                name="ip"
                :rules="{
                  required: true,
                  validator: modalStateFromEqualIPV4AndIPV6,
                }"
              >
                <a-input
                  v-model:value="pane.data.ip"
                  allow-clear
                  :placeholder="t('views.ne.common.ipAddrPlease')"
                  :maxlength="128"
                  @change="(e:any) => fnNeIPChange(e, pane.data)"
                >
                  <template #prefix>
                    <a-tooltip placement="topLeft">
                      <template #title>
                        <div>
                          {{ t('views.ne.common.ipAddrTip') }}
                        </div>
                      </template>
                      <InfoCircleOutlined style="color: rgba(0, 0, 0, 0.45)" />
                    </a-tooltip>
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col :lg="12" :md="12" :xs="24"> </a-col>
          </a-row>

          <template v-if="pane.data.hosts.length > 0">
            <a-divider orientation="left">
              {{ t('views.ne.neInfo.hostConfig') }}
            </a-divider>

            <!-- 主机连接配置 -->
            <a-row :gutter="16">
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('views.ne.neHost.addr')">
                  <a-input
                    v-model:value="pane.data.hosts[0].addr"
                    allow-clear
                    :maxlength="128"
                    :placeholder="t('common.inputPlease')"
                  >
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('views.ne.neHost.port')" name="port">
                  <a-input-number
                    v-model:value="pane.data.hosts[0].port"
                    :min="10"
                    :max="65535"
                    :step="1"
                    :maxlength="5"
                    :placeholder="t('common.inputPlease')"
                    style="width: 100%"
                  ></a-input-number>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('views.ne.neHost.user')">
                  <a-input
                    v-model:value="pane.data.hosts[0].user"
                    allow-clear
                    :maxlength="32"
                    :placeholder="t('common.inputPlease')"
                  >
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :lg="12" :md="12" :xs="24">
                <a-form-item :label="t('views.ne.neHost.authMode')">
                  <a-select
                    v-model:value="pane.data.hosts[0].authMode"
                    default-value="0"
                    :options="dict.neHostAuthMode"
                  >
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>

            <a-form-item
              v-if="pane.data.hosts[0].authMode === '0'"
              :label="t('views.ne.neHost.password')"
              :label-col="{ span: 3 }"
              :label-wrap="true"
            >
              <a-input-password
                v-model:value="pane.data.hosts[0].password"
                :maxlength="128"
                :placeholder="t('common.inputPlease')"
              >
              </a-input-password>
            </a-form-item>

            <template v-if="pane.data.hosts[0].authMode === '1'">
              <a-form-item
                :label="t('views.ne.neHost.privateKey')"
                :label-col="{ span: 3 }"
                :label-wrap="true"
              >
                <a-textarea
                  v-model:value="pane.data.hosts[0].privateKey"
                  :auto-size="{ minRows: 4, maxRows: 6 }"
                  :maxlength="3000"
                  :show-count="true"
                  :placeholder="t('views.ne.neHost.privateKeyPlease')"
                />
              </a-form-item>

              <a-form-item
                :label="t('views.ne.neHost.passPhrase')"
                :label-col="{ span: 3 }"
                :label-wrap="true"
              >
                <a-input-password
                  v-model:value="pane.data.hosts[0].passPhrase"
                  :maxlength="128"
                  :placeholder="t('common.inputPlease')"
                >
                </a-input-password>
              </a-form-item>
            </template>

            <a-form-item
              :label="t('views.ne.neHost.test')"
              name="test"
              :label-col="{ span: 3 }"
              :label-wrap="true"
            >
              <a-button
                type="dashed"
                shape="round"
                @click="fnHostTest(pane.data.hosts[0])"
                :disabled="tabState.confirmLoading"
              >
                <template #icon><LinkOutlined /></template>
              </a-button>

              <a-button
                type="link"
                @click="fnHostAuthorized(pane.data.hosts[0])"
                :disabled="tabState.confirmLoading"
                v-if="
                  pane.data.hosts[0].hostType === 'ssh' &&
                  pane.data.hosts[0].authMode !== '2'
                "
              >
                {{ t('views.ne.neHost.authRSA') }}
              </a-button>
            </a-form-item>
          </template>

          <a-form-item :wrapper-col="{ offset: 10, span: 4 }">
            <a-button
              type="primary"
              ghost
              html-type="submit"
              :disabled="tabState.confirmLoading"
            >
              {{ t('views.system.quickStart.save') }}
            </a-button>
          </a-form-item>
        </a-form>
      </a-tab-pane>
    </a-tabs>

    <div class="ne-oper">
      <a-space direction="horizontal" :size="18">
        <a-button @click="fnStepPrev()" :disabled="tabState.confirmLoading">
          {{ t('views.system.quickStart.exit') }}
        </a-button>

        <a-button
          type="primary"
          @click="fnStepNext('NeInfoConfigPara5G')"
          :disabled="tabState.confirmLoading"
        >
          {{ t('views.system.quickStart.stepNext') }}
        </a-button>
      </a-space>
    </div>
  </div>
</template>

<style lang="less" scoped>
.neinfo-tabs :deep(.ant-tabs-tabpane) {
  padding: 24px;
  height: 60vh;
  overflow-y: auto;
  overflow-x: hidden;
  // margin-bottom: 24px;
  // margin-top: 24px;
}

.ne {
  padding-top: 12px;
  // height: 78vh;
  overflow-x: hidden;
  overflow-y: auto;

  &-oper {
    padding-top: 24px;
    text-align: end;
  }
}
</style>
