<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="editTourProjectGroupPurchaseRef"
        :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="TourProjectGroupPurchase.projectId">
              <SelectBookTourismProject
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.projectId"
                placeholder=""
                :required="true"
                :disabled="false"
                :props="{
                  label: 'projectTitle',
                  value: 'id'
                }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拼团截至时间" prop="TourProjectGroupPurchase.endTime">
              <el-date-picker
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.endTime"
                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="TourProjectGroupPurchase.travelStartTime">
              <el-date-picker
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.travelStartTime"
                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="TourProjectGroupPurchase.travelEndTime">
              <el-date-picker
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.travelEndTime"
                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="TourProjectGroupPurchase.maxCount">
              <el-input-number
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.maxCount"
                placeholder=""
                :clearable="true"
                :min="3"
                :max="9"
                :step="1"
                :precision="0"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拼团状态" prop="TourProjectGroupPurchase.state">
              <el-select
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.state"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="stateWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in stateWidgetDropdownList"
                  :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="TourProjectGroupPurchase.childrenPrice">
              <el-input-number
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.childrenPrice"
                placeholder=""
                :clearable="true"
                :min="0"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成人最低价格" prop="TourProjectGroupPurchase.adultPrice">
              <el-input-number
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.adultPrice"
                placeholder=""
                :clearable="true"
                :min="0"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格单位" prop="TourProjectGroupPurchase.priceUnit">
              <el-input
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.priceUnit"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="返利价格/人" prop="TourProjectGroupPurchase.singleRebate">
              <el-input-number
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.singleRebate"
                placeholder=""
                :clearable="true"
                :min="0"
                :step="1"
                :precision="2"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="TourProjectGroupPurchase.showOrder">
              <el-input-number
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.showOrder"
                placeholder=""
                :clearable="true"
                :min="0"
                :step="1"
                :precision="0"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="拼团标题" prop="TourProjectGroupPurchase.title">
              <el-input
                class="input-item"
                v-model="formData.TourProjectGroupPurchase.title"
                type="textarea"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="背景图" prop="TourProjectGroupPurchase.image">
              <custom-upload
                v-model="imageWidgetFileList"
                name="uploadFile"
                :size="layoutStore.defaultFormItemSize"
                type="expand"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourProjectGroupPurchase/upload')"
                :data="{fieldName: 'image', asImage: true}"
                :limit="imageWidgetMaxCount"
                @change="onImageChange"
              />
            </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: 'editTourProjectGroupPurchase',
};
</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, stringCase } from '@/common/utils';
import { TourProjectGroupPurchaseData } from '@/api/generated/tourProjectGroupPurchaseController';
import { TourismProjectData } from '@/api/generated/tourismProjectController';
import { TourProjectGroupPurchaseDetailData } from '@/api/generated/tourProjectGroupPurchaseDetailController';
import { TourProjectGroupPurchaseController, TourismProjectController, TourProjectGroupPurchaseDetailController } from '@/api/generated';
import SelectBookTourismProject from '@/pages/tourTourismBookInfo/selectBookTourismProject/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 editTourProjectGroupPurchaseRef = ref();
// 表单数据定义
type EditTourProjectGroupPurchaseData = {
  TourProjectGroupPurchase: TourProjectGroupPurchaseData;
};
// 表单数据
const formData = reactive<EditTourProjectGroupPurchaseData>({
  TourProjectGroupPurchase: {
    // 主键id
    id: undefined,
    // 项目id
    projectId: undefined,
    // 拼团结束时间
    endTime: undefined,
    // 出行开始时间
    travelStartTime: undefined,
    // 出行结束时间
    travelEndTime: undefined,
    // 拼团状态(0禁用，1启用)
    state: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 拼团人数上限
    maxCount: undefined,
    // 成人价格
    adultPrice: undefined,
    // 儿童价格
    childrenPrice: undefined,
    // 显示顺序
    showOrder: undefined,
    // 关联字段(与从表)
    code: undefined,
    // 当前拼团的人数
    nowCount: undefined,
    // 拼团是否成功(0.失败;1.成功)
    success: undefined,
    // 拼团标题
    title: undefined,
    // 图片url
    image: undefined,
    // 价格单位
    priceUnit: undefined,
    // 拼团返利/人
    singleRebate: 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,
      // 上传的联系二维码
      contactCode: undefined,
    },
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourProjectGroupPurchase.childrenPrice': [
    {required: true, message: '请输入儿童价格', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.priceUnit': [
    {required: true, message: '请输入价格单位', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.adultPrice': [
    {required: true, message: '请输入成人价格', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.maxCount': [
    {required: true, message: '请输入拼团人数上限', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.showOrder': [
    {required: true, message: '请输入显示顺序', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.state': [
    {required: true, message: '请输入拼团状态', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.endTime': [
    {required: true, message: '请输入拼团截至时间', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.projectId': [
    {required: true, message: '请输入选择旅游项目', trigger: 'blur'}
  ],
  // 'TourProjectGroupPurchase.travelEndTime': [
  //   {required: true, message: '请输入出行结束时间', trigger: 'blur'}
  // ],
  'TourProjectGroupPurchase.title': [
    {required: true, message: '请输入拼团标题', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.image': [
    {required: true, message: '请输入背景图', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.travelStartTime': [
    {required: true, message: '请输入出行开始时间', trigger: 'blur'}
  ],
  'TourProjectGroupPurchase.singleRebate': [
    {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 loadTourProjectGroupPurchaseData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourProjectGroupPurchase = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourProjectGroupPurchaseController.view(params).then(res => {
      formData.TourProjectGroupPurchase = { ...res.data };
      if (formData.TourProjectGroupPurchase.tourismProject == null) {
        formData.TourProjectGroupPurchase.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,
          contactCode: undefined
        };
      }
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 拼团状态下拉数据获取函数
 */
const loadStateDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Enable.getList(),
  });
};
// 拼团状态配置参数
const stateOptions: DropdownOptions<DictData> = {
  loadData: loadStateDropdownList,
  isTree: false,
};
// 拼团状态下拉组件
const stateWidget = useDropdown(stateOptions);
const { dropdownList: stateWidgetDropdownList } = stateWidget
/**
 * 背景图上传文件改变
 */
const onImageChange = val => {
  formData.TourProjectGroupPurchase.image = fileListToJson(val);
};
// 背景图上传文件组件
const imageWidget = useUploadWidget(1);
const { fileList: imageWidgetFileList, maxCount: imageWidgetMaxCount } = imageWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshEditTourProjectGroupPurchase = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetEditTourProjectGroupPurchase = () => {
  refreshEditTourProjectGroupPurchase();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetEditTourProjectGroupPurchase();
};
/**
 * 保存
 */
const onSaveClick = () => {
  editTourProjectGroupPurchaseRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourProjectGroupPurchase
      };
    retFormData.stateDictMap = findItemFromList(stateWidgetDropdownList.value, retFormData.state, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourProjectGroupPurchaseDto: {
        id: formData.TourProjectGroupPurchase.id,
        showOrder: formData.TourProjectGroupPurchase.showOrder,
        code: formData.TourProjectGroupPurchase.code,
        nowCount: formData.TourProjectGroupPurchase.nowCount,
        success: formData.TourProjectGroupPurchase.success,
        title: formData.TourProjectGroupPurchase.title,
        image: formData.TourProjectGroupPurchase.image,
        priceUnit: formData.TourProjectGroupPurchase.priceUnit,
        singleRebate: formData.TourProjectGroupPurchase.singleRebate,
        projectId: formData.TourProjectGroupPurchase.projectId,
        endTime: formData.TourProjectGroupPurchase.endTime,
        travelStartTime: formData.TourProjectGroupPurchase.travelStartTime,
        travelEndTime: formData.TourProjectGroupPurchase.travelEndTime,
        state: formData.TourProjectGroupPurchase.state,
        createUserId: formData.TourProjectGroupPurchase.createUserId,
        createTime: formData.TourProjectGroupPurchase.createTime,
        updateUserId: formData.TourProjectGroupPurchase.updateUserId,
        updateTime: formData.TourProjectGroupPurchase.updateTime,
        maxCount: formData.TourProjectGroupPurchase.maxCount,
        adultPrice: formData.TourProjectGroupPurchase.adultPrice,
        childrenPrice: formData.TourProjectGroupPurchase.childrenPrice,
      }
    };

    let httpCall = isEdit.value ? TourProjectGroupPurchaseController.update : TourProjectGroupPurchaseController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourProjectGroupPurchaseData().then(res => {
    stateWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let imageDownloadParams = {
      id: formData.TourProjectGroupPurchase.id,
      fieldName: 'image',
      asImage: true
    };
    imageWidgetFileList.value = parseUploadData(formData.TourProjectGroupPurchase.image, imageDownloadParams);
    if (isEdit.value) refreshEditTourProjectGroupPurchase();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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