<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="editFormTourHouseAdvisorRef"
        :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="TourHouseAdvisorInfo.developersId">
              <el-select
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.developersId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="developersIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in developersIdWidgetDropdownList"
                  :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="TourHouseAdvisorInfo.type">
              <el-select
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.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="TourHouseAdvisorInfo.name">
              <el-input
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.name"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="行业经验年限" prop="TourHouseAdvisorInfo.experienceAge">
              <el-input-number
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.experienceAge"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成功交房数量" prop="TourHouseAdvisorInfo.successfulDeliveryCount">
              <el-input-number
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.successfulDeliveryCount"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否金牌顾问" prop="TourHouseAdvisorInfo.isGoldAdvisor">
              <el-select
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.isGoldAdvisor"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="isGoldAdvisorWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in isGoldAdvisorWidgetDropdownList"
                  :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="TourHouseAdvisorInfo.avatarUrl">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourHouseAdvisorInfo/upload')"
                :data="{fieldName: 'avatarUrl', asImage: true}"
                :on-success="onAvatarUrlUploadSuccess"
                :on-remove="onAvatarUrlRemoveFile"
                :on-error="onUploadError"
                :show-file-list="false"
              >
              <div v-if="avatarUrlWidgetFileList && avatarUrlWidgetFileList[0] != null" style="position: relative">
                <img class="upload-image-show"
                  :src="avatarUrlWidgetFileList[0].url" />
                <div class="upload-img-del el-icon-close"
                  @click.stop="onAvatarUrlRemoveFile(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="TourHouseAdvisorInfo.code">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourHouseAdvisorInfo/upload')"
                :data="{fieldName: 'code', asImage: true}"
                :on-success="onCodeUploadSuccess"
                :on-remove="onCodeRemoveFile"
                :on-error="onUploadError"
                :show-file-list="false"
              >
              <div v-if="codeWidgetFileList && codeWidgetFileList[0] != null" style="position: relative">
                <img class="upload-image-show"
                  :src="codeWidgetFileList[0].url" />
                <div class="upload-img-del el-icon-close"
                  @click.stop="onCodeRemoveFile(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="TourHouseAdvisorInfo.recordNumber">
              <el-input
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.recordNumber"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="公司名称" prop="TourHouseAdvisorInfo.companyName">
              <el-input
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.companyName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="TourHouseAdvisorInfo.mobile">
              <el-input
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.mobile"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否启用" prop="TourHouseAdvisorInfo.enable">
              <el-radio-group
                class="input-item"
                v-model="formData.TourHouseAdvisorInfo.enable"
              >
                <el-radio
                  v-for="item in enableWidgetDropdownList"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </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="onSaveClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'editFormTourHouseAdvisor',
};
</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 { TourHouseAdvisorInfoData } from '@/api/generated/tourHouseAdvisorInfoController';
import { TourHouseAdvisorInfoController } 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 editFormTourHouseAdvisorRef = ref();
// 表单数据定义
type EditFormTourHouseAdvisorData = {
  TourHouseAdvisorInfo: TourHouseAdvisorInfoData;
};
// 表单数据
const formData = reactive<EditFormTourHouseAdvisorData>({
  TourHouseAdvisorInfo: {
    // 主键
    id: undefined,
    // 所属开发商
    developersId: undefined,
    // 顾问类型 0.顾问 1.房东
    type: undefined,
    // 姓名
    name: undefined,
    // 行业经验年限
    experienceAge: undefined,
    // 成功交房数量
    successfulDeliveryCount: undefined,
    // 是否金牌顾问 0不是 1是
    isGoldAdvisor: undefined,
    // 头像url
    avatarUrl: undefined,
    // 备案编号
    recordNumber: undefined,
    // 公司名称
    companyName: undefined,
    // 二维码
    code: undefined,
    // 是否启用，0禁用，1启用
    enable: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    dataState: undefined,
    // 手机号
    mobile: undefined,
    // 创建人
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 修改人
    updateUserId: undefined,
    // 修改时间
    updateTime: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourHouseAdvisorInfo.code': [
    {required: true, message: '请输入二维码', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.companyName': [
    {required: true, message: '请输入公司名称', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.enable': [
    {required: true, message: '请输入是否启用', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.name': [
    {required: true, message: '请输入姓名', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.developersId': [
    {required: true, message: '请输入所属开发商', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.successfulDeliveryCount': [
    {required: true, message: '请输入成功交房数量', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.experienceAge': [
    {required: true, message: '请输入行业经验年限', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.isGoldAdvisor': [
    {required: true, message: '请输入是否金牌顾问', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.mobile': [
    {required: true, message: '请输入手机号', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.type': [
    {required: true, message: '请输入顾问类型', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.recordNumber': [
    {required: true, message: '请输入备案编号', trigger: 'blur'}
  ],
  'TourHouseAdvisorInfo.avatarUrl': [
    {required: true, message: '请输入头像url', trigger: 'blur'}
  ],
});

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

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

// 初始化页面数据
const loadTourHouseAdvisorInfoData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourHouseAdvisorInfo = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourHouseAdvisorInfoController.view(params).then(res => {
      formData.TourHouseAdvisorInfo = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 所属开发商下拉数据获取函数
 */
const loadDevelopersIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourHouseDevelopersType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 所属开发商配置参数
const developersIdOptions: DropdownOptions<DictData> = {
  loadData: loadDevelopersIdDropdownList,
  isTree: false,
};
// 所属开发商下拉组件
const developersIdWidget = useDropdown(developersIdOptions);
const { dropdownList: developersIdWidgetDropdownList } = developersIdWidget
/**
 * 顾问类型下拉数据获取函数
 */
const loadTypeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'AdvisorType', 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 loadIsGoldAdvisorDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.IsGoldAdvisor.getList(),
  });
};
// 是否金牌顾问配置参数
const isGoldAdvisorOptions: DropdownOptions<DictData> = {
  loadData: loadIsGoldAdvisorDropdownList,
  isTree: false,
};
// 是否金牌顾问下拉组件
const isGoldAdvisorWidget = useDropdown(isGoldAdvisorOptions);
const { dropdownList: isGoldAdvisorWidgetDropdownList } = isGoldAdvisorWidget
/**
 * 头像url上传成功
 */
const onAvatarUrlUploadSuccess = (
  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);
    avatarUrlWidget.onFileChange(file, fileList);
    formData.TourHouseAdvisorInfo.avatarUrl = fileListToJson(avatarUrlWidgetFileList.value);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除头像url
 */
const onAvatarUrlRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  avatarUrlWidget.onFileChange(file, fileList);
  formData.TourHouseAdvisorInfo.avatarUrl = fileListToJson(avatarUrlWidgetFileList.value);
};
// 头像url上传文件组件
const avatarUrlWidget = useUploadWidget(1);
const { fileList: avatarUrlWidgetFileList, maxCount: avatarUrlWidgetMaxCount } = avatarUrlWidget;
/**
 * 二维码上传成功
 */
const onCodeUploadSuccess = (
  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);
    codeWidget.onFileChange(file, fileList);
    formData.TourHouseAdvisorInfo.code = fileListToJson(codeWidgetFileList.value);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除二维码
 */
const onCodeRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  codeWidget.onFileChange(file, fileList);
  formData.TourHouseAdvisorInfo.code = fileListToJson(codeWidgetFileList.value);
};
// 二维码上传文件组件
const codeWidget = useUploadWidget(1);
const { fileList: codeWidgetFileList, maxCount: codeWidgetMaxCount } = codeWidget;
/**
 * 是否启用下拉数据获取函数
 */
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 onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshEditFormTourHouseAdvisor = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetEditFormTourHouseAdvisor = () => {
  refreshEditFormTourHouseAdvisor();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetEditFormTourHouseAdvisor();
};
/**
 * 保存
 */
const onSaveClick = () => {
  editFormTourHouseAdvisorRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourHouseAdvisorInfo
      };
    retFormData.developersIdDictMap = findItemFromList(developersIdWidgetDropdownList, retFormData.developersId, 'id');
    retFormData.typeDictMap = findItemFromList(typeWidgetDropdownList, retFormData.type, 'id');
    retFormData.isGoldAdvisorDictMap = findItemFromList(isGoldAdvisorWidgetDropdownList, retFormData.isGoldAdvisor, 'id');
    retFormData.enableDictMap = findItemFromList(enableWidgetDropdownList, retFormData.enable, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourHouseAdvisorInfoDto: {
        id: formData.TourHouseAdvisorInfo.id,
        type: formData.TourHouseAdvisorInfo.type,
        mobile: formData.TourHouseAdvisorInfo.mobile,
        developersId: formData.TourHouseAdvisorInfo.developersId,
        name: formData.TourHouseAdvisorInfo.name,
        experienceAge: formData.TourHouseAdvisorInfo.experienceAge,
        successfulDeliveryCount: formData.TourHouseAdvisorInfo.successfulDeliveryCount,
        isGoldAdvisor: formData.TourHouseAdvisorInfo.isGoldAdvisor,
        avatarUrl: formData.TourHouseAdvisorInfo.avatarUrl,
        recordNumber: formData.TourHouseAdvisorInfo.recordNumber,
        companyName: formData.TourHouseAdvisorInfo.companyName,
        code: formData.TourHouseAdvisorInfo.code,
        enable: formData.TourHouseAdvisorInfo.enable,
        createUserId: formData.TourHouseAdvisorInfo.createUserId,
        createTime: formData.TourHouseAdvisorInfo.createTime,
        updateUserId: formData.TourHouseAdvisorInfo.updateUserId,
        updateTime: formData.TourHouseAdvisorInfo.updateTime,
      }
    };

    let httpCall = isEdit.value ? TourHouseAdvisorInfoController.update : TourHouseAdvisorInfoController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourHouseAdvisorInfoData().then(res => {
    developersIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    typeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    isGoldAdvisorWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let avatarUrlDownloadParams = {
      id: formData.TourHouseAdvisorInfo.id,
      fieldName: 'avatarUrl',
      asImage: true
    };
    avatarUrlWidgetFileList.value = parseUploadData(formData.TourHouseAdvisorInfo.avatarUrl, avatarUrlDownloadParams);
    let codeDownloadParams = {
      id: formData.TourHouseAdvisorInfo.id,
      fieldName: 'code',
      asImage: true
    };
    codeWidgetFileList.value = parseUploadData(formData.TourHouseAdvisorInfo.code, codeDownloadParams);
    enableWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshEditFormTourHouseAdvisor();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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