<template>
  <div class="item-select-dlg dialog-box">
    <el-form
      ref="selectTourismProjectRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshSelectTourismProject()" @reset="resetSelectTourismProject">
        <el-form-item label="项目标题">
          <el-input
            class="filter-item"
            v-model="formFilter.projectTitleFilter"
            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>
        <el-form-item label="所属分类">
          <el-cascader
            class="filter-item"
            v-model="belongTabFilterPath"
            :options="belongTabFilterWidgetDropdownList"
            placeholder=""
            :clearable="true"
            :filterable="true"
            :show-all-levels="false"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
            @change="onBelongTabFilterValueChange"
          />
        </el-form-item>
        <template #operation>
          <el-button type="primary" @click="onSubmit" :size="layoutStore.defaultFormItemSize">
            确定
          </el-button>
        </template>
      </filter-box>
    </el-form>
    <table-box
      ref="tourismProject"
      class="main-box"
      :data="tourismProjectWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourismProjectWidgetCurrentPage - 1) * tourismProjectWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="false"
      @sort-change="tourismProjectWidget.onSortChange"
      @refresh="tourismProjectWidget.refreshTable()"
      @radio-select-change="onSelectChange"
    >
      <vxe-column title="" type="radio" align="center" :width="80" />
      <vxe-column title="项目标题" field="projectTitle" />
      <vxe-column title="是否热点" field="isHotspotDictMap.name" />
      <vxe-column title="是否启用" field="enableDictMap.name" />
      <vxe-column title="标签" field="projectLabel" />
      <vxe-column title="总天数" field="countTimes" />
      <vxe-column title="项目价格" field="price" />
      <vxe-column title="价格单位" field="priceUnit" />
      <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="tourismProjectWidgetTotalCount"
            :current-page="tourismProjectWidgetCurrentPage"
            :page-size="tourismProjectWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourismProjectWidget.onCurrentPageChange"
            @size-change="tourismProjectWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

<script lang="ts">
export default {
  name: 'selectTourismProject',
};
</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 } from '@/common/utils';
import { TourismProjectData } from '@/api/generated/tourismProjectController';
import { TourismContentData } from '@/api/generated/tourismContentController';
import { TourismFileData } from '@/api/generated/tourismFileController';
import { TourismProjectController, TourismContentController, TourismFileController } 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: TourismProjectData[];
    subPage?: number | string | boolean;
    props: {
      label: string;
      value: string;
    };
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    modelValue: () => [],
    props: () => {
      return {
        label: 'name',
        value: 'id',
      };
    },
    dialog: undefined,
  },
);
// 选中数据
const dialogSelectItems = ref<TourismProjectData>();
const formFilter = reactive({
  // 项目标题
  projectTitleFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 所属分类
  belongTabFilter: undefined,
});
const formFilterCopy = reactive({
  // 项目标题
  projectTitleFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 是否启用
  enableFilter: undefined,
  // 所属分类
  belongTabFilter: undefined,
});

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

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

/**
 * 重置过滤值
 */
const resetSelectTourismProject = () => {
  formFilter.projectTitleFilter = undefined;
  formFilterCopy.projectTitleFilter = undefined;
  formFilter.isHotspotFilter = undefined;
  formFilterCopy.isHotspotFilter = undefined;
  formFilter.enableFilter = undefined;
  formFilterCopy.enableFilter = undefined;
  formFilter.belongTabFilter = undefined;
  formFilterCopy.belongTabFilter = undefined;
  belongTabFilterPath.value = [];
  refreshSelectTourismProject();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetSelectTourismProject();
};
/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourismProjectWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourismProjectDtoFilter: {
      projectTitle: formFilter.projectTitleFilter,
      isHotspot: formFilter.isHotspotFilter,
      enable: formFilter.enableFilter,
      belongTab: formFilter.belongTabFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourismProjectController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
      nextTick(() => {
        setTableSelectRow();
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourismProjectVerify = () => {
  formFilterCopy.projectTitleFilter = formFilter.projectTitleFilter;
  formFilterCopy.isHotspotFilter = formFilter.isHotspotFilter;
  formFilterCopy.enableFilter = formFilter.enableFilter;
  formFilterCopy.belongTabFilter = formFilter.belongTabFilter;
  return true;
};
// 表格组件表格组件参数
const tourismProjectOptions: TableOptions<TourismProjectData> = {
  loadTableData: loadTourismProjectWidgetData,
  verifyTableParameter: loadTourismProjectVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'createTime',
  ascending: false,
};
// 表格组件表格组件
const tourismProject = ref();
const tourismProjectWidget = useTable(tourismProjectOptions);
const {
  dataList: tourismProjectWidgetDataList,
  currentPage: tourismProjectWidgetCurrentPage,
  pageSize: tourismProjectWidgetPageSize,
  totalCount: tourismProjectWidgetTotalCount,
} = tourismProjectWidget;
/**
 * 是否热点下拉数据获取函数
 */
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 loadBelongTabFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictDirectoryInfo(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 所属分类选中值改变
 */
const onBelongTabFilterValueChange = (value) => {
  formFilter.belongTabFilter = Array.isArray(value) ? value[value.length - 1] : value;
};
// 所属分类配置参数
const belongTabFilterOptions: DropdownOptions<DictData> = {
  loadData: loadBelongTabFilterDropdownList,
  isTree: true,
};
// 所属分类选中数据
const belongTabFilterPath = ref<Array<string | number>>([]);
// 所属分类下拉组件
const belongTabFilterWidget = useDropdown(belongTabFilterOptions);
const { dropdownList: belongTabFilterWidgetDropdownList } = belongTabFilterWidget
const setTableSelectRow = () => {
  if (tourismProject.value == null || !Array.isArray(tourismProjectWidget.dataList.value))
    return;
  setTimeout(() => {
    let selectRow = findItemFromList(
      tourismProjectWidget.dataList.value,
      (dialogSelectItems.value || {})[pps.props.value],
      pps.props.value,
    );
    tourismProject.value.getTableImpl().setRadioRow(selectRow);
  }, 50);
};
const refreshSelectTourismProject = () => {
  // 重新获取数据组件的数据
  tourismProjectWidget.refreshTable();
};
const onSelectChange = (row?: TourismProjectData) => {
  dialogSelectItems.value = row;
};

const formInit = () => {
  isHotspotFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  enableFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  belongTabFilterWidget.onVisibleChange(true).then(res => {
    // TODO: 获取级联选中路径
    belongTabFilterPath.value = findTreeNodePath(res, formFilter.belongTabFilter);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
  refreshSelectTourismProject();
};

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>
