<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourHouseFilesRef"
        :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="TourHouseFiles.fileName">
              <el-input
                class="input-item"
                v-model="formData.TourHouseFiles.fileName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件大小" prop="TourHouseFiles.fileSize">
              <el-input
                class="input-item"
                v-model="formData.TourHouseFiles.fileSize"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="TourHouseFiles.price">
              <el-input-number
                class="input-item"
                v-model="formData.TourHouseFiles.price"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货币" prop="TourHouseFiles.currency">
              <el-input
                class="input-item"
                v-model="formData.TourHouseFiles.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="TourHouseFiles.area">
              <el-input-number
                class="input-item"
                v-model="formData.TourHouseFiles.area"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文件类型 " prop="TourHouseFiles.fileType">
              <el-select
                class="input-item"
                v-model="formData.TourHouseFiles.fileType"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="fileTypeWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in fileTypeWidgetDropdownList"
                  :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="TourHouseFiles.fileUrl">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourHouseFiles/upload')"
                :data="{fieldName: 'fileUrl', asImage: true}"
                :on-success="onFileUrlUploadSuccess"
                :on-remove="onFileUrlRemoveFile"
                :on-error="onUploadError"
                :show-file-list="false"
              >
              <div v-if="fileUrlWidgetFileList && fileUrlWidgetFileList[0] != null" style="position: relative">
                <img class="upload-image-show"
                  :src="fileUrlWidgetFileList[0].url" />
                <div class="upload-img-del el-icon-close"
                  @click.stop="onFileUrlRemoveFile(null, null)" />
              </div>
              <i v-else class="el-icon-plus upload-image-item"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上传时间" prop="TourHouseFiles.uploadTime">
              <el-date-picker
                class="input-item"
                v-model="formData.TourHouseFiles.uploadTime"
                type="date"
                placeholder=""
                :clearable="true"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </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="onSubmitTourHouseFilesClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourHouseFiles',
};
</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 { TourHouseFilesData } from '@/api/generated/tourHouseFilesController';
import { TourHouseFilesController } 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 formEditTourHouseFilesRef = ref();
// 表单数据定义
type FormEditTourHouseFilesData = {
  TourHouseFiles: TourHouseFilesData;
};
// 表单数据
const formData = reactive<FormEditTourHouseFilesData>({
  TourHouseFiles: {
    // 主键
    id: undefined,
    // 房屋表id
    tourHouseId: undefined,
    // 文件名称
    fileName: undefined,
    // 文件大小
    fileSize: undefined,
    // 价格
    price: undefined,
    // 货币
    currency: undefined,
    // 面积
    area: undefined,
    // 文件类型 0房屋图集  1户型图集 2周边配套图集 3小区介绍图集
    fileType: undefined,
    // 文件存储地址
    fileUrl: undefined,
    // 上传时间
    uploadTime: undefined,
    // 创建用户
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新用户
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourHouseFiles.fileName': [
  ],
  'TourHouseFiles.fileSize': [
  ],
  'TourHouseFiles.area': [
  ],
  'TourHouseFiles.fileType': [
    {required: true, message: '请输入文件类型 ', trigger: 'blur'}
  ],
  'TourHouseFiles.price': [
  ],
  'TourHouseFiles.currency': [
  ],
  'TourHouseFiles.fileUrl': [
    {required: true, message: '请输入文件存储地址', trigger: 'blur'}
  ],
  'TourHouseFiles.uploadTime': [
  ],
});

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

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

// 初始化页面数据
const loadTourHouseFilesData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourHouseFiles = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourHouseFilesController.view(params).then(res => {
      formData.TourHouseFiles = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 文件类型 下拉数据获取函数
 */
const loadFileTypeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'HouseFileType', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 文件类型 配置参数
const fileTypeOptions: DropdownOptions<DictData> = {
  loadData: loadFileTypeDropdownList,
  isTree: false,
};
// 文件类型 下拉组件
const fileTypeWidget = useDropdown(fileTypeOptions);
const { dropdownList: fileTypeWidgetDropdownList } = fileTypeWidget
/**
 * 文件存储地址上传成功
 */
const onFileUrlUploadSuccess = (
  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);
    fileUrlWidget.onFileChange(file, fileList);
    formData.TourHouseFiles.fileUrl = fileListToJson(fileUrlWidgetFileList.value);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除文件存储地址
 */
const onFileUrlRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  fileUrlWidget.onFileChange(file, fileList);
  formData.TourHouseFiles.fileUrl = fileListToJson(fileUrlWidgetFileList.value);
};
// 文件存储地址上传文件组件
const fileUrlWidget = useUploadWidget(1);
const { fileList: fileUrlWidgetFileList, maxCount: fileUrlWidgetMaxCount } = fileUrlWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourHouseFiles = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourHouseFiles = () => {
  refreshFormEditTourHouseFiles();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourHouseFiles();
};
/**
 * 保存
 */
const onSubmitTourHouseFilesClick = () => {
  formEditTourHouseFilesRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourHouseFiles
      };
    retFormData.fileTypeDictMap = findItemFromList(fileTypeWidgetDropdownList, retFormData.fileType, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourHouseFilesDto: {
        id: formData.TourHouseFiles.id,
        tourHouseId: formData.TourHouseFiles.id,
        fileName: formData.TourHouseFiles.fileName,
        fileSize: formData.TourHouseFiles.fileSize,
        price: formData.TourHouseFiles.price,
        currency: formData.TourHouseFiles.currency,
        area: formData.TourHouseFiles.area,
        fileType: formData.TourHouseFiles.fileType,
        fileUrl: formData.TourHouseFiles.fileUrl,
        uploadTime: formData.TourHouseFiles.uploadTime,
        createUserId: formData.TourHouseFiles.createUserId,
        createTime: formData.TourHouseFiles.createTime,
        updateUserId: formData.TourHouseFiles.updateUserId,
        updateTime: formData.TourHouseFiles.updateTime,
      }
    };

    let httpCall = isEdit.value ? TourHouseFilesController.update : TourHouseFilesController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourHouseFilesData().then(res => {
    fileTypeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let fileUrlDownloadParams = {
      id: formData.TourHouseFiles.id,
      fieldName: 'fileUrl',
      asImage: true
    };
    fileUrlWidgetFileList.value = parseUploadData(formData.TourHouseFiles.fileUrl, fileUrlDownloadParams);
    if (isEdit.value) refreshFormEditTourHouseFiles();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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