<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditDeliveryOrderRef"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rules"
        label-width="120px"
        label-position="right"
        @submit.prevent
      >
        <el-row :gutter="16">
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="DeliveryOrder.shopName">
              <el-input
                class="input-item"
                v-model="formData.DeliveryOrder.shopName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送时间" prop="DeliveryOrder.deliveryTime">
              <el-date-picker
                class="input-item"
                v-model="formData.DeliveryOrder.deliveryTime"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送地址" prop="DeliveryOrder.deliveryAddress">
              <el-input
                class="input-item"
                v-model="formData.DeliveryOrder.deliveryAddress"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="收货电话" prop="DeliveryOrder.deliveryPhone">
              <el-input
                class="input-item"
                v-model="formData.DeliveryOrder.deliveryPhone"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="DeliveryOrder.deliveryRemark">
              <el-input
                class="input-item"
                v-model="formData.DeliveryOrder.deliveryRemark"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="餐具数量" prop="DeliveryOrder.tableware">
              <el-input-number
                class="input-item"
                v-model="formData.DeliveryOrder.tableware"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单号" prop="DeliveryOrder.orderNo">
              <el-input
                class="input-item"
                v-model="formData.DeliveryOrder.orderNo"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下单时间" prop="DeliveryOrder.orderTime">
              <el-date-picker
                class="input-item"
                v-model="formData.DeliveryOrder.orderTime"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单金额" prop="DeliveryOrder.orderAmount">
              <el-input-number
                class="input-item"
                v-model="formData.DeliveryOrder.orderAmount"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实付金额" prop="DeliveryOrder.payAmount">
              <el-input-number
                class="input-item"
                v-model="formData.DeliveryOrder.payAmount"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户id" prop="DeliveryOrder.customerId">
              <el-input-number
                class="input-item"
                v-model="formData.DeliveryOrder.customerId"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="打包费" prop="DeliveryOrder.packCharge">
              <el-input-number
                class="input-item"
                v-model="formData.DeliveryOrder.packCharge"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="配送费" prop="DeliveryOrder.deliveryFee">
              <el-input-number
                class="input-item"
                v-model="formData.DeliveryOrder.deliveryFee"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建用户" prop="DeliveryOrder.createUserId">
              <el-input-number
                class="input-item"
                v-model="formData.DeliveryOrder.createUserId"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="DeliveryOrder.createTime">
              <el-date-picker
                class="input-item"
                v-model="formData.DeliveryOrder.createTime"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新用户" prop="DeliveryOrder.updateUserId">
              <el-input-number
                class="input-item"
                v-model="formData.DeliveryOrder.updateUserId"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="DeliveryOrder.updateTime">
              <el-date-picker
                class="input-item"
                v-model="formData.DeliveryOrder.updateTime"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                disabled="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="DeliveryOrder.orderStatus">
              <el-select
                class="input-item"
                v-model="formData.DeliveryOrder.orderStatus"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="orderStatusWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in orderStatusWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="支付方式" prop="DeliveryOrder.payType">
              <el-select
                class="input-item"
                v-model="formData.DeliveryOrder.payType"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="payTypeWidget.onVisibleChange"
                disabled="true"
              >
                <el-option
                  v-for="item in payTypeWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />

              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退款状态" prop="DeliveryOrder.refundStatus">
              <el-select
                class="input-item"
                v-model="formData.DeliveryOrder.refundStatus"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="refundStatusWidget.onVisibleChange"
                disabled="true"
              >
                <el-option
                  v-for="item in refundStatusWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <table-box
              ref="deliveryOrderItems"
              :data="deliveryOrderItemsWidgetDataList"
              style="height: 300px"
              :size="layoutStore.defaultFormItemSize"
              :row-config="{isCurrent: false, isHover: true}"
              :seq-config="{startIndex: ((deliveryOrderItemsWidgetCurrentPage - 1) * deliveryOrderItemsWidgetPageSize)}"
              :sort-config="{remote: true}"
              :hasExtend="false"
              @sort-change="deliveryOrderItemsWidget.onSortChange"
              @refresh="deliveryOrderItemsWidget.refreshTable()"
            >
              <vxe-column title="序号" type="seq" :index="deliveryOrderItemsWidget.getTableIndex" :width="80" />
              <vxe-column title="食品名称" field="foodName" />
              <vxe-column title="价格" field="price" />
              <vxe-column title="数量" field="number" />
              <template slot="empty">
                <div class="table-empty unified-font">
                  <img src="@/assets/img/empty.png">
                  <span>暂无数据</span>
                </div>
              </template>
            </table-box>
          </el-col>
        </el-row>
      </el-form>
    </el-scrollbar>
    <el-row class="footer-box" type="flex" justify="end" align="middle">
      <el-button :size="layoutStore.defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="layoutStore.defaultFormItemSize" type="primary" @click="onSubmitDeliveryOrderClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditDeliveryOrder',
};
</script>

<script setup lang="ts">
import { DialogProp } from '@/components/Dialog/types';
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';

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;
    id?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    id: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

const formEditDeliveryOrderRef = ref();
// 表单数据定义
type FormEditDeliveryOrderData = {
  DeliveryOrder: DeliveryOrderData;
};
// 表单数据
const formData = reactive<FormEditDeliveryOrderData>({
  DeliveryOrder: {
    // 主键
    id: undefined,
    // 配送时间
    deliveryTime: undefined,
    // 配送地址
    deliveryAddress: undefined,
    // 收货电话
    deliveryPhone: undefined,
    // 备注
    deliveryRemark: undefined,
    // 餐具数量
    tableware: undefined,
    // 订单号
    orderNo: undefined,
    // 下单时间
    orderTime: undefined,
    // 支付方式
    payType: undefined,
    // 订单金额
    orderAmount: undefined,
    // 实付金额
    payAmount: undefined,
    // 订单状态
    orderStatus: undefined,
    // 用户id
    customerId: undefined,
    // 退款状态
    refundStatus: undefined,
    // 打包费
    packCharge: undefined,
    // 配送费
    deliveryFee: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 店铺名称
    shopName: undefined,
    // 外卖订单明细管理数据
    deliveryOrderItemsList: [],
  },
},
);
// 表单验证规则
const rules = reactive({
  'DeliveryOrder.deliveryRemark': [
  ],
  'DeliveryOrder.deliveryFee': [
  ],
  'DeliveryOrder.tableware': [
  ],
  'DeliveryOrder.shopName': [
    {required: true, message: '请输入店铺名称', trigger: 'blur'}
  ],
  'DeliveryOrder.deliveryAddress': [
  ],
  'DeliveryOrder.refundStatus': [
  ],
  'DeliveryOrder.deliveryPhone': [
  ],
  'DeliveryOrder.packCharge': [
  ],
  'DeliveryOrder.orderTime': [
  ],
  'DeliveryOrder.updateUserId': [
  ],
  'DeliveryOrder.updateTime': [
  ],
  'DeliveryOrder.payType': [
  ],
  'DeliveryOrder.createUserId': [
  ],
  'DeliveryOrder.orderNo': [
  ],
  'DeliveryOrder.createTime': [
  ],
  'DeliveryOrder.orderStatus': [
  ],
  'DeliveryOrder.deliveryTime': [
  ],
  'DeliveryOrder.customerId': [
  ],
  'DeliveryOrder.orderAmount': [
  ],
  'DeliveryOrder.payAmount': [
  ],
});

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  }
};

const isEdit = computed(() => {
  return props.saveOnSubmit ? props.id != null : props.rowData != null;
});

// 初始化页面数据
const loadDeliveryOrderData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.DeliveryOrder = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    DeliveryOrderController.view(params).then(res => {
      formData.DeliveryOrder = { ...res.data };
      deliveryOrderItemsWidget.refreshTable();
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 订单状态下拉数据获取函数
 */
const loadOrderStatusDropdownList = (): 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 orderStatusOptions: DropdownOptions<DictData> = {
  loadData: loadOrderStatusDropdownList,
  isTree: false,
};
// 订单状态下拉组件
const orderStatusWidget = useDropdown(orderStatusOptions);
const { dropdownList: orderStatusWidgetDropdownList } = orderStatusWidget
/**
 * 支付方式下拉数据获取函数
 */
const loadPayTypeDropdownList = (): 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 payTypeOptions: DropdownOptions<DictData> = {
  loadData: loadPayTypeDropdownList,
  isTree: false,
};
// 支付方式下拉组件
const payTypeWidget = useDropdown(payTypeOptions);
const { dropdownList: payTypeWidgetDropdownList } = payTypeWidget
/**
 * 退款状态下拉数据获取函数
 */
const loadRefundStatusDropdownList = (): 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 refundStatusOptions: DropdownOptions<DictData> = {
  loadData: loadRefundStatusDropdownList,
  isTree: false,
};
// 退款状态下拉组件
const refundStatusWidget = useDropdown(refundStatusOptions);
const { dropdownList: refundStatusWidgetDropdownList } = refundStatusWidget
/**
 * 外卖订单明细管理数据获取函数，返回Promise
 */
const loadDeliveryOrderItemsWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    deliveryOrderItemsDtoFilter: {
      orderId: props.id ||formData.DeliveryOrder.id
    }
  };
  return new Promise((resolve, reject) => {
    DeliveryOrderItemsController.list(params).then(res => {
      // 级联更新设置临时唯一id
      let tempTime = new Date().getTime();
      nextTick(() => {
        formData.DeliveryOrder.deliveryOrderItemsList = deliveryOrderItemsWidgetDataList.value;
      });
      resolve({
        dataList: res.data.dataList.map((item, index) => {
          return {
            __cascade_add_temp_id__: tempTime + index,
            ...item
          }
        }),
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 外卖订单明细管理数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadDeliveryOrderItemsVerify = () => {
  return true;
};
// 外卖订单明细管理表格组件参数
const deliveryOrderItemsOptions: TableOptions<DeliveryOrderItemsData> = {
  loadTableData: loadDeliveryOrderItemsWidgetData,
  verifyTableParameter: loadDeliveryOrderItemsVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 外卖订单明细管理表格组件
const deliveryOrderItems = ref();
const deliveryOrderItemsWidget = useTable(deliveryOrderItemsOptions);
const {
  dataList: deliveryOrderItemsWidgetDataList,
  currentPage: deliveryOrderItemsWidgetCurrentPage,
  pageSize: deliveryOrderItemsWidgetPageSize,
  totalCount: deliveryOrderItemsWidgetTotalCount,
} = deliveryOrderItemsWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditDeliveryOrder = () => {
  // 刷新段落
  deliveryOrderItemsWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormEditDeliveryOrder = () => {
  refreshFormEditDeliveryOrder();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditDeliveryOrder();
};
/**
 * 保存
 */
const onSubmitDeliveryOrderClick = () => {
  formEditDeliveryOrderRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.DeliveryOrder
      };
    formData.orderStatusDictMap = findItemFromList(orderStatusWidgetDropdownList, formData.orderStatus, 'id');
    formData.payTypeDictMap = findItemFromList(payTypeWidgetDropdownList, formData.payType, 'id');
    formData.refundStatusDictMap = findItemFromList(refundStatusWidgetDropdownList, formData.refundStatus, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      deliveryOrderDto: {
        id: formData.DeliveryOrder.id,
        shopName: formData.DeliveryOrder.shopName,
        deliveryTime: formData.DeliveryOrder.deliveryTime,
        deliveryAddress: formData.DeliveryOrder.deliveryAddress,
        deliveryPhone: formData.DeliveryOrder.deliveryPhone,
        deliveryRemark: formData.DeliveryOrder.deliveryRemark,
        tableware: formData.DeliveryOrder.tableware,
        orderNo: formData.DeliveryOrder.orderNo,
        orderTime: formData.DeliveryOrder.orderTime,
        payType: formData.DeliveryOrder.payType,
        orderAmount: formData.DeliveryOrder.orderAmount,
        payAmount: formData.DeliveryOrder.payAmount,
        orderStatus: formData.DeliveryOrder.orderStatus,
        customerId: formData.DeliveryOrder.customerId,
        refundStatus: formData.DeliveryOrder.refundStatus,
        packCharge: formData.DeliveryOrder.packCharge,
        deliveryFee: formData.DeliveryOrder.deliveryFee,
        createUserId: formData.DeliveryOrder.createUserId,
        createTime: formData.DeliveryOrder.createTime,
        updateUserId: formData.DeliveryOrder.updateUserId,
        updateTime: formData.DeliveryOrder.updateTime,
      }
    };

    let httpCall = isEdit.value ? DeliveryOrderController.update : DeliveryOrderController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadDeliveryOrderData().then(res => {
    orderStatusWidget.onVisibleChange(true).catch(e => {console.error(e)});
    payTypeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    refundStatusWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshFormEditDeliveryOrder();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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