<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formCarOrderRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormCarOrder()" @reset="resetFormCarOrder">
        <el-form-item label="起点">
          <el-cascader
            class="filter-item"
            v-model="startPlaceIdFilterPath"
            :options="startPlaceIdFilterWidgetDropdownList"
            placeholder=""
            :clearable="true"
            :filterable="true"
            :show-all-levels="false"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
            @change="onStartPlaceIdFilterValueChange"
          />
        </el-form-item>
        <el-form-item label="乘客联系电话">
          <el-input
            class="filter-item"
            v-model="formFilter.connectPhoneFilter"
            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.connectNameFilter"
            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.connectSexFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="connectSexFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in connectSexFilterWidgetDropdownList"
              :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.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-select
            class="filter-item"
            v-model="formFilter.categoryTypeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="categoryTypeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in categoryTypeFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="tourCarOrder"
      class="page-table"
      :data="tourCarOrderWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((tourCarOrderWidgetCurrentPage - 1) * tourCarOrderWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="false"
      @sort-change="tourCarOrderWidget.onSortChange"
      @refresh="tourCarOrderWidget.refreshTable()"
    >
      <vxe-column title="序号" type="seq" :index="tourCarOrderWidget.getTableIndex" :width="80" />
      <vxe-column title="订单号" field="orderNo" />
      <vxe-column title="车型归属" field="categoryTypeDictMap.name" />
      <vxe-column title="车型种类" field="carModelDictMap.name" />
      <vxe-column title="车型车名" field="carName" />
      <vxe-column title="车型座位数" field="carSeatNumber" />
      <vxe-column title="车型行李数" field="carLuggageNumber" />
      <vxe-column title="司机名称" field="driverName" />
      <vxe-column title="司机性别" field="driverSexDictMap.name" />
      <vxe-column title="乘客联系电话" field="connectPhone" />
      <vxe-column title="乘客联系姓名" field="connectName" />
      <vxe-column title="乘客联系人性别" field="connectSexDictMap.name" />
      <vxe-column title="乘车人微信" field="connectWechat" />
      <vxe-column title="起点" field="startPlaceIdDictMap.name" />
      <vxe-column title="订单状态" field="stateDictMap.name" />
      <vxe-column title="账号昵称" field="sysUser.showName" />
      <vxe-column title="账号所在部门" field="sysUser.deptIdDictMap.name" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onFormViewCarOrderClick(scope.row)"
            :disabled="!checkPermCodeExist('formCarOrder:formCarOrder:formViewCarOrder')"
          >
            包车订单详情
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditCarOrderInfoClick(scope.row)"
            :disabled="!checkPermCodeExist('formCarOrder:formCarOrder:editCarOrderInfo')"
          >
            编辑包车订单详情
          </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="tourCarOrderWidgetTotalCount"
            :current-page="tourCarOrderWidgetCurrentPage"
            :page-size="tourCarOrderWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="tourCarOrderWidget.onCurrentPageChange"
            @size-change="tourCarOrderWidget.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: 'formCarOrder',
};
</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 { TourCarDriverData } from '@/api/generated/tourCarDriverController';
import { TourCarOrderData } from '@/api/generated/tourCarOrderController';
import { TourCarCategoryData } from '@/api/generated/tourCarCategoryController';
import { TourCarDriverController, TourCarOrderController, TourCarCategoryController } from '@/api/generated';
import EditCarOrderInfo from '@/pages/tourContractCarInfo/editCarOrderInfo.vue';
import FormViewCarOrder from '@/pages/tourContractCarInfo/formViewCarOrder.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({
  // 起点
  startPlaceIdFilter: undefined,
  // 联系电话
  connectPhoneFilter: undefined,
  // 联系姓名
  connectNameFilter: undefined,
  // 联系人性别
  connectSexFilter: undefined,
  // 订单状态
  stateFilter: undefined,
  // 车型归属
  categoryTypeFilter: undefined,
});
const formFilterCopy = reactive({
  // 起点
  startPlaceIdFilter: undefined,
  // 联系电话
  connectPhoneFilter: undefined,
  // 联系姓名
  connectNameFilter: undefined,
  // 联系人性别
  connectSexFilter: undefined,
  // 订单状态
  stateFilter: undefined,
  // 车型归属
  categoryTypeFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadTourCarOrderWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourCarOrderDtoFilter: {
      startPlaceId: formFilter.startPlaceIdFilter,
      connectPhone: formFilter.connectPhoneFilter,
      connectName: formFilter.connectNameFilter,
      connectSex: formFilter.connectSexFilter,
      state: formFilter.stateFilter,
      categoryType: formFilter.categoryTypeFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourCarOrderController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadTourCarOrderVerify = () => {
  formFilterCopy.startPlaceIdFilter = formFilter.startPlaceIdFilter;
  formFilterCopy.connectPhoneFilter = formFilter.connectPhoneFilter;
  formFilterCopy.connectNameFilter = formFilter.connectNameFilter;
  formFilterCopy.connectSexFilter = formFilter.connectSexFilter;
  formFilterCopy.stateFilter = formFilter.stateFilter;
  formFilterCopy.categoryTypeFilter = formFilter.categoryTypeFilter;
  return true;
};
/**
 * 包车订单详情
 */
const onFormViewCarOrderClick = (row?: TourCarOrderData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('包车订单详情', FormViewCarOrder, { area: ['900px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      tourCarOrderWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑包车订单详情
 */
const onEditCarOrderInfoClick = (row?: TourCarOrderData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑包车订单详情', EditCarOrderInfo, { area: ['900px', '700px'] }, { ...params, subPage: true })
    .then(res => {
      tourCarOrderWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
// 表格组件表格组件参数
const tourCarOrderOptions: TableOptions<TourCarOrderData> = {
  loadTableData: loadTourCarOrderWidgetData,
  verifyTableParameter: loadTourCarOrderVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const tourCarOrder = ref();
const tourCarOrderWidget = useTable(tourCarOrderOptions);
const {
  dataList: tourCarOrderWidgetDataList,
  currentPage: tourCarOrderWidgetCurrentPage,
  pageSize: tourCarOrderWidgetPageSize,
  totalCount: tourCarOrderWidgetTotalCount,
} = tourCarOrderWidget;
/**
 * 起点下拉数据获取函数
 */
const loadStartPlaceIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourCarContractMenu(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 起点选中值改变
 */
const onStartPlaceIdFilterValueChange = (value) => {
  formFilter.startPlaceIdFilter = Array.isArray(value) ? value[value.length - 1] : value;
};
// 起点配置参数
const startPlaceIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadStartPlaceIdFilterDropdownList,
  isTree: true,
};
// 起点选中数据
const startPlaceIdFilterPath = ref<Array<string | number>>([]);
// 起点下拉组件
const startPlaceIdFilterWidget = useDropdown(startPlaceIdFilterOptions);
const { dropdownList: startPlaceIdFilterWidgetDropdownList } = startPlaceIdFilterWidget
/**
 * 联系人性别下拉数据获取函数
 */
const loadConnectSexFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'UserSex', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 联系人性别配置参数
const connectSexFilterOptions: DropdownOptions<DictData> = {
  loadData: loadConnectSexFilterDropdownList,
  isTree: false,
};
// 联系人性别下拉组件
const connectSexFilterWidget = useDropdown(connectSexFilterOptions);
const { dropdownList: connectSexFilterWidgetDropdownList } = connectSexFilterWidget
/**
 * 订单状态下拉数据获取函数
 */
const loadStateFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.TourCarOrderState.getList(),
  });
};
// 订单状态配置参数
const stateFilterOptions: DropdownOptions<DictData> = {
  loadData: loadStateFilterDropdownList,
  isTree: false,
};
// 订单状态下拉组件
const stateFilterWidget = useDropdown(stateFilterOptions);
const { dropdownList: stateFilterWidgetDropdownList } = stateFilterWidget
/**
 * 车型归属下拉数据获取函数
 */
const loadCategoryTypeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.TourCarType.getList(),
  });
};
// 车型归属配置参数
const categoryTypeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadCategoryTypeFilterDropdownList,
  isTree: false,
};
// 车型归属下拉组件
const categoryTypeFilterWidget = useDropdown(categoryTypeFilterOptions);
const { dropdownList: categoryTypeFilterWidgetDropdownList } = categoryTypeFilterWidget
const refreshFormCarOrder = () => {
  // 刷新段落
  tourCarOrderWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormCarOrder = () => {
  formFilter.startPlaceIdFilter = undefined;
  formFilterCopy.startPlaceIdFilter = undefined;
  startPlaceIdFilterPath.value = [];
  formFilter.connectPhoneFilter = undefined;
  formFilterCopy.connectPhoneFilter = undefined;
  formFilter.connectNameFilter = undefined;
  formFilterCopy.connectNameFilter = undefined;
  formFilter.connectSexFilter = undefined;
  formFilterCopy.connectSexFilter = undefined;
  formFilter.stateFilter = undefined;
  formFilterCopy.stateFilter = undefined;
  formFilter.categoryTypeFilter = undefined;
  formFilterCopy.categoryTypeFilter = undefined;
  refreshFormCarOrder();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormCarOrder();
};
const formInit = () => {
  startPlaceIdFilterWidget.onVisibleChange(true).then(res => {
    // TODO: 获取级联选中路径
    startPlaceIdFilterPath.value = findTreeNodePath(res, formFilter.startPlaceIdFilter);
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
  connectSexFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  stateFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  categoryTypeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormCarOrder();
};

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