<script setup lang="ts">
import { reactive, ref, onMounted, toRaw } from 'vue';
import { PageContainer } from 'antdv-pro-layout';
import { SizeType } from 'ant-design-vue/es/config-provider';
import { MenuInfo } from 'ant-design-vue/es/menu/src/interface';
import { ColumnsType } from 'ant-design-vue/es/table';
import { parseDateToStr, parseStrToDate } from '@/utils/date-utils';
import { RESULT_CODE_SUCCESS } from '@/constants/result-constants';
import { listCallBack, updateStatus } from '@/api/agentManage/callback';
import useNeInfoStore from '@/store/modules/neinfo';
import useDictStore from '@/store/modules/dict';
import useI18n from '@/hooks/useI18n';
import { message } from 'ant-design-vue';
import { ProModal } from 'antdv-pro-modal';
import { create } from 'domain';
import { commentProps } from 'ant-design-vue/es/comment';

const { getDict } = useDictStore();
const { t } = useI18n();
let dictStatus = ref<DictType[]>([]);

/**网元参数 */
let neOtions = ref<Record<string, any>[]>([]);
/**开始结束时间 */
let queryRangePicker = ref<[string, string]>(['', '']);

/**查询参数 */
let queryParams = reactive({
  /**网元类型 */
  neId: '001',
  /**记录时间 */
  startTime: '',
  endTime: '',
  callerNumber: '',
  agentName: '',
  status: undefined,
  /**当前页数 */
  pageNum: 1,
  /**每页条数 */
  pageSize: 20,
});

/**查询参数重置 */
function fnQueryReset() {
  queryParams = Object.assign(queryParams, {
    neId: '001',
    status: undefined,
    beginTime: '',
    endTime: '',
    callerNumber: '',
    agentName: '',
    pageNum: 1,
    pageSize: 20,
  });
  queryRangePicker.value = ['', ''];
  tablePagination.current = 1;
  tablePagination.pageSize = 20;
  fnGetList();
}

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

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

/**表格字段列 */
let tableColumns: ColumnsType = [
  {
    title: t('views.agentManage.callback.ticketId'),
    dataIndex: 'ticketId',
    align: 'center',
    width: 5,
  },
  {
    title: t('views.agentManage.callback.agentName'),
    dataIndex: 'agentName',
    align: 'center',
    width: 5,
  },
  {
    title: t('views.agentManage.callback.callerIdNumber'),
    dataIndex: 'callerNumber',
    align: 'center',
    width: 5,
  },
  {
    title: t('views.agentManage.callback.calleeIdNumber'),
    dataIndex: 'calleeNumber',
    align: 'center',
    width: 5,
  },
  {
    title: t('views.agentManage.callback.status'),
    dataIndex: 'status',
    key: 'status',
    align: 'center',
    width: 4,
  },
  {
    title: t('views.agentManage.callback.startTime'),
    dataIndex: 'createdAt',
    align: 'center',
    width: 6,
    customRender(opt) {
      if (!opt.value) return '';
      return parseDateToStr(opt.value / 1000);
    },
  },
  {
    title: t('views.agentManage.callback.updateTime'),
    dataIndex: 'updatedAt',
    align: 'center',
    width: 6,
    customRender(opt) {
      if (!opt.value) return '';
      return parseDateToStr(opt.value / 1000);
    },
  },
  // {
  //   title: t('views.agentManage.callback.msdData'),
  //   dataIndex: 'msdData',
  //   align: 'center',
  //   width: 6,
  // },
  {
    title: t('common.operate'),
    key: 'callbackId',
    align: 'left',
    width: 6,
  },
];

/**表格分页器参数 */
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 fnTableSize({ key }: MenuInfo) {
  tableState.size = key as SizeType;
}

/**查询备份信息列表, 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];

  listCallBack(toRaw(queryParams)).then(res => {
    if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
      tablePagination.total = res.total;
      tableState.data = res.data;
      if (
        tablePagination.total <=
          (queryParams.pageNum - 1) * tablePagination.pageSize &&
        queryParams.pageNum !== 1
      ) {
        tableState.loading = false;
        fnGetList(queryParams.pageNum - 1);
      }
    }
    tableState.loading = false;
  });
}

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

/**对话框对象信息状态 */
let modalState: ModalStateType = reactive({
  openByView: false,
  openByEdit: false,
  title: 'callback',
  from: {
    id: undefined,
    ticketId: '',
    agentName: '',
    callerNumber: '',
    calleeNumber: '',
    agentEmail: '',
    agentMobile: '',
    status: '',
    createdAt: '',
    comment: '',
  },
  confirmLoading: false,
  loadDataLoading: false,
});

function fnModalVisibleByEdit(record: any) {
  modalState.title = t('common.viewText') + t('views.agentManage.callback.title');
  modalState.openByEdit = true;
  modalState.from = Object.assign(modalState.from, record, {
    createdAt: record.createdAt ? parseDateToStr(record.createdAt / 1000) : '',
  });
}

function fnModalOk() {
  const from = Object.assign({}, toRaw(modalState.from));

  modalState.confirmLoading = true;
  const hide = message.loading(t('common.loading'), 0);
  updateStatus(from)
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS) {
        message.success({
          content: t('common.msgSuccess', { msg: modalState.title }),
          duration: 3,
        });
        fnGetList(1);
      } else {
        message.error({
          content: `${res.msg}`,
          duration: 3,
        });
      }
    })
    .finally(() => {
      hide();
      fnModalCancel();
      modalState.confirmLoading = false;
    });
}

function fnModalCancel() {
  modalState.openByEdit = false;
  //modalState.openByView = false;
  //modalStateFrom.resetFields();
}

onMounted(() => {
  getDict('callback_status').then(res => {
    dictStatus.value = res;
  });
  // 获取网元网元列表
  useNeInfoStore()
    .fnNelist()
    .then(res => {
      if (res.code === RESULT_CODE_SUCCESS && Array.isArray(res.data)) {
        if (res.data.length > 0) {
          let arr: Record<string, any>[] = [];
          res.data.forEach(i => {
            if (i.neType === 'MF') {
              arr.push({ value: i.neId, label: i.neName });
            }
          });
          neOtions.value = arr;
          if (arr.length > 0) {
            queryParams.neId = arr[0].value;
          }
        }
      } else {
        message.warning({
          content: t('common.noData'),
          duration: 2,
        });
      }
    })
    .finally(() => {
      // 获取列表数据
      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="PSAP对象" name="neId ">
              <a-select
                v-model:value="queryParams.neId"
                :options="neOtions"
                :placeholder="t('common.selectPlease')"
                @change="fnGetList(1)"
              />
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.callerIdNumber')"
              name="callerNumber"
            >
              <a-input
                v-model:value="queryParams.callerNumber"
                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="t('views.agentManage.callback.agentName')"
              name="agentName"
            >
              <a-input
                v-model:value="queryParams.agentName"
                allow-clear
                :placeholder="t('common.inputPlease')"
              ></a-input>
            </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-col :lg="6" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.status')"
              name="status"
            >
              <a-select
                v-model:value="queryParams.status"
                :options="dictStatus"
                :allow-clear="true"
              >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="8" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.startTime')"
              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"
                style="width: 100%"
              ></a-range-picker>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <a-card :bordered="false" :body-style="{ padding: '0px' }">
      <!-- 插槽-卡片左侧侧 -->
      <template #title> </template>

      <!-- 插槽-卡片右侧 -->
      <template #extra>
        <a-space :size="8" align="center">
          <a-tooltip>
            <template #title>{{ t('common.reloadText') }}</template>
            <a-button type="text" @click.prevent="fnGetList()">
              <template #icon>
                <ReloadOutlined />
              </template>
            </a-button>
          </a-tooltip>
          <a-tooltip>
            <template #title>{{ t('common.sizeText') }}</template>
            <a-dropdown trigger="click" placement="bottomRight">
              <a-button type="text">
                <template #icon>
                  <ColumnHeightOutlined />
                </template>
              </a-button>
              <template #overlay>
                <a-menu
                  :selected-keys="[tableState.size as string]"
                  @click="fnTableSize"
                >
                  <a-menu-item key="default">
                    {{ t('common.size.default') }}
                  </a-menu-item>
                  <a-menu-item key="middle">
                    {{ t('common.size.middle') }}
                  </a-menu-item>
                  <a-menu-item key="small">
                    {{ t('common.size.small') }}
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </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: 1500, y: 400 }"
      >
        <template #bodyCell="{ column, record }">

          <template v-if="column.key === 'status'">
            <DictTag :options="dictStatus" :value="record.status" />
          </template>

          <template v-if="column.key === 'callbackId'">
            <a-space :size="8" align="center">
              <a-tooltip>
                <template #title>{{ t('common.viewText') }}</template>
                <a-button
                  type="link"
                  @click.prevent="fnModalVisibleByEdit(record)"
                >
                  <template #icon><InfoCircleOutlined /></template>
                </a-button>
              </a-tooltip>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <ProModal
      :drag="true"
      :width="800"
      :destroyOnClose="true"
      style="top: 0px"
      :body-style="{ maxHeight: '600px', 'overflow-y': 'auto' }"
      :keyboard="false"
      :mask-closable="false"
      :open="modalState.openByEdit"
      :title="modalState.title"
      :confirm-loading="modalState.confirmLoading"
      @cancel="fnModalCancel"
      @ok="fnModalOk"
      :okText=" t('views.faultManage.activeAlarm.confirm') "
    >
      <a-form
        name="modalStateFrom"
        layout="horizontal"
        :label-col="{ span: 6 }"
        :labelWrap="true"
      >
        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.ticketId')"
              name="ticketId"
            >
              <a-input
                :disabled="true"
                v-model:value="modalState.from.ticketId"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.agentName')"
              name="agentName"
            >
              <a-input
                :disabled="true"
                v-model:value="modalState.from.agentName"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.callerIdNumber')"
              name="callerNumber"
            >
              <a-input
                :disabled="true"
                v-model:value="modalState.from.callerNumber"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.calleeIdNumber')"
              name="calleeNumber"
            >
              <a-input
                :disabled="true"
                v-model:value="modalState.from.calleeNumber"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.agentEmail')"
              name="agentEmail"
            >
              <a-input
                :disabled="true"
                v-model:value="modalState.from.agentEmail"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.agentMobile')"
              name="agentMobile"
            >
              <a-input
                :disabled="true"
                v-model:value="modalState.from.agentMobile"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.status')"
              name="status"
            >
              <a-input
                :disabled="true"
                v-model:value="modalState.from.status"
              ></a-input>
            </a-form-item>
          </a-col>

          <a-col :lg="12" :md="12" :xs="24">
            <a-form-item
              :label="t('views.agentManage.callback.startTime')"
              name="createdAt"
            >
              <a-input
                :disabled="true"
                v-model:value="modalState.from.createdAt"
              ></a-input>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item
          :label="t('views.agentManage.callback.comment')"
          :label-col="{ span: 3 }"
          name="comment"
        >
          <a-input
            :disabled="true"
            v-model:value="modalState.from.comment"
          ></a-input>
        </a-form-item>
      </a-form>
    </ProModal>
  </PageContainer>
</template>

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

.alarmTitleText {
  max-width: 300px;
  cursor: pointer;
}
</style>
