<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditTourImComplaitRef"
        :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="TourImComplait.userId">
              <el-select
                class="input-item"
                v-model="formData.TourImComplait.userId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="userIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in userIdWidgetDropdownList"
                  :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="TourImComplait.groupId">
              <el-select
                class="input-item"
                v-model="formData.TourImComplait.groupId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="groupIdWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in groupIdWidgetDropdownList"
                  :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="TourImComplait.typeId">
              <el-select
                class="input-item"
                v-model="formData.TourImComplait.typeId"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="typeId_copyWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in typeId_copyWidgetDropdownList"
                  :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="TourImComplait.objectType">
              <el-select
                class="input-item"
                v-model="formData.TourImComplait.objectType"
                placeholder=""
                :clearable="true"
                :filterable="true"
                @visible-change="objectTypeWidget.onVisibleChange"
              >
                <el-option
                  v-for="item in objectTypeWidgetDropdownList"
                  :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="TourImComplait.elseTypeReason">
              <el-input
                class="input-item"
                v-model="formData.TourImComplait.elseTypeReason"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="举报描述" prop="TourImComplait.description">
              <el-input
                class="input-item"
                v-model="formData.TourImComplait.description"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="举报图片" prop="TourImComplait.image">
              <custom-upload
                v-model="imageWidgetFileList"
                name="uploadFile"
                :size="layoutStore.defaultFormItemSize"
                type="expand"
                :headers="getUploadHeaders"
                :action="getUploadActionUrl('/admin/app/tourImComplait/upload')"
                :data="{fieldName: 'image', asImage: true}"
                :limit="imageWidgetMaxCount"
                @change="onImageChange"
              />
            </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="onSubmitTourImComplaitClick()">保存</el-button>
    </el-row>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formEditTourImComplait',
};
</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 { TourImComplaitData } from '@/api/generated/tourImComplaitController';
import {TourImComplaitController, 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 formEditTourImComplaitRef = ref();
// 表单数据定义
type FormEditTourImComplaitData = {
  TourImComplait: TourImComplaitData;
};
// 表单数据
const formData = reactive<FormEditTourImComplaitData>({
  TourImComplait: {
    // id
    id: undefined,
    // 举报类型id
    typeId: undefined,
    // 类型为其他违规的理由
    elseTypeReason: undefined,
    // 举报对象 1用户 2群组
    objectType: undefined,
    // 举报描述
    description: undefined,
    // 举报图片 最多三张
    image: undefined,
    // 删除标记 1正常 -1删除
    dataState: undefined,
    // 创建人id
    createUserId: undefined,
    // 用户id
    userId: undefined,
    // 创建时间
    createTime: undefined,
    // 群组id
    groupId: undefined,
    // 更新时间
    updateTime: undefined,
    // 更新人id
    updateUserId: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'TourImComplait.groupId': [
  ],
  'TourImComplait.elseTypeReason': [
  ],
  'TourImComplait.typeId': [
    {required: true, message: '请输入举报类型', trigger: 'blur'}
  ],
  'TourImComplait.objectType': [
    {required: true, message: '请输入举报对象', trigger: 'blur'}
  ],
  'TourImComplait.userId': [
  ],
  'TourImComplait.image': [
  ],
  'TourImComplait.description': [
    {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 loadTourImComplaitData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.TourImComplait = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      id: props.id
    };
    TourImComplaitController.view(params).then(res => {
      formData.TourImComplait = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 用户下拉数据获取函数
 */
const loadUserIdDropdownList = (): 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 userIdOptions: DropdownOptions<TourUser> = {
  loadData: loadUserIdDropdownList,
  isTree: false,
};
// 用户下拉组件
const userIdWidget = useDropdown(userIdOptions);
const { dropdownList: userIdWidgetDropdownList } = userIdWidget
/**
 * 群组下拉数据获取函数
 */
const loadGroupIdDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourImGroup(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 群组配置参数
const groupIdOptions: DropdownOptions<DictData> = {
  loadData: loadGroupIdDropdownList,
  isTree: false,
};
// 群组下拉组件
const groupIdWidget = useDropdown(groupIdOptions);
const { dropdownList: groupIdWidgetDropdownList } = groupIdWidget
/**
 * 举报类型下拉数据获取函数
 */
const loadTypeId_copyDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictTourImComplaintType(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 举报类型配置参数
const typeId_copyOptions: DropdownOptions<DictData> = {
  loadData: loadTypeId_copyDropdownList,
  isTree: false,
};
// 举报类型下拉组件
const typeId_copyWidget = useDropdown(typeId_copyOptions);
const { dropdownList: typeId_copyWidgetDropdownList } = typeId_copyWidget
/**
 * 举报对象下拉数据获取函数
 */
const loadObjectTypeDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    DictionaryController.dictGlobalDict({ dictCode: 'ComplaintObjectType', itemIdType: 'Integer' }).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 举报对象配置参数
const objectTypeOptions: DropdownOptions<DictData> = {
  loadData: loadObjectTypeDropdownList,
  isTree: false,
};
// 举报对象下拉组件
const objectTypeWidget = useDropdown(objectTypeOptions);
const { dropdownList: objectTypeWidgetDropdownList } = objectTypeWidget
/**
 * 举报图片上传文件改变
 */
const onImageChange = val => {
  formData.TourImComplait.image = fileListToJson(val);
};
// 举报图片上传文件组件
const imageWidget = useUploadWidget(3);
const { fileList: imageWidgetFileList, maxCount: imageWidgetMaxCount } = imageWidget;
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditTourImComplait = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditTourImComplait = () => {
  refreshFormEditTourImComplait();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditTourImComplait();
};
/**
 * 保存
 */
const onSubmitTourImComplaitClick = () => {
  formEditTourImComplaitRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.TourImComplait
      };
    retFormData.userIdDictMap = findItemFromList(userIdWidgetDropdownList.value, retFormData.userId, 'id');
    retFormData.groupIdDictMap = findItemFromList(groupIdWidgetDropdownList.value, retFormData.groupId, 'id');
    retFormData.typeIdDictMap = findItemFromList(typeId_copyWidgetDropdownList.value, retFormData.typeId, 'id');
    retFormData.objectTypeDictMap = findItemFromList(objectTypeWidgetDropdownList.value, retFormData.objectType, 'id');
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      tourImComplaitDto: {
        id: formData.TourImComplait.id,
        objectType: formData.TourImComplait.objectType,
        userId: formData.TourImComplait.userId,
        groupId: formData.TourImComplait.groupId,
        typeId: formData.TourImComplait.typeId,
        elseTypeReason: formData.TourImComplait.elseTypeReason,
        description: formData.TourImComplait.description,
        image: formData.TourImComplait.image,
        createUserId: formData.TourImComplait.createUserId,
        createTime: formData.TourImComplait.createTime,
        updateTime: formData.TourImComplait.updateTime,
        updateUserId: formData.TourImComplait.updateUserId,
      }
    };

    let httpCall = isEdit.value ? TourImComplaitController.update : TourImComplaitController.add;
    httpCall(params).then(res => {
      ElMessage.success('保存成功');
      props.dialog?.submit();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  });
};
const formInit = () => {
  loadTourImComplaitData().then(res => {
    userIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    groupIdWidget.onVisibleChange(true).catch(e => {console.error(e)});
    typeId_copyWidget.onVisibleChange(true).catch(e => {console.error(e)});
    objectTypeWidget.onVisibleChange(true).catch(e => {console.error(e)});
    let imageDownloadParams = {
      id: formData.TourImComplait.id,
      fieldName: 'image',
      asImage: true
    };
    imageWidgetFileList.value = parseUploadData(formData.TourImComplait.image, imageDownloadParams);
    if (isEdit.value) refreshFormEditTourImComplait();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};

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