<script setup lang="ts">
import { reactive, onMounted, toRaw } from 'vue';
import { message, Form, Modal } from 'ant-design-vue/lib';
import useI18n from '@/hooks/useI18n';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useNeInfoStore from '@/store/modules/neinfo';
import { addNeInfo, updateNeInfo, getTypeAndIDNeInfo } from '@/api/ne/neInfo';
import { NE_TYPE_LIST } from '@/constants/ne-constants';
import { stepState } from '../hooks/useStep';
const { t } = useI18n();
const emit = defineEmits(['next']);

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**新增框或修改框是否显示 */
  visibleByEdit: boolean;
  /**标题 */
  title: string;
  /**表单数据 */
  from: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  visibleByEdit: false,
  title: '网元',
  from: {
    id: undefined,
    neId: '001',
    neType: 'OMC',
    neName: '',
    ip: '',
    port: 3030,
    pvFlag: 'PNF',
    rmUid: '4400HX1OMC001',
    neAddress: '',
    dn: '',
    vendorName: '',
    province: '',
    // 主机
    hosts: [
      {
        hostId: undefined,
        hostType: 'ssh',
        groupId: '1',
        title: 'SSH_NE_22',
        addr: '',
        port: 22,
        user: 'user',
        authMode: '0',
        password: 'user',
        privateKey: '',
        passPhrase: '',
        remark: '',
      },
      {
        hostId: undefined,
        hostType: 'telnet',
        groupId: '1',
        title: 'Telnet_NE_4100',
        addr: '',
        port: 4100,
        user: 'user',
        authMode: '0',
        password: 'user',
        remark: '',
      },
    ],
  },
  confirmLoading: false,
});

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    neType: [
      {
        required: true,
        message: '请输入网元类型',
      },
    ],
    neId: [
      {
        required: true,
        message: '请输入网元标识',
      },
    ],
    rmUid: [
      {
        required: true,
        message: '请输入资源唯一标识',
      },
    ],
    ip: [
      {
        required: true,
        message: '请输入网元IP地址',
      },
    ],
    neName: [
      {
        required: true,
        message: '请输入网元名称',
      },
    ],
  })
);

/**测试连接检查信息 */
function fnNeInfo() {
  const from = toRaw(modalState.from);
  modalStateFrom
    .validate()
    .then(e => {
      modalState.confirmLoading = true;
      return getTypeAndIDNeInfo(from.neType, from.neId);
    })
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        message.warning({
          content: `${from.neType} 已存在网元标识：${from.neId} ，资源唯一标识：${from.rmUid}`,
          duration: 3,
        });
        from.id = res.data.id;
        from.hostIds = res.data.hostIds;
        const hostIds = res.data.hostIds.split(',');
        if (hostIds.length == 2) {
          from.hosts[0].hostId = hostIds[0];
          from.hosts[1].hostId = hostIds[1];
        }
        return true;
      } else {
        message.success({
          content: `${from.neType} 可使用网元标识：${from.neId}`,
          duration: 3,
        });
        return false;
      }
    })
    .then(state => {
      let confirmTitle = '新增提示';
      let confirmContent = '是否新增为新的网元信息并继续？';
      if (state) {
        confirmTitle = '更新提示';
        confirmContent = '是否更新替换已存在网元信息并继续？';
      }
      Modal.confirm({
        title: confirmTitle,
        content: confirmContent,
        okText: '确认',
        cancelText: '取消',
        onCancel: () => {
          from.id = undefined;
        },
        onOk: () => {
          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) {
                message.success({
                  content: '操作成功',
                  duration: 3,
                });
                // 刷新缓存的网元信息
                useNeInfoStore()
                  .fnRefreshNelist()
                  .then(neRes => {
                    const itemNe = neRes.data.find(
                      (item: any) =>
                        item.neType === from.neType && item.neId === from.neId
                    );
                    if (itemNe) {
                      Object.assign(from, itemNe);
                      // 记录当前步骤状态信息
                      stepState.states[stepState.current] = { from };
                      stepState.stepNext = true;
                    }
                  });
              } else {
                message.error({
                  content: `${t('views.configManage.neManage.operFail')}`,
                  duration: 3,
                });
              }
            })
            .finally(() => {
              hide();
              modalState.confirmLoading = false;
            });
        },
      });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    })
    .finally(() => {
      modalState.confirmLoading = false;
    });
}

onMounted(() => {
  // 读取步骤：环境检查
  const stepPrevFrom = stepState.states[0].from;
  modalState.from.ip = stepPrevFrom.addr;
  Object.assign(modalState.from.hosts[0], stepPrevFrom);
  Object.assign(modalState.from.hosts[1], {
    addr: stepPrevFrom.addr,
    user: 'admin',
    password: 'admin',
  });
});
</script>

<template>
  <a-form
    name="modalStateFrom"
    layout="horizontal"
    :label-col="{ span: 6 }"
    :labelWrap="true"
  >
    <a-row :gutter="16">
      <a-col :lg="12" :md="12" :xs="24">
        <a-form-item
          :label="t('views.configManage.neManage.neType')"
          name="neType"
          v-bind="modalStateFrom.validateInfos.neType"
        >
          <a-auto-complete
            v-model:value="modalState.from.neType"
            :options="NE_TYPE_LIST.map(v => ({ value: v }))"
          >
            <a-input
              allow-clear
              :placeholder="t('common.inputPlease')"
              :maxlength="32"
            >
              <template #prefix>
                <a-tooltip placement="topLeft">
                  <template #title>
                    {{ t('views.configManage.neManage.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.configManage.neManage.pvflag')"
          name="pvFlag"
          v-bind="modalStateFrom.validateInfos.pvFlag"
        >
          <a-select v-model:value="modalState.from.pvFlag" default-value="PNF">
            <a-select-opt-group :label="t('views.configManage.neManage.pnf')">
              <a-select-option value="PNF">PNF</a-select-option>
            </a-select-opt-group>
            <a-select-opt-group :label="t('views.configManage.neManage.vnf')">
              <a-select-option value="VNF">VNF</a-select-option>
            </a-select-opt-group>
          </a-select>
        </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.configManage.neManage.neId')"
          name="neId"
          v-bind="modalStateFrom.validateInfos.neId"
        >
          <a-input
            v-model:value="modalState.from.neId"
            allow-clear
            :placeholder="t('common.inputPlease')"
            :maxlength="32"
          ></a-input>
        </a-form-item>
      </a-col>
      <a-col :lg="12" :md="12" :xs="24">
        <a-form-item
          :label="t('views.configManage.neManage.neName')"
          name="neName"
          v-bind="modalStateFrom.validateInfos.neName"
        >
          <a-input
            v-model:value="modalState.from.neName"
            allow-clear
            :placeholder="t('common.inputPlease')"
            :maxlength="64"
          >
          </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.configManage.neManage.ip')"
          name="ip"
          v-bind="modalStateFrom.validateInfos.ip"
        >
          <a-input
            v-model:value="modalState.from.ip"
            allow-clear
            :disabled="true"
            :placeholder="t('common.inputPlease')"
            :maxlength="128"
          >
            <template #prefix>
              <a-tooltip placement="topLeft">
                <template #title>
                  <div>
                    {{ t('views.ne.neInfo.ipAddr') }}
                  </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-form-item
          :label="t('views.configManage.neManage.port')"
          name="port"
          v-bind="modalStateFrom.validateInfos.port"
        >
          <a-input-number
            v-model:value="modalState.from.port"
            style="width: 100%"
            :min="1"
            :max="65535"
            placeholder="<=65535"
          >
            <template #prefix>
              <a-tooltip placement="topLeft">
                <template #title>
                  <div>{{ t('views.configManage.neManage.portTip') }}</div>
                </template>
                <InfoCircleOutlined style="color: rgba(0, 0, 0, 0.45)" />
              </a-tooltip>
            </template>
          </a-input-number>
        </a-form-item>
      </a-col>
    </a-row>

    <a-form-item
      :label="t('views.configManage.neManage.uid')"
      name="rmUid"
      v-bind="modalStateFrom.validateInfos.rmUid"
      :label-col="{ span: 3 }"
      :labelWrap="true"
    >
      <a-input
        v-model:value="modalState.from.rmUid"
        allow-clear
        :placeholder="t('common.inputPlease')"
        :maxlength="40"
      >
        <template #prefix>
          <a-tooltip placement="topLeft">
            <template #title>
              <div>
                {{ t('views.ne.neInfo.rmUID') }}
              </div>
            </template>
            <InfoCircleOutlined style="color: rgba(0, 0, 0, 0.45)" />
          </a-tooltip>
        </template>
      </a-input>
    </a-form-item>

    <a-row :gutter="16">
      <a-col :lg="12" :md="12" :xs="24">
        <a-form-item
          :label="t('views.configManage.neManage.mac')"
          name="neAddress"
        >
          <a-input
            v-model:value="modalState.from.neAddress"
            allow-clear
            :placeholder="t('common.inputPlease')"
            :maxlength="64"
          >
            <template #prefix>
              <a-tooltip placement="topLeft">
                <template #title>
                  <div>{{ t('views.configManage.neManage.macTip') }}</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-form-item :label="t('views.configManage.neManage.dn')" name="dn">
          <a-input
            v-model:value="modalState.from.dn"
            allow-clear
            :placeholder="t('common.inputPlease')"
            :maxlength="255"
          ></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.configManage.neManage.vendorName')"
          name="vendorName"
        >
          <a-input
            v-model:value="modalState.from.vendorName"
            allow-clear
            :placeholder="t('common.inputPlease')"
            :maxlength="64"
          >
          </a-input>
        </a-form-item>
      </a-col>
      <a-col :lg="12" :md="12" :xs="24">
        <a-form-item
          :label="t('views.configManage.neManage.province')"
          name="province"
        >
          <a-input
            v-model:value="modalState.from.province"
            allow-clear
            :placeholder="t('common.inputPlease')"
            :maxlength="32"
          ></a-input>
        </a-form-item>
      </a-col>
    </a-row>

    <a-form-item :wrapper-col="{ span: 14, offset: 3 }">
      <a-button
        type="primary"
        html-type="submit"
        @click="fnNeInfo()"
        :loading="modalState.confirmLoading"
      >
        检查信息
      </a-button>
    </a-form-item>
  </a-form>
</template>

<style lang="less" scoped></style>
