<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formChinaAreaRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormChinaArea()" @reset="resetFormChinaArea">
        <el-form-item label="地区名称">
          <el-input
            class="filter-item"
            v-model="formFilter.nameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="等级 1：省,2：市,3：区县">
          <el-input-number
            class="filter-item"
            v-model="formFilter.levelFilter"
            placeholder=""
            :clearable="true"
            :step="1"
            :controls="true"
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formChinaAreaTable"
      class="page-table"
      :data="formChinaAreaTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formChinaAreaTableWidgetCurrentPage - 1) * formChinaAreaTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formChinaAreaTableWidget.onSortChange"
      @refresh="formChinaAreaTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddChinaAreaClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportChinaAreaClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportChinaAreaClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formChinaAreaTableWidget.getTableIndex" :width="80" />
      <vxe-column title="地区编码" field="code" />
      <vxe-column title="地区名称" field="name" />
      <vxe-column title="城市编码" field="cityCode" />
      <vxe-column title="城市名称" field="cityName" />
      <vxe-column title="省编码" field="provinceCode" />
      <vxe-column title="省名称" field="provinceName" />
      <vxe-column title="国家" field="country" />
      <vxe-column title="等级 1：省,2：市,3：区县" field="level" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditChinaAreaClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteChinaAreaClick(scope.row)"
          >
            删除
          </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="formChinaAreaTableWidgetTotalCount"
            :current-page="formChinaAreaTableWidgetCurrentPage"
            :page-size="formChinaAreaTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formChinaAreaTableWidget.onCurrentPageChange"
            @size-change="formChinaAreaTableWidget.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: 'formChinaArea',
};
</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, stringCase } from '@/common/utils';
import { ChinaAreaData } from '@/api/generated/chinaAreaController';
import { ChinaAreaController } from '@/api/generated';
import FormEditChinaArea from '@/pages/tourVisa/formEditChinaArea.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({
  // 地区名称
  nameFilter: undefined,
  // 等级 1：省,2：市,3：区县
  levelFilter: undefined,
});
const formFilterCopy = reactive({
  // 地区名称
  nameFilter: undefined,
  // 等级 1：省,2：市,3：区县
  levelFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormChinaAreaTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    chinaAreaDtoFilter: {
      name: formFilter.nameFilter,
      level: formFilter.levelFilter,
    }
  };
  return new Promise((resolve, reject) => {
    ChinaAreaController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormChinaAreaTableVerify = () => {
  formFilterCopy.nameFilter = formFilter.nameFilter;
  formFilterCopy.levelFilter = formFilter.levelFilter;
  return true;
};
/**
 * 新建
 */
const onAddChinaAreaClick = (row?: ChinaAreaData) => {
  let params: ANY_OBJECT = {
  };

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

  Dialog
    .show('编辑', FormEditChinaArea, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formChinaAreaTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportChinaAreaClick = (row?: ChinaAreaData) => {
  let params: ANY_OBJECT = {
  };

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    ChinaAreaController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formChinaAreaTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formChinaAreaTableOptions: TableOptions<ChinaAreaData> = {
  loadTableData: loadFormChinaAreaTableWidgetData,
  verifyTableParameter: loadFormChinaAreaTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formChinaAreaTable = ref();
const formChinaAreaTableWidget = useTable(formChinaAreaTableOptions);
const {
  dataList: formChinaAreaTableWidgetDataList,
  currentPage: formChinaAreaTableWidgetCurrentPage,
  pageSize: formChinaAreaTableWidgetPageSize,
  totalCount: formChinaAreaTableWidgetTotalCount,
} = formChinaAreaTableWidget;
const refreshFormChinaArea = () => {
  // 刷新段落
  formChinaAreaTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormChinaArea = () => {
  formFilter.nameFilter = undefined;
  formFilterCopy.nameFilter = undefined;
  formFilter.levelFilter = undefined;
  formFilterCopy.levelFilter = undefined;
  refreshFormChinaArea();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormChinaArea();
};
const formInit = () => {
  refreshFormChinaArea();
};

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