<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourHouseKnowledgeInfoRef"
        :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="TourHoeseKnowledgeInfo.type">
              <el-select
                class="input-item"
                v-model="formData.TourHoeseKnowledgeInfo.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="12">
            <el-form-item label="知识标题" prop="TourHoeseKnowledgeInfo.title">
              <el-input
                class="input-item"
                v-model="formData.TourHoeseKnowledgeInfo.title"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
        
          <el-col :span="12">
            <el-form-item label="是否启用" prop="TourHoeseKnowledgeInfo.enable">
              <el-select
                class="input-item"
                v-model="formData.TourHoeseKnowledgeInfo.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="知识内容" class="rich-input" prop="TourHoeseKnowledgeInfo.content">
             <rich-editor
               ref="content"
               class="input-item"
               v-model="formData.TourHoeseKnowledgeInfo.content"
             />
           </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="onSubmitTourHoeseKnowledgeInfoClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourHouseKnowledgeInfo',
};
</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 { TourHoeseKnowledgeInfoData } from '@/api/generated/tourHoeseKnowledgeInfoController';
import { TourHoeseKnowledgeInfoController } 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 formEditTourHouseKnowledgeInfoRef = ref();
// 表单数据定义
type FormEditTourHouseKnowledgeInfoData = {
  TourHoeseKnowledgeInfo: TourHoeseKnowledgeInfoData;
};
// 表单数据
const formData = reactive<FormEditTourHouseKnowledgeInfoData>({
  TourHoeseKnowledgeInfo: {
    // 主键
    id: undefined,
    // 知识类型 0买房 1装修
    type: undefined,
    // 知识标题
    title: undefined,
    // 知识内容
    content: undefined,
    // 是否启用，0禁用，1启用
    enable: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 创建人
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 修改人
    updateUserId: undefined,
    // 修改时间
    updateTime: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourHoeseKnowledgeInfo.enable': [
    {required: true, message: '请输入是否启用', trigger: 'blur'}
  ],
  'TourHoeseKnowledgeInfo.content': [
    {required: true, message: '请输入知识内容', trigger: 'blur'}
  ],
  'TourHoeseKnowledgeInfo.title': [
    {required: true, message: '请输入知识标题', trigger: 'blur'}
  ],
  'TourHoeseKnowledgeInfo.type': [
    {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 loadTourHoeseKnowledgeInfoData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourHoeseKnowledgeInfo = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourHoeseKnowledgeInfoController.view(params).then(res => {
      formData.TourHoeseKnowledgeInfo = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 知识类型下拉数据获取函数
 */
const loadTypeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'HouseKnowledgeType', 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 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 content = ref();
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourHouseKnowledgeInfo = () => {
  // 刷新段落
};

/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourHouseKnowledgeInfo();
};/**
 * 保存
 */
const onSubmitTourHoeseKnowledgeInfoClick = () => {
  // 更新富文本字段值
  formData.TourHoeseKnowledgeInfo.content = content.value?.getHtml();
  formEditTourHouseKnowledgeInfoRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourHoeseKnowledgeInfo
      };
    retFormData.typeDictMap = findItemFromList(typeWidgetDropdownList, retFormData.type, 'id');
    retFormData.enableDictMap = findItemFromList(enableWidgetDropdownList, retFormData.enable, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourHoeseKnowledgeInfoDto: {
        id: formData.TourHoeseKnowledgeInfo.id,
        type: formData.TourHoeseKnowledgeInfo.type,
        title: formData.TourHoeseKnowledgeInfo.title,
        content: formData.TourHoeseKnowledgeInfo.content,
        enable: formData.TourHoeseKnowledgeInfo.enable,
        createUserId: formData.TourHoeseKnowledgeInfo.createUserId,
        createTime: formData.TourHoeseKnowledgeInfo.createTime,
        updateUserId: formData.TourHoeseKnowledgeInfo.updateUserId,
        updateTime: formData.TourHoeseKnowledgeInfo.updateTime,
      }
    };

    let httpCall = isEdit.value ? TourHoeseKnowledgeInfoController.update : TourHoeseKnowledgeInfoController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourHoeseKnowledgeInfoData().then(res => {
    typeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    enableWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshFormEditTourHouseKnowledgeInfo();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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