<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourVisaCounselorRef"
        :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="TourVisaCounselor.counselorName">
              <el-input
                class="input-item"
                v-model="formData.TourVisaCounselor.counselorName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="顾问电话" prop="TourVisaCounselor.counselorPhone">
              <el-input
                class="input-item"
                v-model="formData.TourVisaCounselor.counselorPhone"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="顾问级别" prop="TourVisaCounselor.level">
              <el-select
                class="input-item"
                v-model="formData.TourVisaCounselor.level"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="levelWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in levelWidgetDropdownList"
                  :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="TourVisaCounselor.start">
              <el-input-number
                class="input-item"
                v-model="formData.TourVisaCounselor.start"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="下班时间" prop="TourVisaCounselor.end">
              <el-input-number
                class="input-item"
                v-model="formData.TourVisaCounselor.end"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="首页显示顾问" prop="TourVisaCounselor.indexFlag">
              <el-select
                class="input-item"
                v-model="formData.TourVisaCounselor.indexFlag"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="indexFlagWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in indexFlagWidgetDropdownList"
                  :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="TourVisaCounselor.counselorAvatar">
              <custom-upload
                v-model="counselorAvatarWidgetFileList"
                name="uploadFile"
                :size="layoutStore.defaultFormItemSize"
                type="expand"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourVisaCounselor/upload')"
                :data="{fieldName: 'counselorAvatar', asImage: true}"
                :limit="counselorAvatarWidgetMaxCount"
                @change="onCounselorAvatarChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="顾问微信" prop="TourVisaCounselor.counselorWechat">
              <custom-upload
                v-model="counselorWechatWidgetFileList"
                name="uploadFile"
                :size="layoutStore.defaultFormItemSize"
                type="expand"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourVisaCounselor/upload')"
                :data="{fieldName: 'counselorWechat', asImage: true}"
                :limit="counselorWechatWidgetMaxCount"
                @change="onCounselorWechatChange"
              />
            </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="onSubmitTourVisaCounselorClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourVisaCounselor',
};
</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 { TourVisaCounselorData } from '@/api/generated/tourVisaCounselorController';
import { TourVisaCounselorController } 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 formEditTourVisaCounselorRef = ref();
// 表单数据定义
type FormEditTourVisaCounselorData = {
  TourVisaCounselor: TourVisaCounselorData;
};
// 表单数据
const formData = reactive<FormEditTourVisaCounselorData>({
  TourVisaCounselor: {
    // 顾问id
    id: undefined,
    // 顾问头像
    counselorAvatar: undefined,
    // 顾问电话
    counselorPhone: undefined,
    // 顾问微信
    counselorWechat: undefined,
    // 顾问姓名
    counselorName: undefined,
    // 逻辑删除 1正常 -1已删除
    deleteFlag: undefined,
    // 创建人id
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新人id
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
    // 级别
    level: undefined,
    // 上班时间
    start: undefined,
    // 下班时间
    end: undefined,
    // 首页显示顾问
    indexFlag: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourVisaCounselor.start': [
    {required: true, message: '请输入上班时间', trigger: 'blur'}
  ],
  'TourVisaCounselor.end': [
    {required: true, message: '请输入下班时间', trigger: 'blur'}
  ],
  'TourVisaCounselor.indexFlag': [
    {required: true, message: '请输入首页显示顾问', trigger: 'blur'},
  ],
  'TourVisaCounselor.level': [
    {required: true, message: '请输入顾问级别', trigger: 'blur'}
  ],
  'TourVisaCounselor.counselorAvatar': [
    {required: true, message: '请输入顾问头像', trigger: 'blur'}
  ],
  'TourVisaCounselor.counselorWechat': [
    {required: true, message: '请输入顾问微信', trigger: 'blur'}
  ],
  'TourVisaCounselor.counselorPhone': [
    {required: true, message: '请输入顾问电话', trigger: 'blur'}
  ],
  'TourVisaCounselor.counselorName': [
    {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 loadTourVisaCounselorData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourVisaCounselor = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourVisaCounselorController.view(params).then(res => {
      formData.TourVisaCounselor = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 顾问级别下拉数据获取函数
 */
const loadLevelDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.VisaConsoluerLevel.getList(),
  });
};
// 顾问级别配置参数
const levelOptions: DropdownOptions<DictData> = {
  loadData: loadLevelDropdownList,
  isTree: false,
};
// 顾问级别下拉组件
const levelWidget = useDropdown(levelOptions);
const { dropdownList: levelWidgetDropdownList } = levelWidget
/**
 * 首页显示顾问下拉数据获取函数
 */
const loadIndexFlagDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.VisaIndexFlag.getList(),
  });
};
// 首页显示顾问配置参数
const indexFlagOptions: DropdownOptions<DictData> = {
  loadData: loadIndexFlagDropdownList,
  isTree: false,
};
// 首页显示顾问下拉组件
const indexFlagWidget = useDropdown(indexFlagOptions);
const { dropdownList: indexFlagWidgetDropdownList } = indexFlagWidget
/**
 * 顾问头像上传文件改变
 */
const onCounselorAvatarChange = val => {
  formData.TourVisaCounselor.counselorAvatar = fileListToJson(val);
};
// 顾问头像上传文件组件
const counselorAvatarWidget = useUploadWidget(1);
const { fileList: counselorAvatarWidgetFileList, maxCount: counselorAvatarWidgetMaxCount } = counselorAvatarWidget;
/**
 * 顾问微信上传文件改变
 */
const onCounselorWechatChange = val => {
  formData.TourVisaCounselor.counselorWechat = fileListToJson(val);
};
// 顾问微信上传文件组件
const counselorWechatWidget = useUploadWidget(1);
const { fileList: counselorWechatWidgetFileList, maxCount: counselorWechatWidgetMaxCount } = counselorWechatWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourVisaCounselor = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourVisaCounselor = () => {
  refreshFormEditTourVisaCounselor();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourVisaCounselor();
};
/**
 * 保存
 */
const onSubmitTourVisaCounselorClick = () => {
  formEditTourVisaCounselorRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourVisaCounselor
      };
    retFormData.levelDictMap = findItemFromList(levelWidgetDropdownList.value, retFormData.level, 'id');
    retFormData.indexFlagDictMap = findItemFromList(indexFlagWidgetDropdownList.value, retFormData.indexFlag, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourVisaCounselorDto: {
        id: formData.TourVisaCounselor.id,
        level: formData.TourVisaCounselor.level,
        start: formData.TourVisaCounselor.start,
        end: formData.TourVisaCounselor.end,
        indexFlag: formData.TourVisaCounselor.indexFlag,
        counselorAvatar: formData.TourVisaCounselor.counselorAvatar,
        counselorPhone: formData.TourVisaCounselor.counselorPhone,
        counselorWechat: formData.TourVisaCounselor.counselorWechat,
        counselorName: formData.TourVisaCounselor.counselorName,
        createUserId: formData.TourVisaCounselor.createUserId,
        createTime: formData.TourVisaCounselor.createTime,
        updateUserId: formData.TourVisaCounselor.updateUserId,
        updateTime: formData.TourVisaCounselor.updateTime,
      }
    };

    let httpCall = isEdit.value ? TourVisaCounselorController.update : TourVisaCounselorController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourVisaCounselorData().then(res => {
    levelWidget.onVisibleChange(true).catch(e => {console.error(e)});
    indexFlagWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let counselorAvatarDownloadParams = {
      id: formData.TourVisaCounselor.id,
      fieldName: 'counselorAvatar',
      asImage: true
    };
    counselorAvatarWidgetFileList.value = parseUploadData(formData.TourVisaCounselor.counselorAvatar, counselorAvatarDownloadParams);
    let counselorWechatDownloadParams = {
      id: formData.TourVisaCounselor.id,
      fieldName: 'counselorWechat',
      asImage: true
    };
    counselorWechatWidgetFileList.value = parseUploadData(formData.TourVisaCounselor.counselorWechat, counselorWechatDownloadParams);
    if (isEdit.value) refreshFormEditTourVisaCounselor();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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