<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourBookInfo"
        :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="TourBookInfo.type">
              <el-radio-group
                class="input-item"
                v-model="formData.TourBookInfo.type"
              >
                <el-radio
                  v-for="item in typeWidgetDropdownList"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="预定种类的id" prop="TourBookInfo.projectId">
              <el-input
                class="input-item"
                v-model="formData.TourBookInfo.projectId"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="预定电话" prop="TourBookInfo.bookMobile">
              <el-input
                class="input-item"
                v-model="formData.TourBookInfo.bookMobile"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="预定姓名" prop="TourBookInfo.bookName">
              <el-input
                class="input-item"
                v-model="formData.TourBookInfo.bookName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="预定的ip" prop="TourBookInfo.bookIp">
              <el-input
                class="input-item"
                v-model="formData.TourBookInfo.bookIp"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="预定时间" prop="TourBookInfo.bookTime">
              <el-date-picker
                class="input-item"
                v-model="formData.TourBookInfo.bookTime"
                type="datetime"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="是否处理" prop="TourBookInfo.isHandle">
              <el-radio-group
                class="input-item"
                v-model="formData.TourBookInfo.isHandle"
              >
                <el-radio
                  v-for="item in isHandleWidgetDropdownList"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成人人数" prop="TourBookInfo.adultNumber">
              <el-input-number
                class="input-item"
                v-model="formData.TourBookInfo.adultNumber"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成人价格" prop="TourBookInfo.adultPrice">
              <el-input-number
                class="input-item"
                v-model="formData.TourBookInfo.adultPrice"
                placeholder=""
                :clearable="true"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="儿童人数" prop="TourBookInfo.childrenNumber">
              <el-input-number
                class="input-item"
                v-model="formData.TourBookInfo.childrenNumber"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="儿童价格" prop="TourBookInfo.childrenPrice">
              <el-input-number
                class="input-item"
                v-model="formData.TourBookInfo.childrenPrice"
                placeholder=""
                :clearable="true"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="总价格" prop="TourBookInfo.totalPrice">
              <el-input-number
                class="input-item"
                v-model="formData.TourBookInfo.totalPrice"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </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="onUpdateClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourBookInfo',
};
</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 { TourBookInfoData } from '@/api/generated/tourBookInfoController';
import { TourBookInfoController } 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 formEditTourBookInfo = ref();
// 表单数据定义
type FormEditTourBookInfoData = {
  TourBookInfo: TourBookInfoData;
};
// 表单数据
const formData = reactive<FormEditTourBookInfoData>({
  TourBookInfo: {
    // 主键id
    id: undefined,
    // 预定电话
    bookMobile: undefined,
    // 预定姓名
    bookName: undefined,
    // 预定的ip
    bookIp: undefined,
    // 预定时间
    bookTime: undefined,
    // 是否处理(0:未处理 1:已处理)
    isHandle: undefined,
    // 创建者Id
    createUserId: undefined,
    // 预定的种类(1:旅游 2:劳务)
    type: undefined,
    // 创建时间
    createTime: undefined,
    // 预定种类的id
    projectId: undefined,
    // 更新者Id
    updateUserId: undefined,
    // 最后更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    deletedFlag: undefined,
    // 成人价格
    adultPrice: undefined,
    // 儿童价格
    childrenPrice: undefined,
    // 成人人数
    adultNumber: undefined,
    // 儿童人数
    childrenNumber: undefined,
    // 总价格
    totalPrice: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourBookInfo.bookTime': [
    {required: true, message: '请输入预定时间', trigger: 'blur'}
  ],
  'TourBookInfo.isHandle': [
  ],
  'TourBookInfo.type': [
  ],
  'TourBookInfo.projectId': [
  ],
  'TourBookInfo.bookName': [
  ],
  'TourBookInfo.bookIp': [
  ],
  'TourBookInfo.bookMobile': [
    {type: 'string', pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ],
});

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

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

// 初始化页面数据
const loadTourBookInfoData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourBookInfo = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourBookInfoController.view(params).then(res => {
      formData.TourBookInfo = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 预定的类型下拉数据获取函数
 */
const loadTypeDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.ProjectType.getList(),
  });
};
// 预定的类型配置参数
const typeOptions: DropdownOptions<DictData> = {
  loadData: loadTypeDropdownList,
  isTree: false,
};
// 预定的类型下拉组件
const typeWidget = useDropdown(typeOptions);
const { dropdownList: typeWidgetDropdownList } = typeWidget
/**
 * 是否处理下拉数据获取函数
 */
const loadIsHandleDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'IsHandle', itemIdType: 'String' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 是否处理配置参数
const isHandleOptions: DropdownOptions<DictData> = {
  loadData: loadIsHandleDropdownList,
  isTree: false,
};
// 是否处理下拉组件
const isHandleWidget = useDropdown(isHandleOptions);
const { dropdownList: isHandleWidgetDropdownList } = isHandleWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourBookInfo = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourBookInfo = () => {
  refreshFormEditTourBookInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourBookInfo();
};
/**
 * 保存
 */
const onUpdateClick = () => {
  formEditTourBookInfo.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.TourBookInfo
      };
    formData.typeDictMap = findItemFromList(typeWidgetDropdownList, formData.type, 'id');
    formData.isHandleDictMap = findItemFromList(isHandleWidgetDropdownList, formData.isHandle, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      tourBookInfoDto: {
        id: formData.TourBookInfo.id,
        type: formData.TourBookInfo.type,
        projectId: formData.TourBookInfo.projectId,
        adultPrice: formData.TourBookInfo.adultPrice,
        childrenPrice: formData.TourBookInfo.childrenPrice,
        adultNumber: formData.TourBookInfo.adultNumber,
        childrenNumber: formData.TourBookInfo.childrenNumber,
        bookMobile: formData.TourBookInfo.bookMobile,
        bookName: formData.TourBookInfo.bookName,
        bookIp: formData.TourBookInfo.bookIp,
        bookTime: formData.TourBookInfo.bookTime,
        isHandle: formData.TourBookInfo.isHandle,
        createUserId: formData.TourBookInfo.createUserId,
        createTime: formData.TourBookInfo.createTime,
        updateUserId: formData.TourBookInfo.updateUserId,
        updateTime: formData.TourBookInfo.updateTime,
        totalPrice: formData.TourBookInfo.totalPrice,
      }
    };

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

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