<template>
  <div class="dialog-box" style="position: relative">
    <el-form
      class="filter-box"
      ref="formSelectProject"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormSelectProject()" @reset="resetFormSelectProject">
        <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-input
            class="filter-item"
            v-model="formFilter.remarksFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="出发地">
          <el-input
            class="filter-item"
            v-model="formFilter.startPlaceFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="目的地">
          <el-input
            class="filter-item"
            v-model="formFilter.endPlaceFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <template #operation>
          <el-button
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            :disabled="selectItemList.length <= 0"
            @click="onSubmit(true)"
          >
            添加
          </el-button>
        </template>
      </filter-box>
    </el-form>
    <table-box
      ref="tourTourismProjectTravelNotes"
      class="content-box"
      :data="tourTourismProjectTravelNotesWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourTourismProjectTravelNotesWidgetCurrentPage - 1) * tourTourismProjectTravelNotesWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="false"
      :checkedMethod="rowChecked"
      @sort-change="tourTourismProjectTravelNotesWidget.onSortChange"
      @refresh="tourTourismProjectTravelNotesWidget.refreshTable()"
      @change="onTourTourismProjectTravelNotesSelectionChange"
    >
      <vxe-column type="checkbox" :width="40" />
      <vxe-column title="序号" type="seq" :index="tourTourismProjectTravelNotesWidget.getTableIndex" :width="80" />
      <vxe-column title="项目标题" field="projectTitle" />
      <vxe-column title="标签" field="projectLabel" />
      <vxe-column title="出发地" field="startPlace" />
      <vxe-column title="目的地" field="endPlace" />
      <vxe-column title="总天数" field="countTimes" />
      <vxe-column title="是否热点" field="isHotspotDictMap.name" />
      <vxe-column title="是否启用" field="enableDictMap.name" />
      <vxe-column title="所属分类" field="belongTabDictMap.name" />
      <vxe-column title="项目价格" field="price" />
      <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="tourTourismProjectTravelNotesWidgetTotalCount"
            :current-page="tourTourismProjectTravelNotesWidgetCurrentPage"
            :page-size="tourTourismProjectTravelNotesWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourTourismProjectTravelNotesWidget.onCurrentPageChange"
            @size-change="tourTourismProjectTravelNotesWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formSelectProject',
};
</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 { TourTourismTravelNotesContentData } from '@/api/generated/tourTourismTravelNotesContentController';
import { TourTourismTravelNotesFileData } from '@/api/generated/tourTourismTravelNotesFileController';
import { TourTourismProjectTravelNotesData } from '@/api/generated/tourTourismProjectTravelNotesController';
import { TourismProjectController, TourTourismTravelNotesContentController, TourTourismTravelNotesFileController, TourTourismProjectTravelNotesController } 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 props = withDefaults(
  defineProps<{
    id?: string | number | undefined;
    travelNotesId?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    selectIdList?: Array<string | number>;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    travelNotesId: undefined,
    saveOnSubmit: true,
    selectIdList: undefined,
    dialog: undefined,
  },
);

const formSelectProject = ref();
const selectItemList = ref<TourismProjectData[]>([]);
const formFilter = reactive({
  // 项目标题
  projectTitleFilter: undefined,
  // 项目简述
  remarksFilter: undefined,
  // 出发地
  startPlaceFilter: undefined,
  // 目的地
  endPlaceFilter: undefined,
});
const formFilterCopy = reactive({
  // 项目标题
  projectTitleFilter: undefined,
  // 项目简述
  remarksFilter: undefined,
  // 出发地
  startPlaceFilter: undefined,
  // 目的地
  endPlaceFilter: undefined,
});

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};
const onSubmit = () => {
  if (!props.saveOnSubmit) {
    props.dialog?.submit(selectItemList.value);
    return;
  }
  let params: ANY_OBJECT = {
    travelNotesId: props.travelNotesId,
    tourTravelNotesProjectRelationDtoList: selectItemList.value.map((item) => {
      return {
        projectId: item.id
      };
    })
  };

  TourTourismProjectTravelNotesController.addTourTravelNotesProjectRelation(params).then(res => {
    ElMessage.success('添加成功');
    props.dialog?.submit(selectItemList.value);
  }).catch(e => {
    // 异常处理
    console.error(e);
  });
};
/**
 * 旅游项目游记管理数据获取函数，返回Promise
 */
const loadTourTourismProjectTravelNotesWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourismProjectDtoFilter: {
      projectTitle: formFilter.projectTitleFilter,
      remarks: formFilter.remarksFilter,
      startPlace: formFilter.startPlaceFilter,
      endPlace: formFilter.endPlaceFilter,
    },
    id: props.travelNotesId,
  };
  return new Promise((resolve, reject) => {
    TourTourismProjectTravelNotesController.listNotInTourTravelNotesProjectRelation(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
      selectItemList.value = [];
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 旅游项目游记管理数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourTourismProjectTravelNotesVerify = () => {
  formFilterCopy.projectTitleFilter = formFilter.projectTitleFilter;
  formFilterCopy.remarksFilter = formFilter.remarksFilter;
  formFilterCopy.startPlaceFilter = formFilter.startPlaceFilter;
  formFilterCopy.endPlaceFilter = formFilter.endPlaceFilter;
  return true;
};
// 旅游项目游记管理表格组件参数
const tourTourismProjectTravelNotesOptions: TableOptions<TourismProjectData> = {
  loadTableData: loadTourTourismProjectTravelNotesWidgetData,
  verifyTableParameter: loadTourTourismProjectTravelNotesVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 旅游项目游记管理表格组件
const tourTourismProjectTravelNotes = ref();
const tourTourismProjectTravelNotesWidget = useTable(tourTourismProjectTravelNotesOptions);
const {
  dataList: tourTourismProjectTravelNotesWidgetDataList,
  currentPage: tourTourismProjectTravelNotesWidgetCurrentPage,
  pageSize: tourTourismProjectTravelNotesWidgetPageSize,
  totalCount: tourTourismProjectTravelNotesWidgetTotalCount,
} = tourTourismProjectTravelNotesWidget;
// 表格行数据选中事件
const onTourTourismProjectTravelNotesSelectionChange = (val: TourismProjectData[]) => {
  selectItemList.value = val;
};
// 表格行是否允许被选中
const rowChecked = ({ row }: { row: TourismProjectData }) => {
  if (Array.isArray(props.selectIdList) && props.selectIdList.length > 0) {
    return props.selectIdList.indexOf(row.id) === -1;
  }
  return true;
};
const refreshFormSelectProject = () => {
  // 刷新段落
  tourTourismProjectTravelNotesWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormSelectProject = () => {
  formFilter.projectTitleFilter = undefined;
  formFilterCopy.projectTitleFilter = undefined;
  formFilter.remarksFilter = undefined;
  formFilterCopy.remarksFilter = undefined;
  formFilter.startPlaceFilter = undefined;
  formFilterCopy.startPlaceFilter = undefined;
  formFilter.endPlaceFilter = undefined;
  formFilterCopy.endPlaceFilter = undefined;
  refreshFormSelectProject();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormSelectProject();
};
const formInit = () => {
  refreshFormSelectProject();
};

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