<script lang="ts" setup>
import { onMounted, reactive, toRaw } from 'vue';
import { PageContainer } from '@ant-design-vue/pro-layout';
import saveAs from 'file-saver';
import useNeInfoStore from '@/store/modules/neinfo';
import {
  RESULT_CODE_ERROR,
  RESULT_CODE_SUCCESS,
} from '@/constants/result-constants';
import useI18n from '@/hooks/useI18n';
import { message, Form } from 'ant-design-vue/lib';
import {
  tcpdumpNeTask,
  tcpdumpNeUPFTask,
  tcpdumpPcapDownload,
} from '@/api/traceManage/pcap';
import { ref } from 'vue';
const { t } = useI18n();

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**网元类型 */
  neType: string[];
  /**表单数据 */
  from: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
  /**执行日志 */
  execLogMsg: string;
  /**文件名 */
  fileName: string;
  /**下载文件按钮 */
  downBtn: boolean;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  neType: [],
  from: {
    ip: '',
    cmd: 'sctp or tcp port 8080 or 8088',
    timeout: 60,
    upfStart: 'pcap dispatch trace on max 100000',
    upfStop: 'pcap dispatch trace off',
  },
  confirmLoading: false,
  execLogMsg: '',
  fileName: '',
  downBtn: false,
});

/**网元类型选择对应修改 */
function fnNeChange(_: any, item: any) {
  modalState.from.ip = item[1].ip;
  modalState.execLogMsg = '';
  modalState.fileName = '';
  modalState.downBtn = false;
  runTime.value = 0;
}

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    cmd: [
      { required: true, message: t('views.traceManage.pcap.capArgPlease') },
    ],
    timeout: [
      { required: true, message: t('views.traceManage.pcap.capTimePlease') },
    ],
    upfStart: [
      { required: true, message: t('views.traceManage.pcap.capArgUPFPlease') },
    ],
    upfStop: [
      { required: true, message: t('views.traceManage.pcap.capArgUPFPlease') },
    ],
  })
);

// 创建 AbortController 实例
let controller = new AbortController();
let timeoutId: any = 0;
let runTime = ref<number>(0);

/**普通抓包执行 */
function fnStart() {
  modalStateFrom
    .validate(['cmd', 'timeout'])
    .then(() => {
      modalState.confirmLoading = true;
      const from = toRaw(modalState.from);
      const hide = message.loading(t('common.loading'), 0);
      controller = new AbortController();
      const signal = controller.signal;
      timeoutId = setInterval(() => {
        runTime.value++;
        if (runTime.value > from.timeout + 5) {
          clearInterval(timeoutId);
          runTime.value = 0;
          message.warning({
            content: t('views.traceManage.pcap.execTimeout'),
            duration: 3,
          });
          // 超时终止请求
          controller.abort();
        }
      }, 1000);

      tcpdumpNeTask(signal, {
        neType: modalState.neType[0],
        neId: modalState.neType[1],
        timeout: from.timeout,
        cmd: from.cmd,
      })
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('views.traceManage.pcap.execSuccess'),
              duration: 3,
            });
            let logmsg = res.data.cmd + '\n\n' + res.data.msg;
            logmsg = logmsg.replace(' \n', '\n\n');
            modalState.execLogMsg = logmsg;
            modalState.fileName = res.data.fileName;
            modalState.downBtn = true;
          } else if (
            res.code === RESULT_CODE_ERROR &&
            res.msg.includes('timeout')
          ) {
            message.warning({
              content: t('views.traceManage.pcap.execBreak'),
              duration: 3,
            });
          } else {
            message.error({
              content: t('views.traceManage.pcap.execFailed'),
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          clearInterval(timeoutId);
          runTime.value = 0;
          modalState.confirmLoading = false;
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

/**普通抓包中断 */
function fnStop() {
  controller.abort(); // 终止请求
  clearInterval(timeoutId);
  runTime.value = 0;
}

/**下载PCAP文件 */
function fnDownPCAP() {
  if (!modalState.fileName) {
    message.warning({
      content: t('views.traceManage.pcap.noFileName'),
      duration: 2,
    });
    return;
  }
  const key = 'tcpdumpPcapDownload';
  message.loading({ content: t('common.loading'), key });
  tcpdumpPcapDownload({
    neType: modalState.neType[0],
    neId: modalState.neType[1],
    fileName: modalState.fileName,
  }).then(res => {
    if (res.code === RESULT_CODE_SUCCESS) {
      message.success({
        content: t('views.traceManage.pcap.execSuccess'),
        key,
        duration: 3,
      });
      saveAs(res.data, modalState.fileName);
    } else {
      message.error({
        content: `${res.msg}`,
        key,
        duration: 3,
      });
    }
  });
}

/**UPF抓包执行 */
function fnUPF(runType: 'start' | 'stop') {
  modalStateFrom
    .validate([runType === 'start' ? 'upfStart' : 'upfStop'])
    .then(() => {
      modalState.confirmLoading = true;
      const from = toRaw(modalState.from);
      const hide = message.loading(t('common.loading'), 0);
      tcpdumpNeUPFTask({
        neType: modalState.neType[0],
        neId: modalState.neType[1],
        runType: runType === 'start' ? 'start_str' : 'stop_str',
        cmd: runType === 'start' ? from.upfStart : from.upfStop,
      })
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            let logmsg = res.data.cmd + '\n\n' + res.data.msg;
            logmsg = logmsg.replace(' \n', '\n\n');
            modalState.execLogMsg = logmsg;
            modalState.fileName = res.data.fileName;
            if (runType === 'start') {
              if (res.data.msg.includes('already')) {
                message.warning({
                  content: t('views.traceManage.pcap.execUPFStartA'),
                  duration: 10,
                });
              } else {
                message.success({
                  content: t('views.traceManage.pcap.execUPFStart'),
                  duration: 10,
                });
              }
            }
            if (runType === 'stop') {
              if (res.data.msg.includes('already')) {
                message.warning({
                  content: t('views.traceManage.pcap.execUPFStopA'),
                  duration: 10,
                });
              } else {
                message.success({
                  content: t('views.traceManage.pcap.execUPFStop'),
                  duration: 10,
                });
                modalState.downBtn = true;
              }
            }
          } else {
            message.error({
              content: t('views.traceManage.pcap.execFailed'),
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

onMounted(() => {
  // 获取网元网元列表
  useNeInfoStore()
    .fnNelist()
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
        if (res.data.length > 0) {
          const info = res.data[0];
          modalState.neType = [info.neType, info.neId];
          modalState.from.ip = info.ip;
        }
      } else {
        message.warning({
          content: 'No Data',
          duration: 2,
        });
      }
    });
});
</script>

<template>
  <PageContainer>
    <a-card :title="t('views.traceManage.pcap.cardTitle')">
      <a-row :gutter="16">
        <a-col :lg="12" :md="12" :xs="24">
          <a-form
            name="modalState"
            :model="modalState"
            layout="horizontal"
            autocomplete="off"
            :label-col="{ span: 5 }"
            labelWrap
          >
            <a-form-item
              :label="t('views.traceManage.pcap.neType')"
              name="neType"
            >
              <a-cascader
                v-model:value="modalState.neType"
                :options="useNeInfoStore().getNeCascaderOtions"
                @change="fnNeChange"
                :allow-clear="false"
                :placeholder="t('views.traceManage.pcap.neTypePlease')"
              />
            </a-form-item>
            <a-form-item :label="t('views.traceManage.pcap.neIp')" name="ip">
              <span style="font-weight: bold">{{ modalState.from.ip }}</span>
            </a-form-item>

            <template v-if="modalState.neType[0] === 'UPF'">
              <a-form-item
                :label="t('views.traceManage.pcap.capStart')"
                name="upfStart"
                v-bind="modalStateFrom.validateInfos.upfStart"
              >
                <a-input-group compact>
                  <a-input
                    v-model:value="modalState.from.upfStart"
                    allow-clear
                    :placeholder="t('views.traceManage.pcap.capArgUPFPlease')"
                    style="width: 75%"
                  />
                  <a-button
                    type="primary"
                    style="width: 25%"
                    :disabled="modalState.confirmLoading"
                    :loading="modalState.confirmLoading"
                    @click.prevent="fnUPF('start')"
                  >
                    {{ t('views.traceManage.pcap.runText') }}
                  </a-button>
                </a-input-group>
              </a-form-item>
              <a-form-item
                :label="t('views.traceManage.pcap.capStop')"
                name="upfStop"
                v-bind="modalStateFrom.validateInfos.upfStop"
              >
                <a-input-group compact>
                  <a-input
                    v-model:value="modalState.from.upfStop"
                    allow-clear
                    :placeholder="t('views.traceManage.pcap.capArgUPFPlease')"
                    style="width: 75%"
                  />
                  <a-button
                    type="primary"
                    style="width: 25%"
                    :disabled="modalState.confirmLoading"
                    :loading="modalState.confirmLoading"
                    @click.prevent="fnUPF('stop')"
                  >
                    {{ t('views.traceManage.pcap.runText') }}
                  </a-button>
                </a-input-group>
              </a-form-item>
            </template>
            <template v-else>
              <a-form-item
                :label="t('views.traceManage.pcap.capArg')"
                name="cmd"
                v-bind="modalStateFrom.validateInfos.cmd"
              >
                <a-input
                  v-model:value="modalState.from.cmd"
                  allow-clear
                  :placeholder="t('views.traceManage.pcap.capArgPlease')"
                >
                </a-input>
              </a-form-item>
              <a-form-item
                :label="t('views.traceManage.pcap.capTime')"
                name="timeout"
                v-bind="modalStateFrom.validateInfos.timeout"
              >
                <a-input-number
                  v-model:value="modalState.from.timeout"
                  :placeholder="t('views.traceManage.pcap.capTimePlease')"
                  :min="5"
                  :max="120"
                />
              </a-form-item>
              <a-form-item :wrapperCol="{ offset: 5 }">
                <a-space :size="8">
                  <a-button
                    type="primary"
                    :disabled="modalState.confirmLoading"
                    :loading="modalState.confirmLoading"
                    @click.prevent="fnStart"
                  >
                    <template #icon><ApiOutlined /></template>
                    {{
                      runTime != 0
                        ? t('views.traceManage.pcap.runTimeText', {
                            s: runTime,
                          })
                        : t('views.traceManage.pcap.runText')
                    }}
                  </a-button>
                  <a-button
                    type="dashed"
                    danger
                    :disabled="!modalState.confirmLoading"
                    @click.prevent="fnStop"
                  >
                    {{ t('views.traceManage.pcap.stopText') }}
                  </a-button>
                </a-space>
              </a-form-item>
            </template>
          </a-form>
        </a-col>
        <a-col :offset="2" :lg="10" :md="10" :xs="24">
          <a-form layout="vertical" autocomplete="off">
            <a-form-item
              :label="t('views.traceManage.pcap.capLog')"
              name="execLogMsg"
              v-show="!!modalState.execLogMsg"
            >
              <a-textarea
                v-model:value="modalState.execLogMsg"
                :auto-size="{ minRows: 10, maxRows: 15 }"
                :disabled="true"
              />
            </a-form-item>
            <a-form-item v-show="modalState.downBtn">
              <a-button
                type="primary"
                :title="modalState.fileName"
                @click.prevent="fnDownPCAP"
              >
                <template #icon><DownloadOutlined /></template>
                {{ t('views.traceManage.pcap.capDownText') }}
              </a-button>
            </a-form-item>
          </a-form>
        </a-col>
      </a-row>
    </a-card>
  </PageContainer>
</template>

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