<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourOrder"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourOrder()" @reset="resetFormTourOrder">
        <el-form-item label="项目简述">
          <el-input
            class="filter-item"
            v-model="formFilter.projectResumeFilter"
            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.customerNameFilter"
            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.customerMobileFilter"
            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.orderStatusFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="orderStatusFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in orderStatusFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="出发日期">
          <el-date-picker
            class="filter-item"
            v-model="formFilter.departureDateFilter"
            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.endDateFilter"
            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>
      </filter-box>
    </el-form>
    <table-box
      ref="tourOrder"
      class="page-table"
      :data="tourOrderWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourOrderWidgetCurrentPage - 1) * tourOrderWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="tourOrderWidget.onSortChange"
      @refresh="tourOrderWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formTourOrder:formTourOrder:add')"
          @click="onAddClick()"
          >
          新增
        </el-button>
      </template>
      <vxe-column title="序号" type="seq" :index="tourOrderWidget.getTableIndex" :width="80" />
      <vxe-column title="订单号" field="orderNo" />
      <vxe-column title="出发日期" field="departureDate">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.departureDate, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="结束日期" field="endDate">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.endDate, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="订单总金额" field="totalAmount" />
      <vxe-column title="币种" field="currency" />
      <vxe-column title="预定日期" field="orderDate">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.orderDate, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="订单状态" field="orderStatusDictMap.name" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourOrder:formTourOrder:edit')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourOrder:formTourOrder:delete')"
          >
            删除
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onFormTourOrderPassengerClick(scope.row)"
            :disabled="!checkPermCodeExist('formTourOrder:formTourOrder:formTourOrderPassenger')"
          >
            订单游客
          </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="tourOrderWidgetTotalCount"
            :current-page="tourOrderWidgetCurrentPage"
            :page-size="tourOrderWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourOrderWidget.onCurrentPageChange"
            @size-change="tourOrderWidget.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: 'formTourOrder',
};
</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 } from '@/common/utils';
import { TourOrderPassenageData } from '@/api/generated/tourOrderPassenageController';
import { tourOrderData } from '@/api/generated/tourOrderController';
import { TourOrderPassenageController, tourOrderController } from '@/api/generated';
import FormEditTourOrder from '@/pages/tourOrder/formEditTourOrder.vue';
import FormTourOrderPassenger from '@/pages/tourOrder/formTourOrderPassenger.vue';
import FormSelectTourProject from '@/pages/tourOrder/formSelectTourProject/formSelectTourProject.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({
  // 项目简述
  projectResumeFilter: undefined,
  // 顾客姓名
  customerNameFilter: undefined,
  // 顾客手机号
  customerMobileFilter: undefined,
  // 订单状态
  orderStatusFilter: undefined,
  // 出发日期
  departureDateFilter: undefined,
  // 结束日期
  endDateFilter: undefined,
});
const formFilterCopy = reactive({
  // 项目简述
  projectResumeFilter: undefined,
  // 顾客姓名
  customerNameFilter: undefined,
  // 顾客手机号
  customerMobileFilter: undefined,
  // 订单状态
  orderStatusFilter: undefined,
  // 出发日期
  departureDateFilter: undefined,
  // 结束日期
  endDateFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadtourOrderWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourOrderDtoFilter: {
      departureDateStart: Array.isArray(formFilter.departureDateFilter) ? formFilter.departureDateFilter[0] : formFilter.departureDateFilter,
      departureDateEnd: Array.isArray(formFilter.departureDateFilter) ? formFilter.departureDateFilter[1] : formFilter.departureDateFilter,
      endDateStart: Array.isArray(formFilter.endDateFilter) ? formFilter.endDateFilter[0] : formFilter.endDateFilter,
      endDateEnd: Array.isArray(formFilter.endDateFilter) ? formFilter.endDateFilter[1] : formFilter.endDateFilter,
      orderStatus: formFilter.orderStatusFilter,
      projectResume: formFilter.projectResumeFilter,
      customerName: formFilter.customerNameFilter,
      customerMobile: formFilter.customerMobileFilter,
    }
  };
  return new Promise((resolve, reject) => {
    tourOrderController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadtourOrderVerify = () => {
  formFilterCopy.projectResumeFilter = formFilter.projectResumeFilter;
  formFilterCopy.customerNameFilter = formFilter.customerNameFilter;
  formFilterCopy.customerMobileFilter = formFilter.customerMobileFilter;
  formFilterCopy.orderStatusFilter = formFilter.orderStatusFilter;
  formFilterCopy.departureDateFilter = formFilter.departureDateFilter;
  formFilterCopy.endDateFilter = formFilter.endDateFilter;
  return true;
};
/**
 * 新增
 */
const onAddClick = (row?: tourOrderData) => {
  let params: ANY_OBJECT = {
  };

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

  Dialog
    .show('编辑', FormEditTourOrder, { area: ['900px', '650px'] }, { ...params, subPage: true })
    .then(res => {
      tourOrderWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 删除
 */
const onDeleteClick = (row?: tourOrderData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  tourOrderController.delete(params).then(res => {
    ElMessage.success('删除成功');
    tourOrderWidget.refreshTable(false, 1);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 订单游客
 */
const onFormTourOrderPassengerClick = (row?: tourOrderData) => {
  let params: ANY_OBJECT = {
    orderId: row?.id,
  };

  router.push({
    name: 'formTourOrderPassenger',
    query: { ...params, subPage: true }
  });
};
// 表格组件表格组件参数
const tourOrderOptions: TableOptions<tourOrderData> = {
  loadTableData: loadtourOrderWidgetData,
  verifyTableParameter: loadtourOrderVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const tourOrder = ref();
const tourOrderWidget = useTable(tourOrderOptions);
const {
  dataList: tourOrderWidgetDataList,
  currentPage: tourOrderWidgetCurrentPage,
  pageSize: tourOrderWidgetPageSize,
  totalCount: tourOrderWidgetTotalCount,
} = tourOrderWidget;
/**
 * 订单状态下拉数据获取函数
 */
const loadOrderStatusFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'OrderStatus', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 订单状态配置参数
const orderStatusFilterOptions: DropdownOptions<DictData> = {
  loadData: loadOrderStatusFilterDropdownList,
  isTree: false,
};
// 订单状态下拉组件
const orderStatusFilterWidget = useDropdown(orderStatusFilterOptions);
const { dropdownList: orderStatusFilterWidgetDropdownList } = orderStatusFilterWidget
const refreshFormTourOrder = () => {
  // 刷新段落
  tourOrderWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourOrder = () => {
  formFilter.projectResumeFilter = undefined;
  formFilterCopy.projectResumeFilter = undefined;
  formFilter.customerNameFilter = undefined;
  formFilterCopy.customerNameFilter = undefined;
  formFilter.customerMobileFilter = undefined;
  formFilterCopy.customerMobileFilter = undefined;
  formFilter.orderStatusFilter = undefined;
  formFilterCopy.orderStatusFilter = undefined;
  formFilter.departureDateFilter = undefined;
  formFilterCopy.departureDateFilter = undefined;
  formFilter.endDateFilter = undefined;
  formFilterCopy.endDateFilter = undefined;
  refreshFormTourOrder();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourOrder();
};
const formInit = () => {
  orderStatusFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourOrder();
};

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