<template>
  <div class="dialog-box" style="position: relative">
    <el-scrollbar class="custom-scroll content-box">
      <el-form
        ref="formEditChinaAreaRef"
        :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="ChinaArea.name">
              <el-input
                class="input-item"
                v-model="formData.ChinaArea.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="ChinaArea.cityCode">
              <el-input-number
                class="input-item"
                v-model="formData.ChinaArea.cityCode"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市名称" prop="ChinaArea.cityName">
              <el-input
                class="input-item"
                v-model="formData.ChinaArea.cityName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省编码" prop="ChinaArea.provinceCode">
              <el-input-number
                class="input-item"
                v-model="formData.ChinaArea.provinceCode"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省名称" prop="ChinaArea.provinceName">
              <el-input
                class="input-item"
                v-model="formData.ChinaArea.provinceName"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国家" prop="ChinaArea.country">
              <el-input
                class="input-item"
                v-model="formData.ChinaArea.country"
                type="text"
                placeholder=""
                :clearable="true"
                :show-word-limit="false"
                maxlength=""
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="等级 1：省,2：市,3：区县" prop="ChinaArea.level">
              <el-input-number
                class="input-item"
                v-model="formData.ChinaArea.level"
                placeholder=""
                :clearable="true"
                :step="1"
                :controls="true"
              />
            </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="onSubmitChinaAreaClick()">保存</el-button>
    </el-row>
  </div>
</template>

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

const formEditChinaAreaRef = ref();
// 表单数据定义
type FormEditChinaAreaData = {
  ChinaArea: ChinaAreaData;
};
// 表单数据
const formData = reactive<FormEditChinaAreaData>({
  ChinaArea: {
    // 地区编码
    code: undefined,
    // 地区名称
    name: undefined,
    // 城市编码
    cityCode: undefined,
    // 城市名称
    cityName: undefined,
    // 省编码
    provinceCode: undefined,
    // 省名称
    provinceName: undefined,
    // 国家
    country: undefined,
    // 等级 1：省,2：市,3：区县
    level: undefined,
  },
},
);
// 表单验证规则
const rules = reactive({
  'ChinaArea.name': [
    {required: true, message: '请输入地区名称', trigger: 'blur'}
  ],
  'ChinaArea.cityName': [
  ],
  'ChinaArea.cityCode': [
    {required: true, message: '请输入城市编码', trigger: 'blur'}
  ],
  'ChinaArea.provinceName': [
  ],
  'ChinaArea.provinceCode': [
    {required: true, message: '请输入省编码', trigger: 'blur'}
  ],
  'ChinaArea.level': [
  ],
  'ChinaArea.country': [
  ],
});

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

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

// 初始化页面数据
const loadChinaAreaData = () => {
  return new Promise<void>((resolve, reject) => {
    if (!isEdit.value) {
      resolve();
      return;
    }
    if (!props.saveOnSubmit && props.rowData != null) {
      formData.ChinaArea = JSON.parse(JSON.stringify(props.rowData));
      resolve();
      return;
    }
    let params: ANY_OBJECT = {
      code: props.code
    };
    ChinaAreaController.view(params).then(res => {
      formData.ChinaArea = { ...res.data };
      resolve();
    }).catch(e => {
      reject(e);
    });
  });
};
const onUploadError = () => {
  ElMessage.error('文件上传失败');
};
const onUploadLimit = () => {
  ElMessage.error('已经超出最大上传个数限制');
};
const refreshFormEditChinaArea = () => {
  // 刷新段落
};
/**
 * 重置过滤值
 */
const resetFormEditChinaArea = () => {
  refreshFormEditChinaArea();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormEditChinaArea();
};
/**
 * 保存
 */
const onSubmitChinaAreaClick = () => {
  formEditChinaAreaRef.value.validate((valid) => {
    if (!valid) return;
    // 级联操作
    if (!props.saveOnSubmit) {
      let retFormData = {
        ...formData.ChinaArea
      };
  props.dialog?.submit(retFormData);
      return;
    }
    let params: ANY_OBJECT = {
      chinaAreaDto: {
        code: formData.ChinaArea.code,
        name: formData.ChinaArea.name,
        cityCode: formData.ChinaArea.cityCode,
        cityName: formData.ChinaArea.cityName,
        provinceCode: formData.ChinaArea.provinceCode,
        provinceName: formData.ChinaArea.provinceName,
        country: formData.ChinaArea.country,
        level: formData.ChinaArea.level,
      }
    };

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

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