<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditDirectoryInfoRef"
        :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="DirectoryInfo.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="12">
            <el-form-item label="菜单名称" prop="DirectoryInfo.menuName">
              <el-input
                class="input-item"
                v-model="formData.DirectoryInfo.menuName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示顺序" prop="DirectoryInfo.showOrder">
              <el-input-number
                class="input-item"
                v-model="formData.DirectoryInfo.showOrder"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="DirectoryInfo.enable">
              <el-select
                class="input-item"
                v-model="formData.DirectoryInfo.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="12">
            <el-form-item label="菜单类型" prop="DirectoryInfo.directoryType">
              <el-select
                class="input-item"
                v-model="formData.DirectoryInfo.directoryType"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="directoryTypeWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in directoryTypeWidgetDropdownList"
                  :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="DirectoryInfo.isHotspot">
              <el-select
                class="input-item"
                v-model="formData.DirectoryInfo.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="12">
            <el-form-item label="热门排序" prop="DirectoryInfo.hotOrder">
              <el-input-number
                class="input-item"
                v-model="formData.DirectoryInfo.hotOrder"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否精选目的地 " prop="DirectoryInfo.isWinnowDestination">
              <el-select
                class="input-item"
                v-model="formData.DirectoryInfo.isWinnowDestination"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isWinnowDestinationWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isWinnowDestinationWidgetDropdownList"
                  :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="DirectoryInfo.hotPictureUrl">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/directoryInfo/upload')"
                :data="{fieldName: 'hotPictureUrl', asImage: true}"
                :on-success="onHotPictureUrlUploadSuccess"
                :on-remove="onHotPictureUrlRemoveFile"
                :on-error="onUploadError"
                :show-file-list="false"
              >
              <div v-if="hotPictureUrlWidgetFileList && hotPictureUrlWidgetFileList[0] != null" style="position: relative">
                <img class="upload-image-show"
                  :src="hotPictureUrlWidgetFileList[0].url" />
                <div class="upload-img-del el-icon-close"
                  @click.stop="onHotPictureUrlRemoveFile(null, null)" />
              </div>
              <i v-else class="el-icon-plus upload-image-item"></i>
              </el-upload>
            </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: 'formEditDirectoryInfo',
};
</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 { DirectoryInfoData } from '@/api/generated/directoryInfoController';
import { DirectoryInfoController } 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 formEditDirectoryInfoRef = ref();
// 表单数据定义
type FormEditDirectoryInfoData = {
  DirectoryInfo: DirectoryInfoData;
};
// 表单数据
const formData = reactive<FormEditDirectoryInfoData>({
  DirectoryInfo: {
    // 主键id
    id: undefined,
    // 父级id
    parentId: undefined,
    // 菜单名称
    menuName: undefined,
    // 显示顺序
    showOrder: undefined,
    // 是否启用，0禁用，1启用
    enable: undefined,
    // 菜单类型：1：旅游，2：劳务
    directoryType: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 是否热点，0非热点，1热点
    isHotspot: undefined,
    // 热门排序
    hotOrder: undefined,
    // 热门图片
    hotPictureUrl: undefined,
    // 精选目的地 1 是 2 不是
    isWinnowDestination: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'DirectoryInfo.enable': [
    {required: true, message: '请输入是否启用', trigger: 'blur'}
  ],
  'DirectoryInfo.showOrder': [
    {required: true, message: '请输入显示顺序', trigger: 'blur'}
  ],
  'DirectoryInfo.menuName': [
    {required: true, message: '请输入菜单名称', trigger: 'blur'}
  ],
  'DirectoryInfo.isWinnowDestination': [
    {required: true, message: '请输入是否精选目的地 ', trigger: 'blur'}
  ],
  'DirectoryInfo.parentId': [
    {required: true, message: '请输入父级菜单', trigger: 'blur'}
  ],
  'DirectoryInfo.directoryType': [
    {required: true, message: '请输入菜单类型', trigger: 'blur'}
  ],
  'DirectoryInfo.isHotspot': [
  ],
  'DirectoryInfo.hotPictureUrl': [
  ],
  'DirectoryInfo.hotOrder': [
  ],
});

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

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

// 初始化页面数据
const loadDirectoryInfoData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.DirectoryInfo = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    DirectoryInfoController.view(params).then(res => {
      formData.DirectoryInfo = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 父级菜单下拉数据获取函数
 */
const loadParentIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictDirectoryInfo(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 父级菜单选中值改变
 */
const onParentIdValueChange = (value) => {
  formData.DirectoryInfo.parentId = Array.isArray(value) ? value[value.length - 1] : value;
};
// 父级菜单配置参数
const parentIdOptions: DropdownOptions<DictData> = {
  loadData: loadParentIdDropdownList,
  isTree: true,
};
// 父级菜单选中数据
const parentIdPath = ref<Array<string | number>>([]);
// 父级菜单下拉组件
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 loadDirectoryTypeDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.CompanyType.getList(),
  });
};
// 菜单类型配置参数
const directoryTypeOptions: DropdownOptions<DictData> = {
  loadData: loadDirectoryTypeDropdownList,
  isTree: false,
};
// 菜单类型下拉组件
const directoryTypeWidget = useDropdown(directoryTypeOptions);
const { dropdownList: directoryTypeWidgetDropdownList } = directoryTypeWidget
/**
 * 是否热点下拉数据获取函数
 */
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 loadIsWinnowDestinationDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsWinnowDestination.getList(),
  });
};
// 是否精选目的地 配置参数
const isWinnowDestinationOptions: DropdownOptions<DictData> = {
  loadData: loadIsWinnowDestinationDropdownList,
  isTree: false,
};
// 是否精选目的地 下拉组件
const isWinnowDestinationWidget = useDropdown(isWinnowDestinationOptions);
const { dropdownList: isWinnowDestinationWidgetDropdownList } = isWinnowDestinationWidget
/**
 * 劳务图片上传成功
 */
const onHotPictureUrlUploadSuccess = (
  response: ANY_OBJECT,
  file: UploadFile,
  fileList: UploadFile[],
) => {
  if (response.success) {
    file.downloadUri = response.data.downloadUri;
    file.filename = response.data.filename;
    file.uploadPath = response.data.uploadPath;
    file.url = URL.createObjectURL(file.raw);
    hotPictureUrlWidget.onFileChange(file, fileList);
    formData.DirectoryInfo.hotPictureUrl = fileListToJson(hotPictureUrlWidgetFileList.value);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除劳务图片
 */
const onHotPictureUrlRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  hotPictureUrlWidget.onFileChange(file, fileList);
  formData.DirectoryInfo.hotPictureUrl = fileListToJson(hotPictureUrlWidgetFileList.value);
};
// 劳务图片上传文件组件
const hotPictureUrlWidget = useUploadWidget(1);
const { fileList: hotPictureUrlWidgetFileList, maxCount: hotPictureUrlWidgetMaxCount } = hotPictureUrlWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditDirectoryInfo = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditDirectoryInfo = () => {
  refreshFormEditDirectoryInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditDirectoryInfo();
};
/**
 * 编辑
 */
const onUpdateClick = () => {
  formEditDirectoryInfoRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.DirectoryInfo
      };
    formData.parentIdDictMap = findTreeNode(parentIdWidgetDropdownList, formData.parentId, 'id');
    formData.enableDictMap = findItemFromList(enableWidgetDropdownList, formData.enable, 'id');
    formData.directoryTypeDictMap = findItemFromList(directoryTypeWidgetDropdownList, formData.directoryType, 'id');
    formData.isHotspotDictMap = findItemFromList(isHotspotWidgetDropdownList, formData.isHotspot, 'id');
    formData.isWinnowDestinationDictMap = findItemFromList(isWinnowDestinationWidgetDropdownList, formData.isWinnowDestination, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      directoryInfoDto: {
        id: formData.DirectoryInfo.id,
        parentId: formData.DirectoryInfo.parentId,
        menuName: formData.DirectoryInfo.menuName,
        showOrder: formData.DirectoryInfo.showOrder,
        enable: formData.DirectoryInfo.enable,
        directoryType: formData.DirectoryInfo.directoryType,
        createUserId: formData.DirectoryInfo.createUserId,
        createTime: formData.DirectoryInfo.createTime,
        updateUserId: formData.DirectoryInfo.updateUserId,
        updateTime: formData.DirectoryInfo.updateTime,
        isHotspot: formData.DirectoryInfo.isHotspot,
        hotOrder: formData.DirectoryInfo.hotOrder,
        hotPictureUrl: formData.DirectoryInfo.hotPictureUrl,
        isWinnowDestination: formData.DirectoryInfo.isWinnowDestination,
      }
    };

    let httpCall = isEdit.value ? DirectoryInfoController.update : DirectoryInfoController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadDirectoryInfoData().then(res => {
    parentIdWidget.onVisibleChange(true).then(res => {
      // TODO: 获取级联选中路径
      parentIdPath.value = findTreeNodePath(res, formData.DirectoryInfo.parentId);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
    enableWidget.onVisibleChange(true).catch(e => {console.error(e)});
    directoryTypeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isHotspotWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isWinnowDestinationWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let hotPictureUrlDownloadParams = {
      id: formData.DirectoryInfo.id,
      fieldName: 'hotPictureUrl',
      asImage: true
    };
    hotPictureUrlWidgetFileList.value = parseUploadData(formData.DirectoryInfo.hotPictureUrl, hotPictureUrlDownloadParams);
    if (isEdit.value) refreshFormEditDirectoryInfo();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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