<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formDirectoryInfo"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormDirectoryInfo()" @reset="resetFormDirectoryInfo">
        <el-form-item label="菜单名称">
          <el-input
            class="filter-item"
            v-model="formFilter.menuNameFilter"
            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.parentIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="parentIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in parentIdFilterWidgetDropdownList"
              :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.directoryTypeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="directoryTypeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in directoryTypeFilterWidgetDropdownList"
              :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.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>
        <el-form-item label="是否精选目的地 ">
          <el-select
            class="filter-item"
            v-model="formFilter.isWinnowDestinationFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isWinnowDestinationFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isWinnowDestinationFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formDirectoryInfoTable"
      class="page-table"
      :data="formDirectoryInfoTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formDirectoryInfoTableWidgetCurrentPage - 1) * formDirectoryInfoTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formDirectoryInfoTableWidget.onSortChange"
      @refresh="formDirectoryInfoTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formDirectoryInfo:formDirectoryInfo:addDirectoryInfo')"
          @click="onAddDirectoryInfoClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formDirectoryInfo:formDirectoryInfo:exportDirectoryInfo')"
          @click="onExportDirectoryInfoClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formDirectoryInfo:formDirectoryInfo:importDirectoryInfo')"
          :on-change="onImportDirectoryInfoClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formDirectoryInfo:formDirectoryInfo:importDirectoryInfo')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formDirectoryInfoTableWidget.getTableIndex" :width="80" />
      <vxe-column title="父级菜单" field="parentIdDictMap.name" />
      <vxe-column title="菜单名称" field="menuName" />
      <vxe-column title="显示顺序" field="showOrder" />
      <vxe-column title="是否启用" field="enableDictMap.name" />
      <vxe-column title="菜单类型" field="directoryTypeDictMap.name" />
      <vxe-column title="是否热点项目" field="isHotspotDictMap.name" />
      <vxe-column title="是否精选目的地" field="isWinnowDestinationDictMap.name" />
      <vxe-column title="热门排序" field="hotOrder" />
      <vxe-column title="劳务图片" min-width="100px">
        <template v-slot="scope">
          <el-image v-for="item in parseUploadData(scope.row.hotPictureUrl, { id: scope.row.id, fieldName: 'hotPictureUrl', asImage: true })"
            :preview-src-list="getPictureList(scope.row.hotPictureUrl, { id: scope.row.id, fieldName: 'hotPictureUrl', asImage: true })"
            class="table-cell-image" :key="item.url" :src="item.url" fit="fill">
            <template #error>
              <div class="table-cell-image">
                <i class="el-icon-picture-outline"></i>
              </div>
            </template>
          </el-image>
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditDirectoryInfoClick(scope.row)"
            :disabled="!checkPermCodeExist('formDirectoryInfo:formDirectoryInfo:editDirectoryInfo')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteDirectoryInfoClick(scope.row)"
            :disabled="!checkPermCodeExist('formDirectoryInfo:formDirectoryInfo:deleteDirectoryInfo')"
          >
            删除
          </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="formDirectoryInfoTableWidgetTotalCount"
            :current-page="formDirectoryInfoTableWidgetCurrentPage"
            :page-size="formDirectoryInfoTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formDirectoryInfoTableWidget.onCurrentPageChange"
            @size-change="formDirectoryInfoTableWidget.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: 'formDirectoryInfo',
};
</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 { DirectoryInfoData } from '@/api/generated/directoryInfoController';
import { DirectoryInfoController } from '@/api/generated';
import FormEditDirectoryInfo from '@/pages/directoryInfo/formEditDirectoryInfo.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({
  // 菜单名称
  menuNameFilter: undefined,
  // 父级菜单
  parentIdFilter: undefined,
  // 菜单类型
  directoryTypeFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 是否精选目的地
  isWinnowDestinationFilter: undefined,
});
const formFilterCopy = reactive({
  // 菜单名称
  menuNameFilter: undefined,
  // 父级菜单
  parentIdFilter: undefined,
  // 菜单类型
  directoryTypeFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 是否精选目的地
  isWinnowDestinationFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormDirectoryInfoTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    directoryInfoDtoFilter: {
      menuName: formFilter.menuNameFilter,
      parentId: formFilter.parentIdFilter,
      directoryType: formFilter.directoryTypeFilter,
      isHotspot: formFilter.isHotspotFilter,
      enable: formFilter.enableFilter,
      isWinnowDestination: formFilter.isWinnowDestinationFilter,
    }
  };
  return new Promise((resolve, reject) => {
    DirectoryInfoController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormDirectoryInfoTableVerify = () => {
  formFilterCopy.menuNameFilter = formFilter.menuNameFilter;
  formFilterCopy.parentIdFilter = formFilter.parentIdFilter;
  formFilterCopy.directoryTypeFilter = formFilter.directoryTypeFilter;
  formFilterCopy.isHotspotFilter = formFilter.isHotspotFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  formFilterCopy.isWinnowDestinationFilter = formFilter.isWinnowDestinationFilter;
  return true;
};
/**
 * 新建
 */
const onAddDirectoryInfoClick = (row?: DirectoryInfoData) => {
  let params: ANY_OBJECT = {
  };

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

  Dialog
    .show('编辑', FormEditDirectoryInfo, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formDirectoryInfoTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportDirectoryInfoClick = (row?: DirectoryInfoData) => {
  let params: ANY_OBJECT = {
    directoryInfoDtoFilter: {
      menuName: formFilter.menuNameFilter,
    }
  };

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    DirectoryInfoController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formDirectoryInfoTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formDirectoryInfoTableOptions: TableOptions<DirectoryInfoData> = {
  loadTableData: loadFormDirectoryInfoTableWidgetData,
  verifyTableParameter: loadFormDirectoryInfoTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formDirectoryInfoTable = ref();
const formDirectoryInfoTableWidget = useTable(formDirectoryInfoTableOptions);
const {
  dataList: formDirectoryInfoTableWidgetDataList,
  currentPage: formDirectoryInfoTableWidgetCurrentPage,
  pageSize: formDirectoryInfoTableWidgetPageSize,
  totalCount: formDirectoryInfoTableWidgetTotalCount,
} = formDirectoryInfoTableWidget;
/**
 * 父级菜单下拉数据获取函数
 */
const loadParentIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
      parentId :0
    };
    DictionaryController.dictDirectoryInfoByParentId(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 父级菜单配置参数
const parentIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadParentIdFilterDropdownList,
  isTree: false,
};
// 父级菜单下拉组件
const parentIdFilterWidget = useDropdown(parentIdFilterOptions);
const { dropdownList: parentIdFilterWidgetDropdownList } = parentIdFilterWidget
/**
 * 菜单类型下拉数据获取函数
 */
const loadDirectoryTypeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.CompanyType.getList(),
  });
};
// 菜单类型配置参数
const directoryTypeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadDirectoryTypeFilterDropdownList,
  isTree: false,
};
// 菜单类型下拉组件
const directoryTypeFilterWidget = useDropdown(directoryTypeFilterOptions);
const { dropdownList: directoryTypeFilterWidgetDropdownList } = directoryTypeFilterWidget
/**
 * 是否热点下拉数据获取函数
 */
const loadIsHotspotFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Hotspot.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 loadIsWinnowDestinationFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsWinnowDestination.getList(),
  });
};
// 是否精选目的地 配置参数
const isWinnowDestinationFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsWinnowDestinationFilterDropdownList,
  isTree: false,
};
// 是否精选目的地 下拉组件
const isWinnowDestinationFilterWidget = useDropdown(isWinnowDestinationFilterOptions);
const { dropdownList: isWinnowDestinationFilterWidgetDropdownList } = isWinnowDestinationFilterWidget
const refreshFormDirectoryInfo = () => {
  // 刷新段落
  formDirectoryInfoTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormDirectoryInfo = () => {
  formFilter.menuNameFilter = undefined;
  formFilterCopy.menuNameFilter = undefined;
  formFilter.parentIdFilter = undefined;
  formFilterCopy.parentIdFilter = undefined;
  formFilter.directoryTypeFilter = undefined;
  formFilterCopy.directoryTypeFilter = undefined;
  formFilter.isHotspotFilter = undefined;
  formFilterCopy.isHotspotFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  formFilter.isWinnowDestinationFilter = undefined;
  formFilterCopy.isWinnowDestinationFilter = undefined;
  refreshFormDirectoryInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormDirectoryInfo();
};
const formInit = () => {
  parentIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  directoryTypeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isHotspotFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  isWinnowDestinationFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormDirectoryInfo();
};

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