<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourFansRef"
        :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="TourFans.attentionId">
              <el-select
                class="input-item"
                v-model="formData.TourFans.attentionId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="attentionIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in attentionIdWidgetDropdownList"
                  :key="item.userId"
                  :label="item.showName"
                  :value="item.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="关注人" prop="TourFans.createUserId">
              <el-select
                class="input-item"
                v-model="formData.TourFans.createUserId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="createUserIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in createUserIdWidgetDropdownList"
                  :key="item.userId"
                  :label="item.showName"
                  :value="item.userId"
                />
              </el-select>
            </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="onSubmitTourFansClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourFans',
};
</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 { TourFansData } from '@/api/generated/tourFansController';
import {TourFansController, TourUserController} from '@/api/generated';
import TourUser from "@/types/table/tourUser";

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 formEditTourFansRef = ref();
// 表单数据定义
type FormEditTourFansData = {
  TourFans: TourFansData;
};
// 表单数据
const formData = reactive<FormEditTourFansData>({
  TourFans: {
    // 粉丝表id
    id: undefined,
    // 被关注人id
    attentionId: undefined,
    // 是否删除
    deleteFlag: undefined,
    // 创建人id
    createUserId: undefined,
    // 创建时间
    createTime: undefined,
    // 更新人id
    updateUserId: undefined,
    // 更新时间
    updateTime: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourFans.attentionId': [
    {required: true, message: '请输入被关注人', trigger: 'blur'}
  ],
  'TourFans.createUserId': [
  ],
});

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

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

// 初始化页面数据
const loadTourFansData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourFans = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourFansController.view(params).then(res => {
      formData.TourFans = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 被关注人下拉数据获取函数
 */
const loadAttentionIdDropdownList = (): Promise<ListData<TourUser>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    TourUserController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 被关注人配置参数
const attentionIdOptions: DropdownOptions<TourUser> = {
  loadData: loadAttentionIdDropdownList,
  isTree: false,
};
// 被关注人下拉组件
const attentionIdWidget = useDropdown(attentionIdOptions);
const { dropdownList: attentionIdWidgetDropdownList } = attentionIdWidget
/**
 * 关注人下拉数据获取函数
 */
const loadCreateUserIdDropdownList = (): Promise<ListData<TourUser>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    TourUserController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 关注人配置参数
const createUserIdOptions: DropdownOptions<TourUser> = {
  loadData: loadCreateUserIdDropdownList,
  isTree: false,
};
// 关注人下拉组件
const createUserIdWidget = useDropdown(createUserIdOptions);
const { dropdownList: createUserIdWidgetDropdownList } = createUserIdWidget
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourFans = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourFans = () => {
  refreshFormEditTourFans();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourFans();
};
/**
 * 保存
 */
const onSubmitTourFansClick = () => {
  formEditTourFansRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourFans
      };
    retFormData.attentionIdDictMap = attentionIdWidgetDropdownList.value.filter(item=>item.userId == formData.TourFans.attentionId)[0];
    retFormData.createUserIdDictMap = createUserIdWidgetDropdownList.value.filter(item=>item.userId == formData.TourFans.createUserId)[0];
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourFansDto: {
        id: formData.TourFans.id,
        attentionId: formData.TourFans.attentionId,
        createUserId: formData.TourFans.createUserId,
        createTime: formData.TourFans.createTime,
        updateUserId: formData.TourFans.updateUserId,
        updateTime: formData.TourFans.updateTime,
      }
    };

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

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