<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourProjectGroupPurchaseInfoRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourProjectGroupPurchaseInfo()" @reset="resetFormTourProjectGroupPurchaseInfo">
        <el-form-item label="选择旅游项目">
          <SelectBookTourismProject
            class="filter-item"
            v-model="formFilter.projectIdFilter"
            placeholder=""
            :required="false"
            :disabled="false"
            :props="{
              label: 'projectTitle',
              value: 'id'
            }"
          />
        </el-form-item>
        <el-form-item label="拼团截止时间">
          <el-date-picker
            class="filter-item"
            v-model="formFilter.endTimeFilter"
            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-date-picker
            class="filter-item"
            v-model="formFilter.travelStartTimeFilter"
            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-date-picker
            class="filter-item"
            v-model="formFilter.travelEndTimeFilter"
            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="拼团人数上限">
          <input-number-range
            class="filter-item"
            v-model="formFilter.maxCountFilter"
            startPlaceholder=""
            endPlaceholder=""
            :step="1"
          />
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="tourProjectGroupPurchase"
      class="page-table"
      :data="tourProjectGroupPurchaseWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourProjectGroupPurchaseWidgetCurrentPage - 1) * tourProjectGroupPurchaseWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="tourProjectGroupPurchaseWidget.onSortChange"
      @refresh="tourProjectGroupPurchaseWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourProjectGroupPurchaseInfo:formTourProjectGroupPurchaseInfo:add')"
          @click="onAddClick()"
          >
          新增
        </el-button>
      </template>
      <vxe-column title="序号" type="seq" :index="tourProjectGroupPurchaseWidget.getTableIndex" :width="80" />
      <vxe-column title="拼团项目标题" field="tourismProject.projectTitle" />
      <vxe-column title="拼团截止时间" field="endTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.endTime, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="出行开始时间" field="travelStartTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.travelStartTime, 'day')}}</span>
        </template>
      </vxe-column>
      <!-- <vxe-column title="出行结束时间" field="travelEndTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.travelEndTime, 'day')}}</span>
        </template>
      </vxe-column> -->
      <vxe-column title="拼团状态" field="stateDictMap.name" />
      <vxe-column title="拼团人数上限" field="maxCount" />
      <vxe-column title="成人价格" field="adultPrice" />
      <vxe-column title="儿童价格" field="childrenPrice" />
      <vxe-column title="价格单位" field="priceUnit" />
      <vxe-column title="返利价格/人" field="singleRebate" />
      <vxe-column title="显示顺序" field="showOrder" />
      <vxe-column title="当前拼团的人数" field="nowCount" />
      <vxe-column title="拼团是否成功" field="successDictMap.name" />
      <vxe-column title="拼团标题" field="title" />
      <vxe-column title="图片url">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.image, {
                id: scope.row.id,
                fieldName: 'image',
                asImage: true
              })
            "
            type="card"
            direction="horizontal"
            :readonly="true"
          />
        </template>
      </vxe-column>
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourProjectGroupPurchaseInfo:formTourProjectGroupPurchaseInfo:edit')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onFormTourProjectGroupPurchaseDetailClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourProjectGroupPurchaseInfo:formTourProjectGroupPurchaseInfo:formTourProjectGroupPurchaseDetail')"
          >
            拼团设置从表管理
          </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="tourProjectGroupPurchaseWidgetTotalCount"
            :current-page="tourProjectGroupPurchaseWidgetCurrentPage"
            :page-size="tourProjectGroupPurchaseWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourProjectGroupPurchaseWidget.onCurrentPageChange"
            @size-change="tourProjectGroupPurchaseWidget.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: 'formTourProjectGroupPurchaseInfo',
};
</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 { TourProjectGroupPurchaseData } from '@/api/generated/tourProjectGroupPurchaseController';
import { TourismProjectData } from '@/api/generated/tourismProjectController';
import { TourProjectGroupPurchaseDetailData } from '@/api/generated/tourProjectGroupPurchaseDetailController';
import { TourProjectGroupPurchaseController, TourismProjectController, TourProjectGroupPurchaseDetailController } from '@/api/generated';
import FormTourProjectGroupPurchaseDetail from '@/pages/tourProjectGroupPurchase/formTourProjectGroupPurchaseDetail.vue';
import EditTourProjectGroupPurchase from '@/pages/tourProjectGroupPurchase/editTourProjectGroupPurchase.vue';
import SelectBookTourismProject from '@/pages/tourTourismBookInfo/selectBookTourismProject/index.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({
  // 选择旅游项目
  projectIdFilter: undefined,
  // 拼团截止时间
  endTimeFilter: [],
  // 出行开始时间
  travelStartTimeFilter: [],
  // 出行结束时间
  travelEndTimeFilter: [],
  // 拼团状态
  stateFilter: undefined,
  // 拼团人数上限
  maxCountFilter: [],
});
const formFilterCopy = reactive({
  // 选择旅游项目
  projectIdFilter: undefined,
  // 拼团截止时间
  endTimeFilter: [],
  // 出行开始时间
  travelStartTimeFilter: [],
  // 出行结束时间
  travelEndTimeFilter: [],
  // 拼团状态
  stateFilter: undefined,
  // 拼团人数上限
  maxCountFilter: [],
});
// 表格行内编辑用到的所有字典数据
const inlineTableDictList = ref({
  enableDataList: [],
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourProjectGroupPurchaseWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourProjectGroupPurchaseDtoFilter: {
      projectId: formFilter.projectIdFilter,
      endTimeStart: Array.isArray(formFilter.endTimeFilter) ? formFilter.endTimeFilter[0] : formFilter.endTimeFilter,
      endTimeEnd: Array.isArray(formFilter.endTimeFilter) ? formFilter.endTimeFilter[1] : formFilter.endTimeFilter,
      travelStartTimeStart: Array.isArray(formFilter.travelStartTimeFilter) ? formFilter.travelStartTimeFilter[0] : formFilter.travelStartTimeFilter,
      travelStartTimeEnd: Array.isArray(formFilter.travelStartTimeFilter) ? formFilter.travelStartTimeFilter[1] : formFilter.travelStartTimeFilter,
      travelEndTimeStart: Array.isArray(formFilter.travelEndTimeFilter) ? formFilter.travelEndTimeFilter[0] : formFilter.travelEndTimeFilter,
      travelEndTimeEnd: Array.isArray(formFilter.travelEndTimeFilter) ? formFilter.travelEndTimeFilter[1] : formFilter.travelEndTimeFilter,
      state: formFilter.stateFilter,
      maxCountStart: Array.isArray(formFilter.maxCountFilter) ? formFilter.maxCountFilter[0] : formFilter.maxCountFilter,
      maxCountEnd: Array.isArray(formFilter.maxCountFilter) ? formFilter.maxCountFilter[1] : formFilter.maxCountFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourProjectGroupPurchaseController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourProjectGroupPurchaseVerify = () => {
  formFilterCopy.projectIdFilter = formFilter.projectIdFilter;
  formFilterCopy.endTimeFilter = formFilter.endTimeFilter;
  formFilterCopy.travelStartTimeFilter = formFilter.travelStartTimeFilter;
  formFilterCopy.travelEndTimeFilter = formFilter.travelEndTimeFilter;
  formFilterCopy.stateFilter = formFilter.stateFilter;
  formFilterCopy.maxCountFilter = formFilter.maxCountFilter;
  return true;
};
/**
 * 新增
 */
const onAddClick = (row?: TourProjectGroupPurchaseData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新增', EditTourProjectGroupPurchase, { area: ['900px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      tourProjectGroupPurchaseWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditClick = (row?: TourProjectGroupPurchaseData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑', EditTourProjectGroupPurchase, { area: ['900px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      tourProjectGroupPurchaseWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 拼团设置从表管理
 */
const onFormTourProjectGroupPurchaseDetailClick = (row?: TourProjectGroupPurchaseData) => {
  let params: ANY_OBJECT = {
    groupPurchaseCode: row?.code,
  };

  router.push({
    name: 'formTourProjectGroupPurchaseDetail',
    query: { ...params, subPage: true }
  });
};
// 表格组件表格组件参数
const tourProjectGroupPurchaseOptions: TableOptions<TourProjectGroupPurchaseData> = {
  loadTableData: loadTourProjectGroupPurchaseWidgetData,
  verifyTableParameter: loadTourProjectGroupPurchaseVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const tourProjectGroupPurchase = ref();
const tourProjectGroupPurchaseWidget = useTable(tourProjectGroupPurchaseOptions);
const {
  dataList: tourProjectGroupPurchaseWidgetDataList,
  currentPage: tourProjectGroupPurchaseWidgetCurrentPage,
  pageSize: tourProjectGroupPurchaseWidgetPageSize,
  totalCount: tourProjectGroupPurchaseWidgetTotalCount,
} = tourProjectGroupPurchaseWidget;
/**
 * 拼团状态下拉数据获取函数
 */
const loadStateFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Enable.getList(),
  });
};
// 拼团状态配置参数
const stateFilterOptions: DropdownOptions<DictData> = {
  loadData: loadStateFilterDropdownList,
  isTree: false,
};
// 拼团状态下拉组件
const stateFilterWidget = useDropdown(stateFilterOptions);
const { dropdownList: stateFilterWidgetDropdownList } = stateFilterWidget
const refreshFormTourProjectGroupPurchaseInfo = () => {
  // 刷新段落
  tourProjectGroupPurchaseWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourProjectGroupPurchaseInfo = () => {
  formFilter.projectIdFilter = undefined;
  formFilterCopy.projectIdFilter = undefined;
  formFilter.endTimeFilter = undefined;
  formFilterCopy.endTimeFilter = undefined;
  formFilter.travelStartTimeFilter = undefined;
  formFilterCopy.travelStartTimeFilter = undefined;
  formFilter.travelEndTimeFilter = undefined;
  formFilterCopy.travelEndTimeFilter = undefined;
  formFilter.stateFilter = undefined;
  formFilterCopy.stateFilter = undefined;
  formFilter.maxCountFilter = undefined;
  formFilterCopy.maxCountFilter = undefined;
  refreshFormTourProjectGroupPurchaseInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourProjectGroupPurchaseInfo();
};
const loadInlineEnableData = () => {
  return new Promise((resolve, reject) => {
    inlineTableDictList.value.enableDataList = StaticDict.Enable.getList();
    inlineTableDictList.value.enableDataList.forEach(item => {
      item.id = item.id.toString();
    });
    resolve();
  });
};
const loadAllInlineTableDictData = () => {
  return new Promise((resolve, reject) => {
    let promises = [
      loadInlineEnableData(),
    ];
    Promise.all(promises).then(() => {
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
const formInit = () => {
  stateFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourProjectGroupPurchaseInfo();
};

onMounted(() => {
  loadAllInlineTableDictData().then(() => {
    formInit();
  }).catch(() => {
    formInit();
  });
});

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