<script setup lang="ts">
import { reactive, onMounted, toRaw, ref } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { ProModal } from 'antdv-pro-modal';
import { Form, message, Modal } from 'ant-design-vue/es';
import { SizeType } from 'ant-design-vue/es/config-provider';
import { ColumnsType } from 'ant-design-vue/es/table';
import { parseDateToStr } from '@/utils/date-utils';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import useI18n from '@/hooks/useI18n';
import {
  delTaskHLR,
  listTaskHLR,
  startTaskHLR,
  stopTaskHLR,
  fileTaskHLR,
  filePullTaskHLR,
} from '@/api/trace/taskHLR';
import { getNeFile } from '@/api/tool/neFile';
import saveAs from 'file-saver';
const { t } = useI18n();

/**开始结束时间 */
let queryRangePicker = ref<[string, string]>(['', '']);

/**查询参数 */
let queryParams = reactive({
  imsi: '',
  msisdn: '',
  /**记录时间 */
  startTime: '',
  endTime: '',
  /**排序字段 */
  sortField: '',
  /**排序方式 */
  sortOrder: 'asc',
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    imsi: '',
    msisdn: '',
    startTime: '',
    endTime: '',
    sortField: '',
    sortOrder: 'asc',
    pageNum: 1,
    pageSize: 20,
  });
  queryRangePicker.value = ['', ''];
  tablePagination.current = 1;
  tablePagination.pageSize = 20;
  fnGetList();
}

/**表格状态类型 */
type TabeStateType = {
  /**加载等待 */
  loading: boolean;
  /**紧凑型 */
  size: SizeType;
  /**搜索栏 */
  seached: boolean;
  /**记录数据 */
  data: object[];
  /**勾选记录 */
  selectedRowKeys: (string | number)[];
};

/**表格状态 */
let tableState: TabeStateType = reactive({
  loading: false,
  size: 'middle',
  seached: true,
  data: [],
  selectedRowKeys: [],
});

/**表格字段列 */
let tableColumns: ColumnsType = reactive([
  {
    title: t('common.rowId'),
    dataIndex: 'id',
    align: 'right',
    width: 50,
  },
  {
    title: t('views.traceManage.task.imsi'),
    dataIndex: 'imsi',
    align: 'left',
    width: 150,
  },
  {
    title: t('views.traceManage.task.msisdn'),
    dataIndex: 'msisdn',
    align: 'left',
    width: 150,
  },
  // {
  //   title: t('views.traceManage.task.status'),
  //   dataIndex: 'status',
  //   align: 'left',
  //   width: 100,
  // },
  {
    title: t('views.traceManage.task.startTime'),
    dataIndex: 'startTime',
    align: 'left',
    customRender(opt) {
      if (!opt.value) return '';
      return parseDateToStr(opt.value);
    },
    width: 150,
  },
  {
    title: t('views.traceManage.task.endTime'),
    dataIndex: 'endTime',
    align: 'left',
    customRender(opt) {
      if (!opt.value) return '';
      return parseDateToStr(opt.value);
    },
    width: 150,
  },
  {
    title: t('common.operate'),
    key: 'id',
    align: 'left',
  },
]);

/**表格分页器参数 */
let tablePagination = reactive({
  /**当前页数 */
  current: 1,
  /**每页条数 */
  pageSize: 20,
  /**默认的每页条数 */
  defaultPageSize: 20,
  /**指定每页可以显示多少条 */
  pageSizeOptions: ['10', '20', '50', '100'],
  /**只有一页时是否隐藏分页器 */
  hideOnSinglePage: false,
  /**是否可以快速跳转至某页 */
  showQuickJumper: true,
  /**是否可以改变 pageSize */
  showSizeChanger: true,
  /**数据总数 */
  total: 0,
  showTotal: (total: number) => t('common.tablePaginationTotal', { total }),
  onChange: (page: number, pageSize: number) => {
    tablePagination.current = page;
    tablePagination.pageSize = pageSize;
    queryParams.pageNum = page;
    queryParams.pageSize = pageSize;
    fnGetList();
  },
});

/**表格多选 */
function fnTableSelectedRowKeys(keys: (string | number)[]) {
  tableState.selectedRowKeys = keys;
}

/**
 * 信息删除
 * @param row 记录编号ID
 */
function fnRecordDelete(row: Record<string, any>) {
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.traceManage.task.delTaskTip', { id: row.id }),
    onOk() {
      const hide = message.loading(t('common.loading'), 0);
      delTaskHLR(row.id)
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('views.traceManage.task.delTask', { id: row.id }),
              duration: 3,
            });
            fnGetList();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 2,
            });
          }
        })
        .finally(() => {
          hide();
        });
    },
  });
}

/**查询信息列表, pageNum初始页数 */
function fnGetList(pageNum?: number) {
  if (tableState.loading) return;
  tableState.loading = true;
  if (pageNum) {
    queryParams.pageNum = pageNum;
  }
  if (!queryRangePicker.value) {
    queryRangePicker.value = ['', ''];
  }
  queryParams.startTime = queryRangePicker.value[0];
  queryParams.endTime = queryRangePicker.value[1];
  listTaskHLR(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.rows)) {
      // 取消勾选
      if (tableState.selectedRowKeys.length > 0) {
        tableState.selectedRowKeys = [];
      }
      tablePagination.total = res.total;
      tableState.data = res.rows;
      if (
        tablePagination.total <=
          (queryParams.pageNum - 1) * tablePagination.pageSize &&
        queryParams.pageNum !== 1
      ) {
        tableState.loading = false;
        fnGetList(queryParams.pageNum - 1);
      }
    }
    tableState.loading = false;
  });
}

/**
 * 信息停止
 * @param row 记录编号ID
 */
function fnRecordStop(id: string) {
  if (!id || modalState.confirmLoading) return;
  if (id === '0') {
    id = tableState.selectedRowKeys.join(',');
  }

  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.traceManage.task.stopTaskTip', { id }),
    onOk() {
      const hide = message.loading(t('common.loading'), 0);
      stopTaskHLR({ id })
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('views.traceManage.task.stopTask', { id }),
              duration: 3,
            });
            fnGetList();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
        });
    },
  });
}

/**对话框对象信息状态类型 */
type ModalStateType = {
  /**详情框是否显示 */
  openByView: boolean;
  /**新增框或修改框是否显示 */
  openByEdit: boolean;
  /**标题 */
  title: string;
  /**任务开始结束时间 */
  timeRangePicker: [string, string];
  /**表单数据 */
  from: Record<string, any>;
  /**确定按钮 loading */
  confirmLoading: boolean;
  /**文件列表数据 */
  fileList: any[];
  /**错误信息 */
  fileErrMsg: string;
};

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  openByView: false,
  openByEdit: false,
  title: '',
  timeRangePicker: ['', ''],
  from: {
    id: undefined,
    startTime: 0,
    endTime: 0,
    remark: '',
    // 跟踪类型用户
    imsi: '',
    msisdn: '',
  },
  confirmLoading: false,
  fileList: [],
  fileErrMsg: '',
});

/**对话框内表单属性和校验规则 */
const modalStateFrom = Form.useForm(
  modalState.from,
  reactive({
    endTime: [
      {
        required: false,
        message: t('views.traceManage.task.rangePickerPlease'),
      },
    ],
    // 跟踪用户
    imsi: [
      {
        required: false,
        message: t('views.traceManage.task.imsiPlease'),
      },
    ],
    msisdn: [
      {
        required: false,
        message: t('views.traceManage.task.msisdnPlease'),
      },
    ],
  })
);

/**开始结束时间选择对应修改 */
function fnRangePickerChange(item: any, _: any) {
  modalState.from.startTime = +item[0];
  modalState.from.endTime = +item[1];
}

/**
 * 对话框弹出显示
 */
function fnModalVisibleByVive(id: Record<string, any>) {
  if (modalState.confirmLoading) return;
  const hide = message.loading(t('common.loading'), 0);
  modalState.confirmLoading = true;
  fileTaskHLR({ id, dir: '/usr/local/log' }).then(res => {
    modalState.fileErrMsg = '';
    modalState.fileList = [];
    modalState.confirmLoading = false;
    hide();
    if (res.code === RESULT_CODE_SUCCESS) {
      for (const item of res.data) {
        if (item.err != '') {
          modalState.fileErrMsg += `${item.neName}: ${item.err} \n`;
          continue;
        }
        modalState.fileList.push(item);
      }

      modalState.confirmLoading = false;
      hide();
      modalState.title = t('views.traceManage.task.viewTask');
      modalState.openByView = true;
    } else {
      message.error(t('views.traceManage.task.errorTaskInfo'), 3);
    }
  });
}

/**
 * 对话框弹出显示为 新增或者修改
 * @param id 不传为新增
 */
function fnModalVisibleByEdit(id?: string) {
  if (!id) {
    fnModalCancel();
    modalState.title = t('views.traceManage.task.addTask');
    modalState.openByEdit = true;
  }
}

/**
 * 对话框弹出确认执行函数
 * 进行表达规则校验
 */
function fnModalOk() {
  const from = toRaw(modalState.from);
  if (from.imsi === '' && from.msisdn === '') {
    message.warning({
      content: t('views.traceManage.task.imsiORmsisdn'),
      duration: 3,
    });
    return;
  }

  modalStateFrom
    .validate()
    .then(e => {
      modalState.confirmLoading = true;
      const hide = message.loading(t('common.loading'), 0);

      startTaskHLR(from)
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.msgSuccess', { msg: modalState.title }),
              duration: 3,
            });
            fnModalCancel();
          } else {
            message.error({
              content: `${res.msg}`,
              duration: 3,
            });
          }
        })
        .finally(() => {
          hide();
          modalState.confirmLoading = false;
          fnGetList(1);
        });
    })
    .catch(e => {
      message.error(t('common.errorFields', { num: e.errorFields.length }), 3);
    });
}

/**
 * 对话框弹出关闭执行函数
 * 进行表达规则校验
 */
function fnModalCancel() {
  modalState.openByView = false;
  modalState.openByEdit = false;
  modalState.confirmLoading = false;
  modalStateFrom.resetFields();
  modalState.timeRangePicker = ['', ''];
}

/**下载触发等待 */
let downLoading = ref<boolean>(false);

/**信息文件下载 */
function fnDownloadFile(row: Record<string, any>) {
  if (downLoading.value) return;
  Modal.confirm({
    title: t('common.tipTitle'),
    content: t('views.logManage.neFile.downTip', { fileName: row.fileName }),
    onOk() {
      downLoading.value = true;
      const hide = message.loading(t('common.loading'), 0);
      const path = row.filePath.substring(0, row.filePath.lastIndexOf('/'));
      filePullTaskHLR({
        neType: row.neType,
        neId: row.neId,
        path: path,
        fileName: row.fileName,
        delTemp: true,
      })
        .then(res => {
          if (res.code === RESULT_CODE_SUCCESS) {
            message.success({
              content: t('common.msgSuccess', {
                msg: t('common.downloadText'),
              }),
              duration: 2,
            });
            saveAs(res.data, `${row.fileName}`);
          } else {
            message.error({
              content: t('views.logManage.neFile.downTipErr'),
              duration: 2,
            });
          }
        })
        .finally(() => {
          hide();
          downLoading.value = false;
        });
    },
  });
}

onMounted(() => {
  // 获取列表数据
  fnGetList();
});
</script>

<template>
  <PageContainer>
    <a-card
      v-show="tableState.seached"
      :bordered="false"
      :body-style="{ marginBottom: '24px', paddingBottom: 0 }"
    >
      <!-- 表格搜索栏 -->
      <a-form :model="queryParams" name="queryParams" layout="horizontal">
        <a-row :gutter="16">
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item label="IMSI" name="imsi ">
              <a-input
                v-model:value="queryParams.imsi"
                allow-clear
                :placeholder="t('common.inputPlease')"
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item label="MSISDN" name="msisdn ">
              <a-input
                v-model:value="queryParams.msisdn"
                allow-clear
                :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.traceManage.task.time')"
              name="queryRangePicker"
            >
              <a-range-picker
                v-model:value="queryRangePicker"
                allow-clear
                bordered
                :show-time="{ format: 'HH:mm:ss' }"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="x"
                :placeholder="[
                  t('views.traceManage.task.startTime'),
                  t('views.traceManage.task.endTime'),
                ]"
                style="width: 100%"
              ></a-range-picker>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item>
              <a-space :size="8">
                <a-button type="primary" @click.prevent="fnGetList(1)">
                  <template #icon><SearchOutlined /></template>
                  {{ t('common.search') }}
                </a-button>
                <a-button type="default" @click.prevent="fnQueryReset">
                  <template #icon><ClearOutlined /></template>
                  {{ t('common.reset') }}
                </a-button>
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title>
        <a-space :size="8" align="center">
          <a-button type="primary" @click.prevent="fnModalVisibleByEdit()">
            <template #icon><PlusOutlined /></template>
            {{ t('common.addText') }}
          </a-button>
          <a-button
            type="default"
            danger
            :disabled="tableState.selectedRowKeys.length <= 0"
            :loading="modalState.confirmLoading"
            @click.prevent="fnRecordStop('0')"
          >
            <template #icon><StopOutlined /></template>
            {{ t('views.traceManage.task.textStop') }}
          </a-button>
        </a-space>
      </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip placement="topRight">
            <template #title>{{ t('common.reloadText') }}</template>
            <a-button type="text" @click.prevent="fnGetList()">
              <template #icon><ReloadOutlined /></template>
            </a-button>
          </a-tooltip>
        </a-space>
      </template>

      <!-- 表格列表 -->
      <a-table
        class="table"
        row-key="id"
        :columns="tableColumns"
        :loading="tableState.loading"
        :data-source="tableState.data"
        :size="tableState.size"
        :pagination="tablePagination"
        :scroll="{ x: true }"
        :row-selection="{
          type: 'checkbox',
          columnWidth: '48px',
          selectedRowKeys: tableState.selectedRowKeys,
          onChange: fnTableSelectedRowKeys,
        }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'id'">
            <a-space :size="8" align="center">
              <a-tooltip v-if="record.status === '1'">
                <template #title>
                  {{ t('views.traceManage.task.textStop') }}
                </template>
                <a-button
                  type="link"
                  danger
                  @click.prevent="fnRecordStop(record.id)"
                >
                  <template #icon><StopOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.viewText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByVive(record.id)"
                >
                  <template #icon><ProfileOutlined /></template>
                </a-button>
              </a-tooltip>
              <a-tooltip>
                <template #title>{{ t('common.deleteText') }}</template>
                <a-button type="link" @click.prevent="fnRecordDelete(record)">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 详情框 -->
    <ProModal
      :drag="true"
      :open="modalState.openByView"
      :title="modalState.title"
      @cancel="fnModalCancel"
      :footer="null"
    >
      <a-form
        name="fileList"
        layout="horizontal"
        autocomplete="off"
        :label-col="{ span: 5 }"
        :label-wrap="true"
      >
        <a-form-item
          :label="t('views.traceManage.task.traceFile')"
          name="fileTree"
          v-show="modalState.fileList.length > 0"
        >
          <a-tree
            :height="250"
            :tree-data="modalState.fileList"
            :field-names="{ title: 'fileName', key: 'filePath' }"
          >
            <template #title="item">
              <span>{{ item.fileName }}</span>
              <span
                class="fileTree-download"
                @click.prevent="fnDownloadFile(item)"
              >
                {{ t('common.downloadText') }}
              </span>
            </template>
          </a-tree>
        </a-form-item>
        <a-form-item
          :label="t('views.traceManage.task.errMsg')"
          name="fileErrMsg"
          v-show="modalState.fileErrMsg.length > 0"
        >
          <a-textarea
            v-model:value="modalState.fileErrMsg"
            :auto-size="{ minRows: 2, maxRows: 6 }"
            :disabled="true"
          />
        </a-form-item>
      </a-form>
    </ProModal>

    <!-- 新增框或修改框 -->
    <ProModal
      :drag="true"
      :width="800"
      :destroyOnClose="true"
      :keyboard="false"
      :mask-closable="false"
      :open="modalState.openByEdit"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @ok="fnModalOk"
      @cancel="fnModalCancel"
    >
      <a-form
        name="modalStateFrom"
        layout="horizontal"
        :label-col="{ span: 4 }"
        :label-wrap="true"
      >
        <!-- 用户跟踪 -->
        <a-form-item
          :label="t('views.traceManage.task.imsi')"
          name="imsi"
          v-bind="modalStateFrom.validateInfos.imsi"
        >
          <a-input
            v-model:value="modalState.from.imsi"
            allow-clear
            :placeholder="t('views.traceManage.task.imsiPlease')"
          >
            <template #prefix>
              <a-tooltip placement="topLeft">
                <template #title>
                  <div>{{ t('views.traceManage.task.imsiTip') }}</div>
                </template>
                <InfoCircleOutlined style="opacity: 0.45; color: inherit;" />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>
        <a-form-item
          :label="t('views.traceManage.task.msisdn')"
          name="msisdn"
          v-bind="modalStateFrom.validateInfos.msisdn"
        >
          <a-input
            v-model:value="modalState.from.msisdn"
            allow-clear
            :placeholder="t('views.traceManage.task.msisdnPlease')"
          >
            <template #prefix>
              <a-tooltip placement="topLeft">
                <template #title>
                  <div>{{ t('views.traceManage.task.msisdnTip') }}</div>
                </template>
                <InfoCircleOutlined style="opacity: 0.45; color: inherit;" />
              </a-tooltip>
            </template>
          </a-input>
        </a-form-item>

        <a-form-item
          :label="t('views.traceManage.task.rangePicker')"
          name="endTime"
          v-bind="modalStateFrom.validateInfos.endTime"
        >
          <a-range-picker
            v-model:value="modalState.timeRangePicker"
            allow-clear
            bordered
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="x"
            :placeholder="[
              t('views.traceManage.task.startTime'),
              t('views.traceManage.task.endTime'),
            ]"
            style="width: 100%"
            @change="fnRangePickerChange"
          ></a-range-picker>
        </a-form-item>
        <a-form-item :label="t('views.traceManage.task.remark')" name="remark">
          <a-textarea
            v-model:value="modalState.from.remark"
            :auto-size="{ minRows: 2, maxRows: 6 }"
            :maxlength="250"
            :show-count="true"
            :placeholder="t('views.traceManage.task.remarkPlease')"
          />
        </a-form-item>
      </a-form>
    </ProModal>
  </PageContainer>
</template>

<style lang="less" scoped>
.table :deep(.ant-pagination) {
  padding: 0 24px;
}

.fileTree-download {
  margin-left: 12px;
  color: #eb2f96;
  text-decoration: underline;
}
</style>
