<template>
  <div class="page-box" style="position: relative">
    <el-form
      ref="formTourismTravelNotesWriteRef"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box
        :item-width="350"
        @search="refreshFormTourismTravelNotesWrite()"
        @reset="resetFormTourismTravelNotesWrite"
      >
        <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-date-picker
            class="filter-item"
            v-model="formFilter.departureTimeFilter"
            type="daterange"
            start-placeholder=""
            end-placeholder=""
            :clearable="true"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="[new Date().setHours(0, 0, 0, 0), new Date().setHours(23, 59, 59, 999)]"
          />
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            class="filter-item"
            v-model="formFilter.stateFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="stateFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in stateFilterWidgetDropdownList"
              :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="endPlaceFilterPath"
            :options="endPlaceFilterWidgetDropdownList"
            placeholder=""
            :clearable="true"
            :filterable="true"
            :show-all-levels="false"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
            @change="onEndPlaceFilterValueChange"
          />
        </el-form-item>
        <el-form-item label="是否原创">
          <el-select
            class="filter-item"
            v-model="formFilter.isOriginalFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="isOriginalFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in isOriginalFilterWidgetDropdownList"
              :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.unmountStateFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="unmountStateFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in unmountStateFilterWidgetDropdownList"
              :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.travelModeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="travelModeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in travelModeFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="tourismProjectTravelNotesWrite"
      class="page-table"
      :data="tourismProjectTravelNotesWriteWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{ isCurrent: false, isHover: true }"
      :seq-config="{
        startIndex:
          (tourismProjectTravelNotesWriteWidgetCurrentPage - 1) *
          tourismProjectTravelNotesWriteWidgetPageSize,
      }"
      :sort-config="{ remote: true }"
      :hasExtend="false"
      @sort-change="tourismProjectTravelNotesWriteWidget.onSortChange"
      @refresh="tourismProjectTravelNotesWriteWidget.refreshTable()"
    >
      <vxe-column
        title="序号"
        type="seq"
        :index="tourismProjectTravelNotesWriteWidget.getTableIndex"
        :width="80"
      />
      <vxe-column title="游记标题" field="projectTitle" />
      <vxe-column title="出发时间" field="departureTime">
        <template v-slot="scope">
          <span>{{ formatDateByStatsType(scope.row.departureTime, 'day') }}</span>
        </template>
      </vxe-column>
      <vxe-column title="出行天数" field="countTimes" />
      <vxe-column title="人物关系" field="role" />
      <vxe-column title="推荐指数" field="recommendationRate" />
      <vxe-column title="人均费用" field="averageCost" />
      <vxe-column title="出行方式" field="travelModeDictMap.name" />
      <vxe-column title="审核状态" field="stateDictMap.name" />
      <vxe-column title="创建时间" field="createTime">
        <template v-slot="scope">
          <span>{{ formatDateByStatsType(scope.row.createTime, 'day') }}</span>
        </template>
      </vxe-column>
      <vxe-column title="更新时间" field="updateTime">
        <template v-slot="scope">
          <span>{{ formatDateByStatsType(scope.row.updateTime, 'day') }}</span>
        </template>
      </vxe-column>
      <vxe-column title="目的地" field="endPlaceDictMap.name" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onViewClick(scope.row)"
            :disabled="
              !checkPermCodeExist('formTourismTravelNotesWrite:formTourismTravelNotesWrite:view')
            "
          >
            详情
          </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="tourismProjectTravelNotesWriteWidgetTotalCount"
            :current-page="tourismProjectTravelNotesWriteWidgetCurrentPage"
            :page-size="tourismProjectTravelNotesWriteWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourismProjectTravelNotesWriteWidget.onCurrentPageChange"
            @size-change="tourismProjectTravelNotesWriteWidget.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: 'formTourismTravelNotesWrite',
};
</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 { TourismTravelNotesContentWriteData } from '@/api/generated/tourismTravelNotesContentWriteController';
import { TourismProjectTravelNotesWriteData } from '@/api/generated/tourismProjectTravelNotesWriteController';
import {
  TourismTravelNotesContentWriteController,
  TourismProjectTravelNotesWriteController,
} from '@/api/generated';
import ViewTravelNotesInfo from '@/pages/tourismTravelNotesWrite/viewTravelNotesInfo.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({
  // 游记标题
  projectTitleFilter: undefined,
  // 出发时间
  departureTimeFilter: [],
  // 审核状态
  stateFilter: undefined,
  // 目的地
  endPlaceFilter: undefined,
  // 是否原创
  isOriginalFilter: undefined,
  // 上下架状态
  unmountStateFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 出行方式
  travelModeFilter: undefined,
});
const formFilterCopy = reactive({
  // 游记标题
  projectTitleFilter: undefined,
  // 出发时间
  departureTimeFilter: [],
  // 审核状态
  stateFilter: undefined,
  // 目的地
  endPlaceFilter: undefined,
  // 是否原创
  isOriginalFilter: undefined,
  // 上下架状态
  unmountStateFilter: undefined,
  // 是否热点
  isHotspotFilter: undefined,
  // 出行方式
  travelModeFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourismProjectTravelNotesWriteWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourismProjectTravelNotesWriteDtoFilter: {
      projectTitle: formFilter.projectTitleFilter,
      departureTimeStart: Array.isArray(formFilter.departureTimeFilter)
        ? formFilter.departureTimeFilter[0]
        : formFilter.departureTimeFilter,
      departureTimeEnd: Array.isArray(formFilter.departureTimeFilter)
        ? formFilter.departureTimeFilter[1]
        : formFilter.departureTimeFilter,
      state: formFilter.stateFilter,
      unmountState: formFilter.unmountStateFilter,
      isHotspot: formFilter.isHotspotFilter,
      isOriginal: formFilter.isOriginalFilter,
      endPlace: formFilter.endPlaceFilter,
      travelMode: formFilter.travelModeFilter,
    },
  };
  return new Promise((resolve, reject) => {
    TourismProjectTravelNotesWriteController.list(params)
      .then(res => {
        resolve({
          dataList: res.data.dataList,
          totalCount: res.data.totalCount,
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourismProjectTravelNotesWriteVerify = () => {
  formFilterCopy.projectTitleFilter = formFilter.projectTitleFilter;
  formFilterCopy.departureTimeFilter = formFilter.departureTimeFilter;
  formFilterCopy.stateFilter = formFilter.stateFilter;
  formFilterCopy.endPlaceFilter = formFilter.endPlaceFilter;
  formFilterCopy.isOriginalFilter = formFilter.isOriginalFilter;
  formFilterCopy.unmountStateFilter = formFilter.unmountStateFilter;
  formFilterCopy.isHotspotFilter = formFilter.isHotspotFilter;
  formFilterCopy.travelModeFilter = formFilter.travelModeFilter;
  return true;
};
/**
 * 详情
 */
const onViewClick = (row?: TourismProjectTravelNotesWriteData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog.show(
    '详情',
    ViewTravelNotesInfo,
    { area: ['1300px', '700px'] },
    { ...params, subPage: true },
  )
    .then(res => {
      tourismProjectTravelNotesWriteWidget.refreshTable();
    })
    .catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
// 表格组件表格组件参数
const tourismProjectTravelNotesWriteOptions: TableOptions<TourismProjectTravelNotesWriteData> = {
  loadTableData: loadTourismProjectTravelNotesWriteWidgetData,
  verifyTableParameter: loadTourismProjectTravelNotesWriteVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: 'updateTime',
  ascending: false,
};
// 表格组件表格组件
const tourismProjectTravelNotesWrite = ref();
const tourismProjectTravelNotesWriteWidget = useTable(tourismProjectTravelNotesWriteOptions);
const {
  dataList: tourismProjectTravelNotesWriteWidgetDataList,
  currentPage: tourismProjectTravelNotesWriteWidgetCurrentPage,
  pageSize: tourismProjectTravelNotesWriteWidgetPageSize,
  totalCount: tourismProjectTravelNotesWriteWidgetTotalCount,
} = tourismProjectTravelNotesWriteWidget;
/**
 * 审核状态下拉数据获取函数
 */
const loadStateFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.AuditState.getList(),
  });
};
// 审核状态配置参数
const stateFilterOptions: DropdownOptions<DictData> = {
  loadData: loadStateFilterDropdownList,
  isTree: false,
};
// 审核状态下拉组件
const stateFilterWidget = useDropdown(stateFilterOptions);
const { dropdownList: stateFilterWidgetDropdownList } = stateFilterWidget;
/**
 * 目的地下拉数据获取函数
 */
const loadEndPlaceFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {};
    DictionaryController.dictDirectoryInfo(params)
      .then(res => {
        resolve({
          dataList: res.getList(),
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
/**
 * 目的地选中值改变
 */
const onEndPlaceFilterValueChange = value => {
  formFilter.endPlaceFilter = Array.isArray(value) ? value[value.length - 1] : value;
};
// 目的地配置参数
const endPlaceFilterOptions: DropdownOptions<DictData> = {
  loadData: loadEndPlaceFilterDropdownList,
  isTree: true,
};
// 目的地选中数据
const endPlaceFilterPath = ref<Array<string | number>>([]);
// 目的地下拉组件
const endPlaceFilterWidget = useDropdown(endPlaceFilterOptions);
const { dropdownList: endPlaceFilterWidgetDropdownList } = endPlaceFilterWidget;
/**
 * 是否原创下拉数据获取函数
 */
const loadIsOriginalFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsOriginal.getList(),
  });
};
// 是否原创配置参数
const isOriginalFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsOriginalFilterDropdownList,
  isTree: false,
};
// 是否原创下拉组件
const isOriginalFilterWidget = useDropdown(isOriginalFilterOptions);
const { dropdownList: isOriginalFilterWidgetDropdownList } = isOriginalFilterWidget;
/**
 * 上下架状态下拉数据获取函数
 */
const loadUnmountStateFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.UnmountState.getList(),
  });
};
// 上下架状态配置参数
const unmountStateFilterOptions: DropdownOptions<DictData> = {
  loadData: loadUnmountStateFilterDropdownList,
  isTree: false,
};
// 上下架状态下拉组件
const unmountStateFilterWidget = useDropdown(unmountStateFilterOptions);
const { dropdownList: unmountStateFilterWidgetDropdownList } = unmountStateFilterWidget;
/**
 * 是否热点下拉数据获取函数
 */
const loadIsHotspotFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Hotspot.getList(),
  });
};
/**
 * 出行方式下拉数据获取函数
 */
const loadTravelModeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'TourTravelMode', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 出行方式配置参数
const travelModeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadTravelModeFilterDropdownList,
  isTree: false,
};
// 出行方式下拉组件
const travelModeFilterWidget = useDropdown(travelModeFilterOptions);
const { dropdownList: travelModeFilterWidgetDropdownList } = travelModeFilterWidget
// 是否热点配置参数
const isHotspotFilterOptions: DropdownOptions<DictData> = {
  loadData: loadIsHotspotFilterDropdownList,
  isTree: false,
};
// 是否热点下拉组件
const isHotspotFilterWidget = useDropdown(isHotspotFilterOptions);
const { dropdownList: isHotspotFilterWidgetDropdownList } = isHotspotFilterWidget;
const refreshFormTourismTravelNotesWrite = () => {
  // 刷新段落
  tourismProjectTravelNotesWriteWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourismTravelNotesWrite = () => {
  formFilter.projectTitleFilter = undefined;
  formFilterCopy.projectTitleFilter = undefined;
  formFilter.departureTimeFilter = undefined;
  formFilterCopy.departureTimeFilter = undefined;
  formFilter.stateFilter = undefined;
  formFilterCopy.stateFilter = undefined;
  formFilter.endPlaceFilter = undefined;
  formFilterCopy.endPlaceFilter = undefined;
  endPlaceFilterPath.value = [];
  formFilter.isOriginalFilter = undefined;
  formFilterCopy.isOriginalFilter = undefined;
  formFilter.unmountStateFilter = undefined;
  formFilterCopy.unmountStateFilter = undefined;
  formFilter.isHotspotFilter = undefined;
  formFilterCopy.isHotspotFilter = undefined;
  formFilter.travelModeFilter = undefined;
  formFilterCopy.travelModeFilter = undefined;
  refreshFormTourismTravelNotesWrite();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourismTravelNotesWrite();
};
const formInit = () => {
  stateFilterWidget.onVisibleChange(true).catch(e => {
    console.error(e);
  });
  endPlaceFilterWidget
    .onVisibleChange(true)
    .then(res => {
      // TODO: 获取级联选中路径
      endPlaceFilterPath.value = findTreeNodePath(res, formFilter.endPlaceFilter);
    })
    .catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  isOriginalFilterWidget.onVisibleChange(true).catch(e => {
    console.error(e);
  });
  unmountStateFilterWidget.onVisibleChange(true).catch(e => {
    console.error(e);
  });
  isHotspotFilterWidget.onVisibleChange(true).catch(e => {
    console.error(e);
  });
  travelModeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourismTravelNotesWrite();
};

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