<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourBookInfo"
      :model="formData" 
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourBookInfo()" @reset="resetFormTourBookInfo">
        <el-form-item label="预定电话">
          <el-input
            class="filter-item"
            v-model="formFilter.bookMobileFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="预定姓名">
          <el-input
            class="filter-item"
            v-model="formFilter.bookNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="预定的ip">
          <el-input
            class="filter-item"
            v-model="formFilter.bookIpFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="预定时间">
          <el-date-picker
            class="filter-item"
            v-model="formFilter.bookTimeFilter"
            type="daterange"
            start-placeholder=""
            end-placeholder=""
            :clearable="true"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date().setHours(0, 0, 0, 0), new Date().setHours(23, 59, 59, 999)]"
          />
        </el-form-item>
        <el-form-item label="是否处理">
          <el-select
            class="filter-item"
            v-model="formFilter.isHandleFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isHandleFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isHandleFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="tourBookInfo"
      class="page-table"
      :data="tourBookInfoWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourBookInfoWidgetCurrentPage - 1) * tourBookInfoWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="tourBookInfoWidget.onSortChange"
      @refresh="tourBookInfoWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourBookInfo:formTourBookInfo:add')"
          @click="onAddClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourBookInfo:formTourBookInfo:export')"
          @click="onExportClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formTourBookInfo:formTourBookInfo:import')"
          :on-change="onImportClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formTourBookInfo:formTourBookInfo:import')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="tourBookInfoWidget.getTableIndex" :width="80" />
      <vxe-column title="预定电话" field="bookMobile" />
      <vxe-column title="预定姓名" field="bookName" />
      <vxe-column title="预定的ip" field="bookIp" />
      <vxe-column title="预定时间" field="bookTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.bookTime, 'datetime')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="是否处理" field="isHandleDictMap.name" />
      <vxe-column title="预定的类型" field="typeDictMap.name" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourBookInfo:formTourBookInfo:edit')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourBookInfo:formTourBookInfo:delete')"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="tourBookInfoWidgetTotalCount"
            :current-page="tourBookInfoWidgetCurrentPage"
            :page-size="tourBookInfoWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourBookInfoWidget.onCurrentPageChange"
            @size-change="tourBookInfoWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formTourBookInfo',
};
</script>

<script setup lang="ts">
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode } from '@/common/utils';
import { TourBookInfoData } from '@/api/generated/tourBookInfoController';
import { TourBookInfoController } from '@/api/generated';
import FormEditTourBookInfo from '@/pages/tourBookInfo/formEditTourBookInfo.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
  }>(),
  {
    subPage: 0,
  },
);

const formFilter = reactive({
  // 预定电话
  bookMobileFilter: undefined,
  // 预定姓名
  bookNameFilter: undefined,
  // 预定的ip
  bookIpFilter: undefined,
  // 预定时间
  bookTimeFilter: [],
  // 是否处理
  isHandleFilter: undefined,
  startTime: undefined,
  endTime: undefined
});
const formFilterCopy = reactive({
  // 预定电话
  bookMobileFilter: undefined,
  // 预定姓名
  bookNameFilter: undefined,
  // 预定的ip
  bookIpFilter: undefined,
  // 预定时间
  bookTimeFilter: [],
  // 是否处理
  isHandleFilter: undefined,
});

const onCancel = () => {
  layoutStore.removeCachePage(route.name as string);
  route.meta.refreshParentCachedPage = true;
  router.go(-1);
};

const onResume = () => {
  refreshFormTourBookInfo();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourBookInfoWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  if(formFilter.bookTimeFilter !== undefined){
    formFilter.startTime = formFilter.bookTimeFilter[0],
    formFilter.endTime = formFilter.bookTimeFilter[1]
  }
  params = {
    ...params,
    tourBookInfoDtoFilter:{
      bookMobile: formFilter.bookMobileFilter,
      bookName: formFilter.bookNameFilter,
      bookIp: formFilter.bookIpFilter,
      isHandle: formFilter.isHandleFilter,
      startTime: formFilter.startTime,
      endTime: formFilter.endTime
    }
  };
  return new Promise((resolve, reject) => {
    TourBookInfoController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourBookInfoVerify = () => {
  formFilterCopy.bookMobileFilter = formFilter.bookMobileFilter;
  formFilterCopy.bookNameFilter = formFilter.bookNameFilter;
  formFilterCopy.bookIpFilter = formFilter.bookIpFilter;
  formFilterCopy.bookTimeFilter = formFilter.bookTimeFilter;
  formFilterCopy.isHandleFilter = formFilter.isHandleFilter;
  return true;
};
/**
 * 新建
 */
const onAddClick = (row?: TourBookInfoData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditTourBookInfo, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      tourBookInfoWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditClick = (row?: TourBookInfoData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑', FormEditTourBookInfo, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      tourBookInfoWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportClick = (row?: TourBookInfoData) => {
  let params: ANY_OBJECT = {
    tourBookInfoDtoFilter: {
      bookMobile: formFilter.bookMobileFilter,
      bookName: formFilter.bookNameFilter,
      bookIp: formFilter.bookIpFilter,
      bookTime: formFilter.bookTimeFilter,
      isHandle: formFilter.isHandleFilter,
    }
  };

  TourBookInfoController.export(params, '.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 导入
 */
const onImportClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  TourBookInfoController.import(params).then(res => {
    ElMessage.success('导入成功');
    tourBookInfoWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 删除
 */
const onDeleteClick = (row?: TourBookInfoData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  TourBookInfoController.delete(params).then(res => {
    ElMessage.success('删除成功');
    tourBookInfoWidget.refreshTable(false, 1);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const tourBookInfoOptions: TableOptions<TourBookInfoData> = {
  loadTableData: loadTourBookInfoWidgetData,
  verifyTableParameter: loadTourBookInfoVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'bookTime',
  ascending: false,
};
// 表格组件表格组件
const tourBookInfo = ref();
const tourBookInfoWidget = useTable(tourBookInfoOptions);
const {
  dataList: tourBookInfoWidgetDataList,
  currentPage: tourBookInfoWidgetCurrentPage,
  pageSize: tourBookInfoWidgetPageSize,
  totalCount: tourBookInfoWidgetTotalCount,
} = tourBookInfoWidget;
/**
 * 是否处理下拉数据获取函数
 */
const loadIsHandleFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'IsHandle', itemIdType: 'String' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 是否处理配置参数
const isHandleFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsHandleFilterDropdownList,
  isTree: false,
};
// 是否处理下拉组件
const isHandleFilterWidget = useDropdown(isHandleFilterOptions);
const { dropdownList: isHandleFilterWidgetDropdownList } = isHandleFilterWidget
const refreshFormTourBookInfo = () => {
  // 刷新段落
  tourBookInfoWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourBookInfo = () => {
  formFilter.bookMobileFilter = undefined;
  formFilterCopy.bookMobileFilter = undefined;
  formFilter.bookNameFilter = undefined;
  formFilterCopy.bookNameFilter = undefined;
  formFilter.bookIpFilter = undefined;
  formFilterCopy.bookIpFilter = undefined;
  formFilter.bookTimeFilter = undefined;
  formFilterCopy.bookTimeFilter = undefined;
  formFilter.isHandleFilter = undefined;
  formFilterCopy.isHandleFilter = undefined;
  refreshFormTourBookInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourBookInfo();
};
const formInit = () => {
  isHandleFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourBookInfo();
};

onMounted(() => {
  formInit();
});
</script>