<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourImGroupTypeRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourImGroupType()" @reset="resetFormTourImGroupType">
<!--        <el-form-item label="类型选择">-->
<!--          <el-cascader-->
<!--            class="filter-item"-->
<!--            v-model="idFilterPath"-->
<!--            :options="idFilterWidgetDropdownList"-->
<!--            placeholder=""-->
<!--            :clearable="true"-->
<!--            :filterable="true"-->
<!--            :show-all-levels="false"-->
<!--            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"-->
<!--            @change="onIdFilterValueChange"-->
<!--          />-->
<!--        </el-form-item>-->
       <!-- <el-form-item label="一级类型选择">
          <el-cascader
            class="filter-item"
            v-model="parentIdFilter_copyPath"
            :options="parentIdFilter_copyWidgetDropdownList"
            placeholder=""
            :clearable="true"
            :filterable="true"
            :show-all-levels="false"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
            @change="onParentIdFilter_copyValueChange"
          />
        </el-form-item> -->
        <el-form-item label="类型名称">
          <el-input
            class="filter-item"
            v-model="formFilter.typeNameFilter"
            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="formTourImGroupTypeTable"
      class="page-table"
      :data="formTourImGroupTypeTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourImGroupTypeTableWidgetCurrentPage - 1) * formTourImGroupTypeTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourImGroupTypeTableWidget.onSortChange"
      @refresh="formTourImGroupTypeTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourImGroupType:formTourImGroupType:addTourImGroupType')"
          @click="onAddTourImGroupTypeClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourImGroupType:formTourImGroupType:exportTourImGroupType')"
          @click="onExportTourImGroupTypeClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formTourImGroupType:formTourImGroupType:importTourImGroupType')"
          :on-change="onImportTourImGroupTypeClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formTourImGroupType:formTourImGroupType:importTourImGroupType')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourImGroupTypeTableWidget.getTableIndex" :width="80" />
      <vxe-column title="父级类型" field="parentIdDictMap.name" >
        <template v-slot="scope">
          <span>{{scope.row?.parentIdDictMap?.name ?? '-'}}</span>
        </template>
      </vxe-column>>

      <vxe-column title="类型名称" field="typeName" />
      <vxe-column title="一级类型图标">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.typeIcon, {
                id: scope.row.id,
                fieldName: 'typeIcon',
                asImage: true
              })
            "
            type="card"
            direction="horizontal"
            :readonly="true"
          />
        </template>
      </vxe-column>
      <vxe-column title="是否启用 " field="enableDictMap.name" />
<!--      <vxe-column title="创建人id" field="createUserId" />-->
      <vxe-column title="创建时间" field="createTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.createTime, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditTourImGroupTypeClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourImGroupType:formTourImGroupType:editTourImGroupType')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteTourImGroupTypeClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourImGroupType:formTourImGroupType:deleteTourImGroupType')"
          >
            删除
          </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="formTourImGroupTypeTableWidgetTotalCount"
            :current-page="formTourImGroupTypeTableWidgetCurrentPage"
            :page-size="formTourImGroupTypeTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourImGroupTypeTableWidget.onCurrentPageChange"
            @size-change="formTourImGroupTypeTableWidget.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: 'formTourImGroupType',
};
</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 { TourImGroupTypeData } from '@/api/generated/tourImGroupTypeController';
import { TourImGroupTypeController } from '@/api/generated';
import FormEditTourImGroupType from '@/pages/ImGroup/formEditTourImGroupType.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({
  // 类型选择
  idFilter: undefined,
  // 一级类型选择
  parentIdFilter_copy: undefined,
  // 类型名称
  typeNameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
});
const formFilterCopy = reactive({
  // 类型选择
  idFilter: undefined,
  // 一级类型选择
  parentIdFilter_copy: undefined,
  // 类型名称
  typeNameFilter: undefined,
  // 是否启用
  enableFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourImGroupTypeTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourImGroupTypeDtoFilter: {
      id: formFilter.idFilter,
      parentId: formFilter.parentIdFilter_copy,
      typeName: formFilter.typeNameFilter,
      enable: formFilter.enableFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourImGroupTypeController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourImGroupTypeTableVerify = () => {
  formFilterCopy.idFilter = formFilter.idFilter;
  formFilterCopy.parentIdFilter_copy = formFilter.parentIdFilter_copy;
  formFilterCopy.typeNameFilter = formFilter.typeNameFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  return true;
};
/**
 * 新建
 */
const onAddTourImGroupTypeClick = (row?: TourImGroupTypeData) => {
  let params: ANY_OBJECT = {
  };

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

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

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourImGroupTypeController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourImGroupTypeTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourImGroupTypeTableOptions: TableOptions<TourImGroupTypeData> = {
  loadTableData: loadFormTourImGroupTypeTableWidgetData,
  verifyTableParameter: loadFormTourImGroupTypeTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourImGroupTypeTable = ref();
const formTourImGroupTypeTableWidget = useTable(formTourImGroupTypeTableOptions);
const {
  dataList: formTourImGroupTypeTableWidgetDataList,
  currentPage: formTourImGroupTypeTableWidgetCurrentPage,
  pageSize: formTourImGroupTypeTableWidgetPageSize,
  totalCount: formTourImGroupTypeTableWidgetTotalCount,
} = formTourImGroupTypeTableWidget;
/**
 * 类型选择下拉数据获取函数
 */
const loadIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourImGroupType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 类型选择选中值改变
 */
const onIdFilterValueChange = (value) => {
  formFilter.idFilter = Array.isArray(value) ? value[value.length - 1] : value;
};
// 类型选择配置参数
const idFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIdFilterDropdownList,
  isTree: true,
};
// 类型选择选中数据
const idFilterPath = ref<Array<string | number>>([]);
// 类型选择下拉组件
const idFilterWidget = useDropdown(idFilterOptions);
const { dropdownList: idFilterWidgetDropdownList } = idFilterWidget
/**
 * 一级类型选择下拉数据获取函数
 */
const loadParentIdFilter_copyDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourImGroupType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 一级类型选择选中值改变
 */
const onParentIdFilter_copyValueChange = (value) => {
  formFilter.parentIdFilter_copy = Array.isArray(value) ? value[value.length - 1] : value;
};
// 一级类型选择配置参数
const parentIdFilter_copyOptions: DropdownOptions<DictData> = {
  loadData: loadParentIdFilter_copyDropdownList,
  isTree: true,
};
// 一级类型选择选中数据
const parentIdFilter_copyPath = ref<Array<string | number>>([]);
// 一级类型选择下拉组件
const parentIdFilter_copyWidget = useDropdown(parentIdFilter_copyOptions);
const { dropdownList: parentIdFilter_copyWidgetDropdownList } = parentIdFilter_copyWidget
/**
 * 是否启用 下拉数据获取函数
 */
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 refreshFormTourImGroupType = () => {
  // 刷新段落
  formTourImGroupTypeTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourImGroupType = () => {
  formFilter.idFilter = undefined;
  formFilterCopy.idFilter = undefined;
  idFilterPath.value = [];
  formFilter.parentIdFilter_copy = undefined;
  formFilterCopy.parentIdFilter_copy = undefined;
  parentIdFilter_copyPath.value = [];
  formFilter.typeNameFilter = undefined;
  formFilterCopy.typeNameFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  refreshFormTourImGroupType();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourImGroupType();
};
const formInit = () => {
  idFilterWidget.onVisibleChange(true).then(res => {
    // TODO: 获取级联选中路径
    idFilterPath.value = findTreeNodePath(res, formFilter.idFilter);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
  parentIdFilter_copyWidget.onVisibleChange(true).then(res => {
    // TODO: 获取级联选中路径
    parentIdFilter_copyPath.value = findTreeNodePath(res, formFilter.parentIdFilter_copy);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourImGroupType();
};

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

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