<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formTourVisaOrderRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormTourVisaOrder()" @reset="resetFormTourVisaOrder">
        <el-form-item label="下单人姓名">
          <el-input
            class="filter-item"
            v-model="formFilter.orderNameFilter"
            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.orderPhoneFilter"
            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.orderIdCardFilter"
            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.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.payStateFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="payStateFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in payStateFilterWidgetDropdownList"
              :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.counselorIdFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="counselorIdFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in counselorIdFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formTourVisaOrderTable"
      class="page-table"
      :data="formTourVisaOrderTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formTourVisaOrderTableWidgetCurrentPage - 1) * formTourVisaOrderTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formTourVisaOrderTableWidget.onSortChange"
      @refresh="formTourVisaOrderTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onAddTourVisaOrderClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          @click="onExportTourVisaOrderClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :on-change="onImportTourVisaOrderClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formTourVisaOrderTableWidget.getTableIndex" :width="80" />
      <vxe-column title="下单人姓名" field="orderName" />
      <vxe-column title="下单人电话" field="orderPhone" />
      <vxe-column title="下单身份证" field="orderIdCard" />
      <vxe-column title="签证商品" field="visaIdDictMap.name" />
      <vxe-column title="订单状态" field="stateDictMap.name" />
      <vxe-column title="支付状态" field="payStateDictMap.name" />
      <vxe-column title="订单价格" field="orderPrice" />
      <vxe-column title="负责顾问" field="counselorIdDictMap.name" />
      <vxe-column title="订单地址" field="orderAddress" />
      <vxe-column title="服务费" field="servicePrice" />
      <vxe-column title="税费" field="price" />
      <vxe-column title="文件列表" min-width="180px">
        <template v-slot="scope">
          <upload-file-list
            :file-list="
              parseUploadData(scope.row.file, {
                id: scope.row.id,
                fieldName: 'file',
                asImage: false
              })
            "
            type="text"
            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="onEditTourVisaOrderClick(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteTourVisaOrderClick(scope.row)"
          >
            删除
          </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="formTourVisaOrderTableWidgetTotalCount"
            :current-page="formTourVisaOrderTableWidgetCurrentPage"
            :page-size="formTourVisaOrderTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formTourVisaOrderTableWidget.onCurrentPageChange"
            @size-change="formTourVisaOrderTableWidget.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: 'formTourVisaOrder',
};
</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 { TourVisaOrderData } from '@/api/generated/tourVisaOrderController';
import { TourVisaOrderController } from '@/api/generated';
import FormEditTourVisaOrder from '@/pages/tourVisaOrder/formEditTourVisaOrder.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({
  // 下单人姓名
  orderNameFilter: undefined,
  // 下单人电话
  orderPhoneFilter: undefined,
  // 下单身份证
  orderIdCardFilter: undefined,
  // 订单状态
  stateFilter: undefined,
  // 支付状态
  payStateFilter: undefined,
  // 负责顾问
  counselorIdFilter: undefined,
});
const formFilterCopy = reactive({
  // 下单人姓名
  orderNameFilter: undefined,
  // 下单人电话
  orderPhoneFilter: undefined,
  // 下单身份证
  orderIdCardFilter: undefined,
  // 订单状态
  stateFilter: undefined,
  // 支付状态
  payStateFilter: undefined,
  // 负责顾问
  counselorIdFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormTourVisaOrderTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    tourVisaOrderDtoFilter: {
      orderName: formFilter.orderNameFilter,
      orderPhone: formFilter.orderPhoneFilter,
      orderIdCard: formFilter.orderIdCardFilter,
      state: formFilter.stateFilter,
      payState: formFilter.payStateFilter,
      counselorId: formFilter.counselorIdFilter,
    }
  };
  return new Promise((resolve, reject) => {
    TourVisaOrderController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormTourVisaOrderTableVerify = () => {
  formFilterCopy.orderNameFilter = formFilter.orderNameFilter;
  formFilterCopy.orderPhoneFilter = formFilter.orderPhoneFilter;
  formFilterCopy.orderIdCardFilter = formFilter.orderIdCardFilter;
  formFilterCopy.stateFilter = formFilter.stateFilter;
  formFilterCopy.payStateFilter = formFilter.payStateFilter;
  formFilterCopy.counselorIdFilter = formFilter.counselorIdFilter;
  return true;
};
/**
 * 新建
 */
const onAddTourVisaOrderClick = (row?: TourVisaOrderData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditTourVisaOrder, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourVisaOrderTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 编辑
 */
const onEditTourVisaOrderClick = (row?: TourVisaOrderData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑', FormEditTourVisaOrder, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formTourVisaOrderTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportTourVisaOrderClick = (row?: TourVisaOrderData) => {
  let params: ANY_OBJECT = {
  };

  TourVisaOrderController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 导入
 */
const onImportTourVisaOrderClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  TourVisaOrderController.import(params).then(res => {
    ElMessage.success('导入成功');
    formTourVisaOrderTableWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 删除
 */
const onDeleteTourVisaOrderClick = (row?: TourVisaOrderData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    TourVisaOrderController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formTourVisaOrderTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formTourVisaOrderTableOptions: TableOptions<TourVisaOrderData> = {
  loadTableData: loadFormTourVisaOrderTableWidgetData,
  verifyTableParameter: loadFormTourVisaOrderTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formTourVisaOrderTable = ref();
const formTourVisaOrderTableWidget = useTable(formTourVisaOrderTableOptions);
const {
  dataList: formTourVisaOrderTableWidgetDataList,
  currentPage: formTourVisaOrderTableWidgetCurrentPage,
  pageSize: formTourVisaOrderTableWidgetPageSize,
  totalCount: formTourVisaOrderTableWidgetTotalCount,
} = formTourVisaOrderTableWidget;
/**
 * 订单状态下拉数据获取函数
 */
const loadStateFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.VisaOrderState.getList(),
  });
};
// 订单状态配置参数
const stateFilterOptions: DropdownOptions<DictData> = {
  loadData: loadStateFilterDropdownList,
  isTree: false,
};
// 订单状态下拉组件
const stateFilterWidget = useDropdown(stateFilterOptions);
const { dropdownList: stateFilterWidgetDropdownList } = stateFilterWidget
/**
 * 支付状态下拉数据获取函数
 */
const loadPayStateFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.VisaPayState.getList(),
  });
};
// 支付状态配置参数
const payStateFilterOptions: DropdownOptions<DictData> = {
  loadData: loadPayStateFilterDropdownList,
  isTree: false,
};
// 支付状态下拉组件
const payStateFilterWidget = useDropdown(payStateFilterOptions);
const { dropdownList: payStateFilterWidgetDropdownList } = payStateFilterWidget
/**
 * 负责顾问下拉数据获取函数
 */
const loadCounselorIdFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourVisaCounselor(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 负责顾问配置参数
const counselorIdFilterOptions: DropdownOptions<DictData> = {
  loadData: loadCounselorIdFilterDropdownList,
  isTree: false,
};
// 负责顾问下拉组件
const counselorIdFilterWidget = useDropdown(counselorIdFilterOptions);
const { dropdownList: counselorIdFilterWidgetDropdownList } = counselorIdFilterWidget
const refreshFormTourVisaOrder = () => {
  // 刷新段落
  formTourVisaOrderTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormTourVisaOrder = () => {
  formFilter.orderNameFilter = undefined;
  formFilterCopy.orderNameFilter = undefined;
  formFilter.orderPhoneFilter = undefined;
  formFilterCopy.orderPhoneFilter = undefined;
  formFilter.orderIdCardFilter = undefined;
  formFilterCopy.orderIdCardFilter = undefined;
  formFilter.stateFilter = undefined;
  formFilterCopy.stateFilter = undefined;
  formFilter.payStateFilter = undefined;
  formFilterCopy.payStateFilter = undefined;
  formFilter.counselorIdFilter = undefined;
  formFilterCopy.counselorIdFilter = undefined;
  refreshFormTourVisaOrder();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormTourVisaOrder();
};
const formInit = () => {
  stateFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  payStateFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  counselorIdFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormTourVisaOrder();
};

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