<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourOrderRef"
        :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="tourOrder.departureDate">
              <el-date-picker
                class="input-item"
                v-model="formData.tourOrder.departureDate"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="tourOrder.endDate">
              <el-date-picker
                class="input-item"
                v-model="formData.tourOrder.endDate"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单总金额" prop="tourOrder.totalAmount">
              <el-input-number
                class="input-item"
                v-model="formData.tourOrder.totalAmount"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="币种" prop="tourOrder.currency">
              <el-input
                class="input-item"
                v-model="formData.tourOrder.currency"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预定日期" prop="tourOrder.orderDate">
              <el-date-picker
                class="input-item"
                v-model="formData.tourOrder.orderDate"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="tourOrder.orderStatus">
              <el-select
                class="input-item"
                v-model="formData.tourOrder.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="tourOrder.customerName">
              <el-input
                class="input-item"
                v-model="formData.tourOrder.customerName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="顾客手机号" prop="tourOrder.customerMobile">
              <el-input
                class="input-item"
                v-model="formData.tourOrder.customerMobile"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="旅游项目" prop="tourOrder.projectId">
              <FormSelectTourProject
                class="input-item"
                v-model="formData.tourOrder.projectId"
                placeholder=""
                :required="false"
                :disabled="false"
                :props="{
                  label: 'projectTitle',
                  value: 'id'
                }"
              />
            </el-form-item>
          </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="onSaveClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourOrder',
};
</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 { TourismProjectData } from '@/api/generated/tourismProjectController';
import { TourOrderPassenageData } from '@/api/generated/tourOrderPassenageController';
import { tourOrderData } from '@/api/generated/tourOrderController';
import { TourismProjectController, TourOrderPassenageController, tourOrderController } from '@/api/generated';
import FormSelectTourProject from '@/pages/tourOrder/formSelectTourProject/index.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;
    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 formEditTourOrderRef = ref();
// 表单数据定义
type FormEditTourOrderData = {
  tourOrder: tourOrderData;
};
// 表单数据
const formData = reactive<FormEditTourOrderData>({
  tourOrder: {
    // ID主键
    id: undefined,
    // 订单号
    orderNo: undefined,
    // 出发日期
    departureDate: undefined,
    // 结束日期
    endDate: undefined,
    // 成人数量
    adultNumber: undefined,
    // 儿童数量
    childrenNumber: undefined,
    // 币种
    currency: undefined,
    // 订单总金额
    totalAmount: undefined,
    // 房间数量
    roomNumber: undefined,
    // 车辆信息
    carId: undefined,
    // 车辆金额
    carAmount: undefined,
    // 预定日期
    orderDate: undefined,
    // 订单状态
    orderStatus: undefined,
    // 旅游项目
    projectId: undefined,
    // 项目简述
    projectResume: undefined,
    // 顾客姓名
    customerName: undefined,
    // 顾客手机号
    customerMobile: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    tourismProject: {
      // 主键id
      id: undefined,
      // 项目标题
      projectTitle: undefined,
      // 项目简述
      remarks: undefined,
      // 是否热点
      isHotspot: undefined,
      // 标签
      projectLabel: undefined,
      // 显示顺序
      showOrder: undefined,
      // 是否启用
      enable: undefined,
      // 所属分类
      belongTab: undefined,
      // 出发地
      startPlace: undefined,
      // 目的地
      endPlace: undefined,
      // 总天数
      countTimes: undefined,
      // 项目价格
      price: undefined,
      // 项目展示图片
      tourismUrl: undefined,
      // 创建用户
      createUserId: undefined,
      // 创建时间
      createTime: undefined,
      // 更新用户
      updateUserId: undefined,
      // 更新时间
      updateTime: undefined,
      // 删除标记(1: 正常 -1: 已删除)
      dataState: undefined,
      // 价格单位
      priceUnit: undefined,
      // 服务保障
      serviceEnsure: undefined,
      // 联系电话
      contactNumber: undefined,
      // 产品卖点
      sellingPoint: undefined,
      // 短标题
      shortTitle: undefined,
      // 短描述
      shortDescription: undefined,
      // 首页热门图片
      homeHotPicture: undefined,
      // 联系人描述
      contactDescription: undefined,
      // 游记banner
      travelNotesBanner: undefined,
      // 点赞量
      likeCount: undefined,
      // 浏览量
      pageViewCount: undefined,
      // 人物关系
      role: undefined,
      // 出发时间
      departureTime: undefined,
      // 人均费用
      averageCost: undefined,
      // 推荐指数
      recommendationRate: undefined,
    },
  },
},
);
// 表单验证规则
const rules = reactive({
  'tourOrder.currency': [
    {required: true, message: '请输入币种', trigger: 'blur'}
  ],
  'tourOrder.customerMobile': [
    {required: true, message: '请输入顾客手机号', trigger: 'blur'}
  ],
  'tourOrder.totalAmount': [
    {required: true, message: '请输入订单总金额', trigger: 'blur'}
  ],
  'tourOrder.orderDate': [
    {required: true, message: '请输入预定日期', trigger: 'blur'}
  ],
  'tourOrder.departureDate': [
    {required: true, message: '请输入出发日期', trigger: 'blur'}
  ],
  'tourOrder.projectId': [
  ],
  'tourOrder.orderStatus': [
    {required: true, message: '请输入订单状态', trigger: 'blur'}
  ],
  'tourOrder.customerName': [
    {required: true, message: '请输入顾客姓名', trigger: 'blur'}
  ],
  'tourOrder.endDate': [
    {required: true, message: '请输入结束日期', trigger: 'blur'}
  ],
});

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

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

// 初始化页面数据
const loadtourOrderData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.tourOrder = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    tourOrderController.view(params).then(res => {
      formData.tourOrder = { ...res.data };
      if (formData.tourOrder.tourismProject == null) {
        formData.tourOrder.tourismProject = {
          id: undefined,
          projectTitle: undefined,
          remarks: undefined,
          isHotspot: undefined,
          projectLabel: undefined,
          showOrder: undefined,
          enable: undefined,
          belongTab: undefined,
          startPlace: undefined,
          endPlace: undefined,
          countTimes: undefined,
          price: undefined,
          tourismUrl: undefined,
          createUserId: undefined,
          createTime: undefined,
          updateUserId: undefined,
          updateTime: undefined,
          dataState: undefined,
          priceUnit: undefined,
          serviceEnsure: undefined,
          contactNumber: undefined,
          sellingPoint: undefined,
          shortTitle: undefined,
          shortDescription: undefined,
          homeHotPicture: undefined,
          contactDescription: undefined,
          travelNotesBanner: undefined,
          likeCount: undefined,
          pageViewCount: undefined,
          role: undefined,
          departureTime: undefined,
          averageCost: undefined,
          recommendationRate: undefined
        };
      }
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 订单状态下拉数据获取函数
 */
const loadOrderStatusDropdownList = (): 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 orderStatusOptions: DropdownOptions<DictData> = {
  loadData: loadOrderStatusDropdownList,
  isTree: false,
};
// 订单状态下拉组件
const orderStatusWidget = useDropdown(orderStatusOptions);
const { dropdownList: orderStatusWidgetDropdownList } = orderStatusWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourOrder = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourOrder = () => {
  refreshFormEditTourOrder();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourOrder();
};
/**
 * 保存
 */
const onSaveClick = () => {
  formEditTourOrderRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.tourOrder
      };
    formData.orderStatusDictMap = findItemFromList(orderStatusWidgetDropdownList, formData.orderStatus, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      tourOrderDto: {
        id: formData.tourOrder.id,
        orderNo: formData.tourOrder.orderNo,
        departureDate: formData.tourOrder.departureDate,
        endDate: formData.tourOrder.endDate,
        adultNumber: formData.tourOrder.adultNumber,
        childrenNumber: formData.tourOrder.childrenNumber,
        currency: formData.tourOrder.currency,
        totalAmount: formData.tourOrder.totalAmount,
        roomNumber: formData.tourOrder.roomNumber,
        carId: formData.tourOrder.carId,
        carAmount: formData.tourOrder.carAmount,
        orderDate: formData.tourOrder.orderDate,
        orderStatus: formData.tourOrder.orderStatus,
        projectId: formData.tourOrder.projectId,
        projectResume: formData.tourOrder.projectResume,
        customerName: formData.tourOrder.customerName,
        customerMobile: formData.tourOrder.customerMobile,
        createUserId: formData.tourOrder.createUserId,
        createTime: formData.tourOrder.createTime,
        updateUserId: formData.tourOrder.updateUserId,
        updateTime: formData.tourOrder.updateTime,
      }
    };

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

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