<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="editFormTourUserInfo"
        :model="formData"
        :size="layoutStore.defaultFormItemSize"
        :rules="rules"
        label-width="120px"
        label-position="right"
        @submit.prevent
      >
        <el-row :gutter="16">
          <el-col :span="14">
            <el-form-item label="用户登录名" prop="TourUser.loginName">
              <el-input
                class="input-item"
                v-model="formData.TourUser.loginName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="密码" prop="TourUser.password">
              <el-input
                class="input-item"
                v-model="formData.TourUser.password"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="昵称" prop="TourUser.showName">
              <el-input
                class="input-item"
                v-model="formData.TourUser.showName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="用户头像的Url" prop="TourUser.headImageUrl">
              <el-upload
                class="upload-image-item"
                name="uploadFile"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourUser/upload')"
                :data="{fieldName: 'headImageUrl', asImage: true}"
                :on-success="onHeadImageUrlUploadSuccess"
                :on-remove="onHeadImageUrlRemoveFile"
                :on-error="onUploadError"
                :show-file-list="false"
              >
              <div v-if="headImageUrlWidgetFileList && headImageUrlWidgetFileList[0] != null" style="position: relative">
                <img class="upload-image-show"
                  :src="headImageUrlWidgetFileList[0].url" />
                <div class="upload-img-del el-icon-close"
                  @click.stop="onHeadImageUrlRemoveFile(null, null)" />
              </div>
              <i v-else class="el-icon-plus upload-image-item"></i>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="状态" prop="TourUser.userStatus">
              <el-radio-group
                class="input-item"
                v-model="formData.TourUser.userStatus"
              >
                <el-radio
                  v-for="item in userStatusWidgetDropdownList"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="用户邮箱" prop="TourUser.email">
              <el-input
                class="input-item"
                v-model="formData.TourUser.email"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="用户手机" prop="TourUser.mobile">
              <el-input
                class="input-item"
                v-model="formData.TourUser.mobile"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="性别" prop="TourUser.sex">
              <el-radio-group
                class="input-item"
                v-model="formData.TourUser.sex"
              >
                <el-radio
                  v-for="item in sexWidgetDropdownList"
                  :key="item.id"
                  :label="item.id"
                >
                  {{ item.name }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="生日" prop="TourUser.birthday">
              <el-date-picker
                class="input-item"
                v-model="formData.TourUser.birthday"
                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="onUpdateClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourUserInfo',
};
</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 { TourUserData } from '@/api/generated/tourUserController';
import { TourUserController } 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;
    userId?: ANY_OBJECT;
    saveOnSubmit?: boolean;
    rowData?: ANY_OBJECT;
    // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
    dialog?: DialogProp<ANY_OBJECT[]>;
  }>(),
  {
    subPage: 0,
    userId: undefined,
    saveOnSubmit: true,
    rowData: undefined,
    dialog: undefined,
  },
);

const editFormTourUserInfo = ref();
// 表单数据定义
type FormEditTourUserInfoData = {
  TourUser: TourUserData;
};
// 表单数据
const formData = reactive<FormEditTourUserInfoData>({
  TourUser: {
    // 主键Id
    userId: undefined,
    // 用户登录名称
    loginName: undefined,
    // 密码
    password: undefined,
    // 昵称
    showName: undefined,
    // 用户头像的Url
    headImageUrl: undefined,
    // 状态(0: 正常 1: 锁定)
    userStatus: undefined,
    // 用户邮箱
    email: undefined,
    // 用户手机
    mobile: undefined,
    // 性别(1:男 2:女 3:其它)
    sex: undefined,
    // 生日
    birthday: undefined,
    // 创建者Id
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新者Id
    updateUserId: undefined,
    // 最后更新时间
    updateTime: undefined,
    // 删除标记(1: 正常 -1: 已删除)
    deletedFlag: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourUser.email': [
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ],
  'TourUser.userStatus': [
    {required: true, message: '请输入状态', trigger: 'blur'}
  ],
  'TourUser.sex': [
  ],
  'TourUser.mobile': [
    {required: true, message: '请输入用户手机', trigger: 'blur'},
    {type: 'string', pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'},
  ],
  'TourUser.birthday': [
  ],
  'TourUser.password': [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  'TourUser.loginName': [
    {required: true, message: '请输入用户登录名', trigger: 'blur'}
  ],
  'TourUser.headImageUrl': [
  ],
  'TourUser.showName': [
    {required: true, message: '请输入昵称', trigger: 'blur'}
  ],
});

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

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

// 初始化页面数据
const loadTourUserData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourUser = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      userId: props.userId
    };
    TourUserController.view(params).then(res => {
      formData.TourUser = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 用户头像的Url上传成功
 */
const onHeadImageUrlUploadSuccess = (
  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);
    headImageUrlWidget.onFileChange(file, fileList);
    formData.TourUser.headImageUrl = fileListToJson(headImageUrlWidgetFileList);
  } else {
    ElMessage.error(response.message);
  }
};
/**
 * 移除用户头像的Url
 */
const onHeadImageUrlRemoveFile = (file: UploadFile | null, fileList: UploadFile[] | null) => {
  headImageUrlWidget.onFileChange(file, fileList);
  formData.TourUser.headImageUrl = fileListToJson(headImageUrlWidgetFileList);
};
// 用户头像的Url上传文件组件
const headImageUrlWidget = useUploadWidget(1);
const { fileList: headImageUrlWidgetFileList, maxCount: headImageUrlWidgetMaxCount } = headImageUrlWidget;
/**
 * 状态下拉数据获取函数
 */
const loadUserStatusDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.SysUserStatus.getList(),
  });
};
// 状态配置参数
const userStatusOptions: DropdownOptions<DictData> = {
  loadData: loadUserStatusDropdownList,
  isTree: false,
};
// 状态下拉组件
const userStatusWidget = useDropdown(userStatusOptions);
const { dropdownList: userStatusWidgetDropdownList } = userStatusWidget
/**
 * 性别下拉数据获取函数
 */
const loadSexDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'UserSex', itemIdType: 'String' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 性别配置参数
const sexOptions: DropdownOptions<DictData> = {
  loadData: loadSexDropdownList,
  isTree: false,
};
// 性别下拉组件
const sexWidget = useDropdown(sexOptions);
const { dropdownList: sexWidgetDropdownList } = sexWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshEditFormTourUserInfo = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetEditFormTourUserInfo = () => {
  refreshEditFormTourUserInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetEditFormTourUserInfo();
};
/**
 * 保存
 */
const onUpdateClick = () => {
  editFormTourUserInfo.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let formData = {
        ...formData.TourUser
      };
    formData.userStatusDictMap = findItemFromList(userStatusWidgetDropdownList, formData.userStatus, 'id');
    formData.sexDictMap = findItemFromList(sexWidgetDropdownList, formData.sex, 'id');
  props.dialog?.submit(formData);
      return;
    }
    let params: ANY_OBJECT = {
      tourUserDto: {
        userId: formData.TourUser.userId,
        loginName: formData.TourUser.loginName,
        password: formData.TourUser.password,
        showName: formData.TourUser.showName,
        headImageUrl: formData.TourUser.headImageUrl,
        userStatus: formData.TourUser.userStatus,
        email: formData.TourUser.email,
        mobile: formData.TourUser.mobile,
        sex: formData.TourUser.sex,
        birthday: formData.TourUser.birthday,
        createUserId: formData.TourUser.createUserId,
        createTime: formData.TourUser.createTime,
        updateUserId: formData.TourUser.updateUserId,
        updateTime: formData.TourUser.updateTime,
      }
    };

    let httpCall = isEdit.value ? TourUserController.update : TourUserController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourUserData().then(res => {
    let headImageUrlDownloadParams = {
      userId: formData.TourUser.userId,
      fieldName: 'headImageUrl',
      asImage: true
    };
    headImageUrlWidgetFileList.value = parseUploadData(formData.TourUser.headImageUrl, headImageUrlDownloadParams);
    userStatusWidget.onVisibleChange(true).catch(e => {console.error(e)});
    sexWidget.onVisibleChange(true).catch(e => {console.error(e)});
    if (isEdit.value) refreshEditFormTourUserInfo();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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