<template>
  <el-container class="advance-query-form advance-box" style="position: relative;">
    <el-aside width="300px">
      <el-card class="base-card" shadow="never">
        <template #header>
          <div class="base-card-header">
            <span style="color: #333333; font-weight: bold" class="header-title">包车区域菜单</span>
            <div class="base-card-operation">
              <el-button
                class="advance-icon-btn"
                style="width: 40px; height: 32px; padding: 0"
                @click="refreshIdDropdownList"
              >
                <img src="@/assets/img/refresh2.png" alt="" style="vertical-align: middle" />
              </el-button>
            </div>
          </div>
        </template>
        <el-scrollbar :style="{height: (mainContextHeight - 130) + 'px'}" class="custom-scroll">
          <el-tree
            ref="id"
            :props="{label: 'name'}"
            :data="idWidget.dropdownList"
            node-key="id"
            current-node-key="id"
            :highlight-current="true"
            :default-expand-all="true"
            @node-click="onIdValueChange"
          />
        </el-scrollbar>
      </el-card>
    </el-aside>
    <el-main class="page-box" style="padding-left: 15px; display: flex">
    <el-form
      ref="formCarContractMenuRef"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormCarContractMenu()" @reset="resetFormCarContractMenu">
        <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.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="tourCarContractMenu"
        class="page-table"
        :data="tourCarContractMenuWidgetDataList"
        :size="layoutStore.defaultFormItemSize"
        :row-config="{isCurrent: false, isHover: true}"
        :seq-config="{startIndex: ((tourCarContractMenuWidgetCurrentPage - 1) * tourCarContractMenuWidgetPageSize)}"
        :sort-config="{remote: true}"
        :hasExtend="true"
        @sort-change="tourCarContractMenuWidget.onSortChange"
        @refresh="tourCarContractMenuWidget.refreshTable()"
      >
        <template #operator>
          <el-button
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            :disabled="!checkPermCodeExist('formCarContractMenu:formCarContractMenu:add')"
            @click="onAddClick()"
            >
            新建
          </el-button>
        </template>
        <vxe-column title="序号" type="seq" :index="tourCarContractMenuWidget.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="操作" fixed="right">
          <template v-slot="scope">
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              @click.stop="onEditClick(scope.row)"
              :disabled="!checkPermCodeExist('formCarContractMenu:formCarContractMenu:edit')"
            >
              编辑
            </el-button>
            <el-button
              link
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              @click.stop="onDeleteClick(scope.row)"
              :disabled="!checkPermCodeExist('formCarContractMenu:formCarContractMenu: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="tourCarContractMenuWidgetTotalCount"
              :current-page="tourCarContractMenuWidgetCurrentPage"
              :page-size="tourCarContractMenuWidgetPageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, prev, pager, next, sizes"
              @current-change="tourCarContractMenuWidget.onCurrentPageChange"
              @size-change="tourCarContractMenuWidget.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>
    </el-main>
  </el-container>
</template>

<script lang="ts">
export default {
  name: 'formCarContractMenu',
};
</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 { TourCarContractMenuData } from '@/api/generated/tourCarContractMenuController';
import { TourCarContractMenuController } from '@/api/generated';
import EditFormCarConnectMenu from '@/pages/tourContractCarInfo/editFormCarConnectMenu.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({
  // 主键id
  id: undefined,
  // 菜单名称
  menuNameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
});
const formFilterCopy = reactive({
  // 主键id
  id: undefined,
  // 菜单名称
  menuNameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
});

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

const onResume = () => {
  refreshFormCarContractMenu();
};
const id = ref();
const refreshIdDropdownList = () => {
  idWidget.reloadDropdownData().then(dataList => {
    if (
      !Array.isArray(dataList) ||
      dataList.find(item => item.id === formFilter.id) == null
    ) {
      formFilter.id = undefined;
      formFilterCopy.id = undefined;
    }
    if (id.value) id.value.setCurrentKey(formFilter.id);
  });
};
/**
 * 主键id下拉数据获取函数
 */
const loadIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourCarContractMenu(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 主键id选中值改变
 */
const onIdValueChange = (value) => {
  if (value.id !== formFilter.id) {
    formFilter.id = value.id;
  } else {
    formFilter.id = undefined;
    nextTick(() => {
      id.value?.setCurrentKey(null);
    });
  }
  refreshFormCarContractMenu(true);
};
// 主键id配置参数
const idOptions: DropdownOptions<DictData> = {
  loadData: loadIdDropdownList,
  isTree: true,
};
// 主键id下拉组件
const idWidget = useDropdown(idOptions);
const { dropdownList: idWidgetDropdownList } = idWidget
/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourCarContractMenuWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourCarContractMenuDtoFilter: {
      menuName: formFilter.menuNameFilter,
      enable: formFilter.enableFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourCarContractMenuController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourCarContractMenuVerify = () => {
  formFilterCopy.menuNameFilter = formFilter.menuNameFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  formFilterCopy.id = formFilter.id;
  return true;
};
/**
 * 新建
 */
const onAddClick = (row?: TourCarContractMenuData) => {
  let params: ANY_OBJECT = {
  };

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

  Dialog
    .show('编辑', EditFormCarConnectMenu, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      tourCarContractMenuWidget.refreshTable();
      refreshIdDropdownList();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 删除
 */
const onDeleteClick = (row?: TourCarContractMenuData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  TourCarContractMenuController.delete(params).then(res => {
    ElMessage.success('删除成功');
    tourCarContractMenuWidget.refreshTable(false, 1);
    refreshIdDropdownList();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const tourCarContractMenuOptions: TableOptions<TourCarContractMenuData> = {
  loadTableData: loadTourCarContractMenuWidgetData,
  verifyTableParameter: loadTourCarContractMenuVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'showOrder',
  ascending: true,
};
// 表格组件表格组件
const tourCarContractMenu = ref();
const tourCarContractMenuWidget = useTable(tourCarContractMenuOptions);
const {
  dataList: tourCarContractMenuWidgetDataList,
  currentPage: tourCarContractMenuWidgetCurrentPage,
  pageSize: tourCarContractMenuWidgetPageSize,
  totalCount: tourCarContractMenuWidgetTotalCount,
} = tourCarContractMenuWidget;
/**
 * 是否启用下拉数据获取函数
 */
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 refreshFormCarContractMenu = () => {
  // 刷新段落
  tourCarContractMenuWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormCarContractMenu = () => {
  formFilter.menuNameFilter = undefined;
  formFilterCopy.menuNameFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  formFilter.id = undefined;
  formFilterCopy.id = undefined;
  refreshFormCarContractMenu();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormCarContractMenu();
};
const formInit = () => {
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  idWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormCarContractMenu();
};

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

<style scoped>
  ::v-deep .el-tree-node__content {
    height: 35px;
  }
</style>
