<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourHouseAreaMenuRef"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rules"
        label-width="120px"
        label-position="right"
        @submit.prevent
      >
        <el-row :gutter="16">
          <el-col :span="24">
            <el-form-item label="父级id" prop="TourHouseAreaMenu.parentId">
              <el-cascader
                class="input-item"
                v-model="parentIdPath"
                :options="parentIdWidgetDropdownList"
                placeholder=""
                :clearable="true"
                :filterable="true"
                :show-all-levels="false"
                :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
                @change="onParentIdValueChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="菜单名称" prop="TourHouseAreaMenu.levelName">
              <el-input
                class="input-item"
                v-model="formData.TourHouseAreaMenu.levelName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="20">
            <el-form-item label="菜单等级" prop="TourHouseAreaMenu.levelNum">
              <el-input-number
                class="input-item"
                v-model="formData.TourHouseAreaMenu.levelNum"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示顺序" prop="TourHouseAreaMenu.showOrder">
              <el-input-number
                class="input-item"
                v-model="formData.TourHouseAreaMenu.showOrder"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否启用" prop="TourHouseAreaMenu.enable">
              <el-select
                class="input-item"
                v-model="formData.TourHouseAreaMenu.enable"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="enableWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in enableWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="租售类型" prop="TourHouseAreaMenu.type">
              <el-select
                class="input-item"
                v-model="formData.TourHouseAreaMenu.type"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="typeWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in typeWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="是否热点" prop="TourHouseAreaMenu.isHotspot">
              <el-select
                class="input-item"
                v-model="formData.TourHouseAreaMenu.isHotspot"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isHotspotWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isHotspotWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="热门排序" prop="TourHouseAreaMenu.hotOrder">
              <el-input-number
                class="input-item"
                v-model="formData.TourHouseAreaMenu.hotOrder"
                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="onSubmitTourHouseAreaMenuClick()"
        >保存</el-button
      >
    </el-row>
  </div>
</template>

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

<script setup lang="ts">
import { VxeColumn, VxeTable } from 'vxe-table';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { DialogProp } from '@/components/Dialog/types';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
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 { TourHouseAreaMenuData } from '@/api/generated/tourHouseAreaMenuController';
import { TourHouseAreaMenuController } 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 formEditTourHouseAreaMenuRef = ref();
// 表单数据定义
type FormEditTourHouseAreaMenuData = {
  TourHouseAreaMenu: TourHouseAreaMenuData;
};
// 表单数据
const formData = reactive<FormEditTourHouseAreaMenuData>({
  TourHouseAreaMenu: {
    // 主键id
    id: undefined,
    // 父级id
    parentId: 0,
    // 菜单等级
    levelNum: undefined,
    // 菜单名称
    levelName: undefined,
    // 显示顺序
    showOrder: undefined,
    // 是否启用，0禁用，1启用
    enable: undefined,
    // 租售类型：0：出售 1：租赁
    type: undefined,
    // 是否热点，0非热点，1热点
    isHotspot: undefined,
    // 热门排序
    hotOrder: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
  },
});
// 表单验证规则
const rules = reactive({
  'TourHouseAreaMenu.isHotspot': [],
  'TourHouseAreaMenu.hotOrder': [],
  // 'TourHouseAreaMenu.levelNum': [],
  // 'TourHouseAreaMenu.parentId': [],
  // 'TourHouseAreaMenu.showOrder': [],
  // 'TourHouseAreaMenu.levelName': [],
  // 'TourHouseAreaMenu.type': [],
  // 'TourHouseAreaMenu.enable': [],
  'TourHouseAreaMenu.levelNum': [{ required: true, message: '请输入菜单等级', trigger: 'blur' }],
  'TourHouseAreaMenu.parentId': [{ required: true, message: '请输入父级id', trigger: 'blur' }],
  'TourHouseAreaMenu.showOrder': [{ required: true, message: '请输入显示顺序', trigger: 'blur' }],
  'TourHouseAreaMenu.levelName': [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  'TourHouseAreaMenu.type': [{ required: true, message: '请输入租售类型', trigger: 'blur' }],
  'TourHouseAreaMenu.enable': [{ 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 loadTourHouseAreaMenuData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourHouseAreaMenu = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id,
    };
    TourHouseAreaMenuController.view(params)
      .then(res => {
        formData.TourHouseAreaMenu = { ...res.data };
        resolve();
      })
      .catch(e => {
        reject(e);
      });
  });
};
/**
 * 父级id下拉数据获取函数
 */
const loadParentIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {};
    DictionaryController.dictTourHouseAreaMenu(params)
      .then(res => {
        resolve({
          dataList: res.getList(),
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
/**
 * 父级id选中值改变
 */
const onParentIdValueChange = value => {
  formData.TourHouseAreaMenu.parentId = Array.isArray(value) ? value[value.length - 1] : value;
};
// 父级id配置参数
const parentIdOptions: DropdownOptions<DictData> = {
  loadData: loadParentIdDropdownList,
  isTree: true,
};
// 父级id选中数据
const parentIdPath = ref<Array<string | number>>([]);
// 父级id下拉组件
const parentIdWidget = useDropdown(parentIdOptions);
const { dropdownList: parentIdWidgetDropdownList } = parentIdWidget;
/**
 * 是否启用下拉数据获取函数
 */
const loadEnableDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Enable.getList(),
  });
};
// 是否启用配置参数
const enableOptions: DropdownOptions<DictData> = {
  loadData: loadEnableDropdownList,
  isTree: false,
};
// 是否启用下拉组件
const enableWidget = useDropdown(enableOptions);
const { dropdownList: enableWidgetDropdownList } = enableWidget;
/**
 * 租售类型下拉数据获取函数
 */
const loadTypeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'IsSaleOrRent', itemIdType: 'Integer' })
      .then(res => {
        resolve({
          dataList: res.getList(),
        });
      })
      .catch(e => {
        reject(e);
      });
  });
};
// 租售类型配置参数
const typeOptions: DropdownOptions<DictData> = {
  loadData: loadTypeDropdownList,
  isTree: false,
};
// 租售类型下拉组件
const typeWidget = useDropdown(typeOptions);
const { dropdownList: typeWidgetDropdownList } = typeWidget;
/**
 * 是否热点下拉数据获取函数
 */
const loadIsHotspotDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Hotspot.getList(),
  });
};
// 是否热点配置参数
const isHotspotOptions: DropdownOptions<DictData> = {
  loadData: loadIsHotspotDropdownList,
  isTree: false,
};
// 是否热点下拉组件
const isHotspotWidget = useDropdown(isHotspotOptions);
const { dropdownList: isHotspotWidgetDropdownList } = isHotspotWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourHouseAreaMenu = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourHouseAreaMenu = () => {
  refreshFormEditTourHouseAreaMenu();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourHouseAreaMenu();
};
/**
 * 保存
 */
const onSubmitTourHouseAreaMenuClick = () => {
  formEditTourHouseAreaMenuRef.value.validate(valid => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourHouseAreaMenu,
      };
      retFormData.parentIdDictMap = findTreeNode(
        parentIdWidgetDropdownList,
        retFormData.parentId,
        'id',
      );
      retFormData.enableDictMap = findItemFromList(
        enableWidgetDropdownList,
        retFormData.enable,
        'id',
      );
      retFormData.typeDictMap = findItemFromList(typeWidgetDropdownList, retFormData.type, 'id');
      retFormData.isHotspotDictMap = findItemFromList(
        isHotspotWidgetDropdownList,
        retFormData.isHotspot,
        'id',
      );
      props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourHouseAreaMenuDto: {
        id: formData.TourHouseAreaMenu.id,
        parentId: formData.TourHouseAreaMenu.parentId??0,
        levelNum: formData.TourHouseAreaMenu.levelNum,
        levelName: formData.TourHouseAreaMenu.levelName,
        showOrder: formData.TourHouseAreaMenu.showOrder,
        enable: formData.TourHouseAreaMenu.enable,
        type: formData.TourHouseAreaMenu.type,
        isHotspot: formData.TourHouseAreaMenu.isHotspot,
        hotOrder: formData.TourHouseAreaMenu.hotOrder,
        createUserId: formData.TourHouseAreaMenu.createUserId,
        createTime: formData.TourHouseAreaMenu.createTime,
        updateUserId: formData.TourHouseAreaMenu.updateUserId,
        updateTime: formData.TourHouseAreaMenu.updateTime,
      },
    };

    let httpCall = isEdit.value
      ? TourHouseAreaMenuController.update
      : TourHouseAreaMenuController.add;
    httpCall(params)
      .then(res => {
        ElMessage.success('保存成功');
        props.dialog?.submit();
      })
      .catch(e => {
        // TODO: 异常处理
        console.error(e);
      });
  });
};
const formInit = () => {
  loadTourHouseAreaMenuData()
    .then(res => {
      parentIdWidget
        .onVisibleChange(true)
        .then(res => {
          // TODO: 获取级联选中路径
          parentIdPath.value = findTreeNodePath(res, formData.TourHouseAreaMenu.parentId);
        })
        .catch(e => {
          // TODO: 异常处理
          console.error(e);
        });
      enableWidget.onVisibleChange(true).catch(e => {
        console.error(e);
      });
      typeWidget.onVisibleChange(true).catch(e => {
        console.error(e);
      });
      isHotspotWidget.onVisibleChange(true).catch(e => {
        console.error(e);
      });
      if (isEdit.value) refreshFormEditTourHouseAreaMenu();
    })
    .catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};

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