<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formRestaurantAreaMenuRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormRestaurantAreaMenu()" @reset="resetFormRestaurantAreaMenu">
        <el-form-item label="菜单名称">
          <el-input
            class="filter-item"
            v-model="formFilter.levelNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="是否热点">
          <el-select
            class="filter-item"
            v-model="formFilter.isHotspotFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isHotspotFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isHotspotFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select
            class="filter-item"
            v-model="formFilter.enableFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="enableFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in enableFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formRestaurantAreaMenuTable"
      class="page-table"
      :data="formRestaurantAreaMenuTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formRestaurantAreaMenuTableWidgetCurrentPage - 1) * formRestaurantAreaMenuTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      :tree-config="{ rowField: 'id', parentField: 'parentId' }"
      @sort-change="formRestaurantAreaMenuTableWidget.onSortChange"
      @refresh="formRestaurantAreaMenuTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddRestaurantAreaMenuClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportRestaurantAreaMenuClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportRestaurantAreaMenuClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formRestaurantAreaMenuTableWidget.getTableIndex" :width="80" tree-node />
      <vxe-column title="父级区域" field="parentIdDictMap.name" />
      <vxe-column title="区域名称" field="levelName" />
<!--      <vxe-column title="菜单等级" field="levelNum" sortable />-->
      <vxe-column title="显示顺序" field="showOrder" sortable />
      <vxe-column title="是否启用" field="enableDictMap.name" />
<!--      <vxe-column title="是否热点" field="isHotspotDictMap.name" />-->
<!--      <vxe-column title="热门排序" field="hotOrder" sortable />-->
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditRestaurantAreaMenuClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteRestaurantAreaMenuClick(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>
    </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: 'formRestaurantAreaMenu',
};
</script>

<script setup lang="ts">
import * as validateRules from '@/common/utils/validate';
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 { RestaurantAreaMenuData } from '@/api/generated/restaurantAreaMenuController';
import { RestaurantAreaMenuController } from '@/api/generated';
import FormEditRestaurantAreaMenu from '@/pages/RestaurantAreaMenu/formEditRestaurantAreaMenu.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({
  // 菜单名称
  levelNameFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
});
const formFilterCopy = reactive({
  // 菜单名称
  levelNameFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormRestaurantAreaMenuTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    restaurantAreaMenuDtoFilter: {
      levelName: formFilter.levelNameFilter,
      isHotspot: formFilter.isHotspotFilter,
      enable: formFilter.enableFilter,
    }
  };
  return new Promise((resolve, reject) => {
    RestaurantAreaMenuController.list(params).then(res => {
      // 列表数据转换成树形数据
      res.data.dataList = treeDataTranslate(
        res.data.dataList,
        'id',
        'parentId'
      );
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormRestaurantAreaMenuTableVerify = () => {
  formFilterCopy.levelNameFilter = formFilter.levelNameFilter;
  formFilterCopy.isHotspotFilter = formFilter.isHotspotFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  return true;
};
/**
 * 新建
 */
const onAddRestaurantAreaMenuClick = (row?: RestaurantAreaMenuData) => {
  let params: ANY_OBJECT = {
  };

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

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

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    RestaurantAreaMenuController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formRestaurantAreaMenuTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formRestaurantAreaMenuTableOptions: TableOptions<RestaurantAreaMenuData> = {
  loadTableData: loadFormRestaurantAreaMenuTableWidgetData,
  verifyTableParameter: loadFormRestaurantAreaMenuTableVerify,
  paged: false,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formRestaurantAreaMenuTable = ref();
const formRestaurantAreaMenuTableWidget = useTable(formRestaurantAreaMenuTableOptions);
const {
  dataList: formRestaurantAreaMenuTableWidgetDataList,
  currentPage: formRestaurantAreaMenuTableWidgetCurrentPage,
  pageSize: formRestaurantAreaMenuTableWidgetPageSize,
  totalCount: formRestaurantAreaMenuTableWidgetTotalCount,
} = formRestaurantAreaMenuTableWidget;
/**
 * 是否热点下拉数据获取函数
 */
const loadIsHotspotFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsTrue.getList(),
  });
};
// 是否热点配置参数
const isHotspotFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsHotspotFilterDropdownList,
  isTree: false,
};
// 是否热点下拉组件
const isHotspotFilterWidget = useDropdown(isHotspotFilterOptions);
const { dropdownList: isHotspotFilterWidgetDropdownList } = isHotspotFilterWidget
/**
 * 是否启用下拉数据获取函数
 */
const loadEnableFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Enable.getList(),
  });
};
// 是否启用配置参数
const enableFilterOptions: DropdownOptions<DictData> = {
  loadData: loadEnableFilterDropdownList,
  isTree: false,
};
// 是否启用下拉组件
const enableFilterWidget = useDropdown(enableFilterOptions);
const { dropdownList: enableFilterWidgetDropdownList } = enableFilterWidget
const refreshFormRestaurantAreaMenu = () => {
  // 刷新段落
  formRestaurantAreaMenuTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormRestaurantAreaMenu = () => {
  formFilter.levelNameFilter = undefined;
  formFilterCopy.levelNameFilter = undefined;
  formFilter.isHotspotFilter = undefined;
  formFilterCopy.isHotspotFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  refreshFormRestaurantAreaMenu();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormRestaurantAreaMenu();
};
const formInit = () => {
  isHotspotFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormRestaurantAreaMenu();
};

onMounted(() => {
  formInit();
});

onActivated(() => {
  onResume();
});
</script>
