<template>
  <div class="item-select-dlg dialog-box">
    <el-form
      ref="formSelectTypeRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormSelectType()" @reset="resetFormSelectType">
        <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="是否启用">
          <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>
        <template #operation>
          <el-button type="primary" @click="onSubmit" :size="layoutStore.defaultFormItemSize">
            确定
          </el-button>
        </template>
      </filter-box>
    </el-form>
    <table-box
      ref="restaurantFoodType"
      class="main-box"
      :data="restaurantFoodTypeWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((restaurantFoodTypeWidgetCurrentPage - 1) * restaurantFoodTypeWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="false"
      @sort-change="restaurantFoodTypeWidget.onSortChange"
      @refresh="restaurantFoodTypeWidget.refreshTable()"
      @radio-select-change="onSelectChange"
    >
      <vxe-column title="" type="radio" align="center" :width="80" />
      <vxe-column title="种类名称" field="name" />
      <vxe-column title="餐馆id" field="restaurantIdDictMap.name" />
      <vxe-column title="是否启用" field="enableDictMap.name" />
      <vxe-column title="显示顺序" field="showOrder" />
      <vxe-column title="描述" field="description" />
      <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="restaurantFoodTypeWidgetTotalCount"
            :current-page="restaurantFoodTypeWidgetCurrentPage"
            :page-size="restaurantFoodTypeWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="restaurantFoodTypeWidget.onCurrentPageChange"
            @size-change="restaurantFoodTypeWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

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

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
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 { RestaurantFoodTypeData } from '@/api/generated/restaurantFoodTypeController';
import { RestaurantFoodTypeController } from '@/api/generated';

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 pps = withDefaults(
  defineProps<{
    modelValue: RestaurantFoodTypeData[];
    subPage?: number | string | boolean;
    props: {
      label: string;
      value: string;
      restaurantId: string,
    };
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    modelValue: () => [],
    props: () => {
      return {
        label: 'name',
        value: 'id',
        restaurantId: 'restaurantId',
      };
    },
    dialog: undefined,
  },
);
// 选中数据
const dialogSelectItems = ref<RestaurantFoodTypeData>();
const formFilter = reactive({
  // 种类名称
  nameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  restaurantId: undefined,
});
const formFilterCopy = reactive({
  // 种类名称
  nameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  restaurantId: undefined,
});

const onCancel = () => {
  if (pps.dialog) {
    pps.dialog.cancel();
  }
};

const onSubmit = () => {
  if (pps.dialog) {
    pps.dialog.submit(dialogSelectItems.value);
  }
};

/**
 * 重置过滤值
 */
const resetFormSelectType = () => {
  formFilter.nameFilter = undefined;
  formFilterCopy.nameFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  refreshFormSelectType();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormSelectType();
};
/**
 * 表格组件数据获取函数，返回Promise
 */
const loadRestaurantFoodTypeWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  console.log(232313525415215)
  console.log(pps.props.restaurantId)
  params = {
    ...params,
    restaurantFoodTypeDtoFilter: {
      name: formFilter.nameFilter,
      enable: formFilter.enableFilter,
      restaurantId: pps.props.restaurantId
    }
  };
  return new Promise((resolve, reject) => {
    RestaurantFoodTypeController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
      nextTick(() => {
        setTableSelectRow();
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadRestaurantFoodTypeVerify = () => {
  formFilterCopy.nameFilter = formFilter.nameFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  return true;
};
// 表格组件表格组件参数
const restaurantFoodTypeOptions: TableOptions<RestaurantFoodTypeData> = {
  loadTableData: loadRestaurantFoodTypeWidgetData,
  verifyTableParameter: loadRestaurantFoodTypeVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const restaurantFoodType = ref();
const restaurantFoodTypeWidget = useTable(restaurantFoodTypeOptions);
const {
  dataList: restaurantFoodTypeWidgetDataList,
  currentPage: restaurantFoodTypeWidgetCurrentPage,
  pageSize: restaurantFoodTypeWidgetPageSize,
  totalCount: restaurantFoodTypeWidgetTotalCount,
} = restaurantFoodTypeWidget;
/**
 * 是否启用下拉数据获取函数
 */
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 setTableSelectRow = () => {
  if (restaurantFoodType.value == null || !Array.isArray(restaurantFoodTypeWidget.dataList.value))
    return;
  setTimeout(() => {
    let selectRow = findItemFromList(
      restaurantFoodTypeWidget.dataList.value,
      (dialogSelectItems.value || {})[pps.props.value],
      pps.props.value,
    );
    restaurantFoodType.value.getTableImpl().setRadioRow(selectRow);
  }, 50);
};
const refreshFormSelectType = () => {
  // 重新获取数据组件的数据
  restaurantFoodTypeWidget.refreshTable();
};
const onSelectChange = (row?: RestaurantFoodTypeData) => {
  dialogSelectItems.value = row;
};

const formInit = () => {
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormSelectType();
};

onMounted(() => {
  if (Array.isArray(pps.modelValue) && pps.modelValue.length > 0) {
    dialogSelectItems.value = {
      ...pps.modelValue[0],
    };
  }
  formInit();
});
</script>

<style scoped>
.main-box {
  flex-grow: 1;
}
</style>
