<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formDeliveryOrderRef"
      :model="formData"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormDeliveryOrder()" @reset="resetFormDeliveryOrder">
        <el-form-item label="店铺名称">
          <el-input
            class="filter-item"
            v-model="formFilter.shopNameFilter"
            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.deliveryPhoneFilter_copy"
            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.orderNoFilter"
            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.payTypeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="payTypeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in payTypeFilterWidgetDropdownList"
              :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.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-select
            class="filter-item"
            v-model="formFilter.refundStatusFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="refundStatusFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in refundStatusFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formDeliveryOrderTable"
      class="page-table"
      :data="formDeliveryOrderTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formDeliveryOrderTableWidgetCurrentPage - 1) * formDeliveryOrderTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formDeliveryOrderTableWidget.onSortChange"
      @refresh="formDeliveryOrderTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formDeliveryOrder:formDeliveryOrder:exportDeliveryOrder')"
          @click="onExportDeliveryOrderClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formDeliveryOrder:formDeliveryOrder:importDeliveryOrder')"
          :on-change="onImportDeliveryOrderClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formDeliveryOrder:formDeliveryOrder:importDeliveryOrder')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formDeliveryOrderTableWidget.getTableIndex" :width="80" />
      <vxe-column title="订单号" field="orderNo" />
      <vxe-column title="店铺名称" field="shopName" />
      <vxe-column title="收货电话" field="deliveryPhone" />
      <vxe-column title="配送地址" field="deliveryAddress" />
      <vxe-column title="下单时间" field="orderTime">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.orderTime, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="配送时间" field="deliveryTime" sortable>
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.deliveryTime, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="餐具数量" field="tableware" />
      <vxe-column title="订单金额" field="orderAmount" />
      <vxe-column title="实付金额" field="payAmount" />
      <vxe-column title="备注" field="deliveryRemark" />
      <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="onListDeliveryOrderItemsClick(scope.row)"
            :disabled="!checkPermCodeExist('formDeliveryOrder:formDeliveryOrder:listDeliveryOrderItems')"
          >
            订单明细
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onFormEditDeliveryOrderClick(scope.row)"
            :disabled="!checkPermCodeExist('formDeliveryOrder:formDeliveryOrder:formEditDeliveryOrder')"
          >
            编辑外卖订单管理
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteDeliveryOrderClick(scope.row)"
            :disabled="!checkPermCodeExist('formDeliveryOrder:formDeliveryOrder:deleteDeliveryOrder')"
          >
            删除
          </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="formDeliveryOrderTableWidgetTotalCount"
            :current-page="formDeliveryOrderTableWidgetCurrentPage"
            :page-size="formDeliveryOrderTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formDeliveryOrderTableWidget.onCurrentPageChange"
            @size-change="formDeliveryOrderTableWidget.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: 'formDeliveryOrder',
};
</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 { DeliveryOrderData } from '@/api/generated/deliveryOrderController';
import { DeliveryOrderItemsData } from '@/api/generated/deliveryOrderItemsController';
import { DeliveryOrderController, DeliveryOrderItemsController } from '@/api/generated';
import FormDeliveryOrderItems from '@/pages/generated/formDeliveryOrderItems.vue';
import FormEditDeliveryOrder from '@/pages/generated/formEditDeliveryOrder.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({
  // 店铺名称
  shopNameFilter: undefined,
  // 收货电话
  deliveryPhoneFilter_copy: undefined,
  // 订单号
  orderNoFilter: undefined,
  // 支付方式
  payTypeFilter: undefined,
  // 订单状态
  orderStatusFilter: undefined,
  // 退款状态
  refundStatusFilter: undefined,
});
const formFilterCopy = reactive({
  // 店铺名称
  shopNameFilter: undefined,
  // 收货电话
  deliveryPhoneFilter_copy: undefined,
  // 订单号
  orderNoFilter: undefined,
  // 支付方式
  payTypeFilter: undefined,
  // 订单状态
  orderStatusFilter: undefined,
  // 退款状态
  refundStatusFilter: undefined,
});

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

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

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormDeliveryOrderTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    deliveryOrderDtoFilter: {
      // 店铺名称
     shopName:formFilter.shopNameFilter,
      // 收货电话
     deliveryPhone:formFilter.deliveryPhoneFilter_copy,
      // 订单号
     orderNo:formFilter.orderNoFilter,
      // 支付方式
     payType:formFilter.payTypeFilter,
      // 订单状态
     orderStatus:formFilter.orderStatusFilter,
      // 退款状态
     refundStatus:formFilter.refundStatusFilter,
    }
  };
  return new Promise((resolve, reject) => {
    DeliveryOrderController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormDeliveryOrderTableVerify = () => {
  formFilterCopy.shopNameFilter = formFilter.shopNameFilter;
  formFilterCopy.deliveryPhoneFilter_copy = formFilter.deliveryPhoneFilter_copy;
  formFilterCopy.orderNoFilter = formFilter.orderNoFilter;
  formFilterCopy.payTypeFilter = formFilter.payTypeFilter;
  formFilterCopy.orderStatusFilter = formFilter.orderStatusFilter;
  formFilterCopy.refundStatusFilter = formFilter.refundStatusFilter;
  return true;
};
/**
 * 订单明细
 */
const onListDeliveryOrderItemsClick = (row?: DeliveryOrderData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  router.push({
    name: 'formDeliveryOrderItems',
    query: { ...params, subPage: true }
  });
};
/**
 * 编辑外卖订单管理
 */
const onFormEditDeliveryOrderClick = (row?: DeliveryOrderData) => {
  let params: ANY_OBJECT = {
    id: row?.id,
  };

  Dialog
    .show('编辑外卖订单管理', FormEditDeliveryOrder, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formDeliveryOrderTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportDeliveryOrderClick = (row?: DeliveryOrderData) => {
  let params: ANY_OBJECT = {
  };

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

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

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    DeliveryOrderController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formDeliveryOrderTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formDeliveryOrderTableOptions: TableOptions<DeliveryOrderData> = {
  loadTableData: loadFormDeliveryOrderTableWidgetData,
  verifyTableParameter: loadFormDeliveryOrderTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formDeliveryOrderTable = ref();
const formDeliveryOrderTableWidget = useTable(formDeliveryOrderTableOptions);
const {
  dataList: formDeliveryOrderTableWidgetDataList,
  currentPage: formDeliveryOrderTableWidgetCurrentPage,
  pageSize: formDeliveryOrderTableWidgetPageSize,
  totalCount: formDeliveryOrderTableWidgetTotalCount,
} = formDeliveryOrderTableWidget;
/**
 * 支付方式下拉数据获取函数
 */
const loadPayTypeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'DeliveryPayType', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 支付方式配置参数
const payTypeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadPayTypeFilterDropdownList,
  isTree: false,
};
// 支付方式下拉组件
const payTypeFilterWidget = useDropdown(payTypeFilterOptions);
const { dropdownList: payTypeFilterWidgetDropdownList } = payTypeFilterWidget
/**
 * 订单状态下拉数据获取函数
 */
const loadOrderStatusFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'DeliveryOrderStatus', 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 loadRefundStatusFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'DeliveryOrderRefundStatus', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 退款状态配置参数
const refundStatusFilterOptions: DropdownOptions<DictData> = {
  loadData: loadRefundStatusFilterDropdownList,
  isTree: false,
};
// 退款状态下拉组件
const refundStatusFilterWidget = useDropdown(refundStatusFilterOptions);
const { dropdownList: refundStatusFilterWidgetDropdownList } = refundStatusFilterWidget
const refreshFormDeliveryOrder = () => {
  // 刷新段落
  formDeliveryOrderTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormDeliveryOrder = () => {
  formFilter.shopNameFilter = undefined;
  formFilterCopy.shopNameFilter = undefined;
  formFilter.deliveryPhoneFilter_copy = undefined;
  formFilterCopy.deliveryPhoneFilter_copy = undefined;
  formFilter.orderNoFilter = undefined;
  formFilterCopy.orderNoFilter = undefined;
  formFilter.payTypeFilter = undefined;
  formFilterCopy.payTypeFilter = undefined;
  formFilter.orderStatusFilter = undefined;
  formFilterCopy.orderStatusFilter = undefined;
  formFilter.refundStatusFilter = undefined;
  formFilterCopy.refundStatusFilter = undefined;
  refreshFormDeliveryOrder();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormDeliveryOrder();
};
const formInit = () => {
  payTypeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  orderStatusFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refundStatusFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  refreshFormDeliveryOrder();
};

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