<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditBannerInfo"
        :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="banner名称" prop="BannerInfo.bannerName">
              <el-input
                class="input-item"
                v-model="formData.BannerInfo.bannerName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="BannerInfo.belongTab">
              <el-select
                class="input-item"
                v-model="formData.BannerInfo.belongTab"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="belongTabWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in belongTabWidgetDropdownList"
                  :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="BannerInfo.enable">
              <el-select
                class="input-item"
                v-model="formData.BannerInfo.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="是否主banner" prop="BannerInfo.mainBanner">
              <el-select
                class="input-item"
                v-model="formData.BannerInfo.mainBanner"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="mainBannerWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in mainBannerWidgetDropdownList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="图片URL" prop="BannerInfo.imgUrl">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/bannerInfo/upload')"
                :data="{fieldName: 'imgUrl', asImage: true}"
                :on-success="onImgUrlUploadSuccess"
                :on-remove="onImgUrlRemoveFile"
                :on-error="onUploadError"
                :show-file-list="false"
              >
              <div v-if="imgUrlWidgetFileList && imgUrlWidgetFileList[0] != null" style="position: relative">
                <img class="upload-image-show"
                  :src="imgUrlWidgetFileList[0].url" />
                <div class="upload-img-del el-icon-close"
                  @click.stop="onImgUrlRemoveFile(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="BannerInfo.bannerUrl">
              <el-input
                class="input-item"
                v-model="formData.BannerInfo.bannerUrl"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="banner排序" prop="BannerInfo.showOrder">
              <el-input-number
                class="input-item"
                v-model="formData.BannerInfo.showOrder"
                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="onSubmitBannerInfoClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditBannerInfo',
};
</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 { BannerInfoData } from '@/api/generated/bannerInfoController';
import { BannerInfoController } 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 formEditBannerInfo = ref();
// 表单数据定义
type FormEditBannerInfoData = {
  BannerInfo: BannerInfoData;
};
// 表单数据
const formData = reactive<FormEditBannerInfoData>({
  BannerInfo: {
    // 主键
    id: undefined,
    // banner名称
    bannerName: undefined,
    // 所属分类
    belongTab: undefined,
    // 是否启用
    enable: undefined,
    // 是否主banner
    mainBanner: undefined,
    // 图片URL
    imgUrl: undefined,
    // 跳转链接
    bannerUrl: undefined,
    // banner排序
    showOrder: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 创建人
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 修改人
    updateUserId: undefined,
    // 修改时间
    updateTime: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'BannerInfo.enable': [
  ],
  'BannerInfo.mainBanner': [
  ],
  'BannerInfo.imgUrl': [
  ],
  'BannerInfo.bannerUrl': [
  ],
  'BannerInfo.showOrder': [
  ],
  'BannerInfo.bannerName': [
  ],
  'BannerInfo.belongTab': [
  ],
});

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

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

// 初始化页面数据
const loadBannerInfoData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.BannerInfo = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    BannerInfoController.view(params).then(res => {
      formData.BannerInfo = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 所属分类下拉数据获取函数
 */
const loadBelongTabDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
        const params = {
          parentId:0
        };
    DictionaryController.dictDirectoryInfoByParentId(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 所属分类配置参数
const belongTabOptions: DropdownOptions<DictData> = {
  loadData: loadBelongTabDropdownList,
  isTree: false,
};
// 所属分类下拉组件
const belongTabWidget = useDropdown(belongTabOptions);
const { dropdownList: belongTabWidgetDropdownList } = belongTabWidget
/**
 * 是否启用下拉数据获取函数
 */
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
/**
 * 是否主banner下拉数据获取函数
 */
const loadMainBannerDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsFirst.getList(),
  });
};
// 是否主banner配置参数
const mainBannerOptions: DropdownOptions<DictData> = {
  loadData: loadMainBannerDropdownList,
  isTree: false,
};
// 是否主banner下拉组件
const mainBannerWidget = useDropdown(mainBannerOptions);
const { dropdownList: mainBannerWidgetDropdownList } = mainBannerWidget
/**
 * 图片URL上传成功
 */
const onImgUrlUploadSuccess = (
  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);
    console.log(8888888888888888);
    console.log(fileList)
    imgUrlWidget.onFileChange(file, fileList);
    formData.BannerInfo.imgUrl = fileListToJson(imgUrlWidgetFileList.value);
    console.log(2333333333);
    console.log(imgUrlWidgetFileList);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除图片URL
 */
const onImgUrlRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  imgUrlWidget.onFileChange(file, fileList);
  formData.BannerInfo.imgUrl = fileListToJson(imgUrlWidgetFileList);
};
// 图片URL上传文件组件
const imgUrlWidget = useUploadWidget(1);
const { fileList: imgUrlWidgetFileList, maxCount: imgUrlWidgetMaxCount } = imgUrlWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditBannerInfo = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditBannerInfo = () => {
  refreshFormEditBannerInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditBannerInfo();
};
/**
 * 保存
 */
const onSubmitBannerInfoClick = () => {
  formEditBannerInfo.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.BannerInfo
      };
    formData.belongTabDictMap = findItemFromList(belongTabWidgetDropdownList, formData.belongTab, 'id');
    formData.enableDictMap = findItemFromList(enableWidgetDropdownList, formData.enable, 'id');
    formData.mainBannerDictMap = findItemFromList(mainBannerWidgetDropdownList, formData.mainBanner, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      bannerInfoDto: {
        id: formData.BannerInfo.id,
        bannerName: formData.BannerInfo.bannerName,
        belongTab: formData.BannerInfo.belongTab,
        enable: formData.BannerInfo.enable,
        mainBanner: formData.BannerInfo.mainBanner,
        imgUrl: formData.BannerInfo.imgUrl,
        bannerUrl: formData.BannerInfo.bannerUrl,
        showOrder: formData.BannerInfo.showOrder,
        createUserId: formData.BannerInfo.createUserId,
        createTime: formData.BannerInfo.createTime,
        updateUserId: formData.BannerInfo.updateUserId,
        updateTime: formData.BannerInfo.updateTime,
      }
    };

    let httpCall = isEdit.value ? BannerInfoController.update : BannerInfoController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadBannerInfoData().then(res => {
    belongTabWidget.onVisibleChange(true).catch(e => {console.error(e)});
    enableWidget.onVisibleChange(true).catch(e => {console.error(e)});
    mainBannerWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let imgUrlDownloadParams = {
      id: formData.BannerInfo.id,
      fieldName: 'imgUrl',
      asImage: true
    };
    imgUrlWidgetFileList.value = parseUploadData(formData.BannerInfo.imgUrl, imgUrlDownloadParams);
    if (isEdit.value) refreshFormEditBannerInfo();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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