<template>
  <basicModal
    @register="modalRegister"
    ref="modalRef"
    class="basicModal basicFormModal"
    @on-ok="handleSubmit"
    @on-close="handleClose"
  >
    <template #default>
      <n-form ref="formRef" :model="formData" label-placement="left" label-width="140px">
        <div class="flex">
          <n-form-item
            label="租户图片"
            path="image"
            :rule="{ required: true, message: '请上传租户图片', trigger: 'change' }"
          >
            <UploadImg
              @change-file-name="(name) => (formData.imageImgName = name)"
              :fileType="['image/jpeg', 'image/png', 'image/jpg', 'image/gif']"
              name="tenant"
              :fileSize="200"
              v-model:image-url="formData.image"
              :cropper="false"
            >
              <template #tip>支持扩展名: jpg png jpeg;文件大小不超过200M</template>
            </UploadImg>
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="名称"
            path="name"
            class="flex-1"
            :rule="{ required: true, message: '请输入名称', trigger: 'blur' }"
          >
            <n-input v-model:value="formData.name" placeholder="请输入名称" clearable />
          </n-form-item>
          <n-form-item
            label="编号"
            path="code"
            class="flex-1"
            :rule="{ required: true, message: '请输入编号', trigger: 'blur' }"
          >
            <n-input v-model:value="formData.code" clearable placeholder="请输入编号" />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="统一社会信用代码"
            path="license"
            class="flex-1"
            :rule="{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }"
          >
            <n-input
              v-model:value="formData.license"
              placeholder="请输入统一社会信用代码"
              clearable
            />
          </n-form-item>
          <n-form-item
            label="联系人"
            path="contactUser"
            class="flex-1"
            :rule="{ required: true, message: '请输入联系人', trigger: 'blur' }"
          >
            <n-input v-model:value="formData.contactUser" placeholder="请输入联系人" clearable />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="联系电话"
            path="contactMobile"
            class="flex-1"
            :rule="{ required: true, message: '请输入联系电话', trigger: 'blur' }"
          >
            <n-input
              v-model:value="formData.contactMobile"
              placeholder="请输入联系电话"
              clearable
            />
          </n-form-item>
          <n-form-item
            label="邮箱地址"
            path="contactEmail"
            class="flex-1"
            :rule="[
              { required: true, message: '请输入邮箱地址', trigger: 'blur' },
              { type: 'email', message: '请输入正确邮箱地址', trigger: 'blur' },
            ]"
          >
            <n-input v-model:value="formData.contactEmail" placeholder="请输入邮箱地址" clearable />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="官网地址"
            path="contactSite"
            class="flex-1"
            :rule="{ required: true, message: '请输入官网地址', trigger: 'blur' }"
          >
            <n-input v-model:value="formData.contactSite" placeholder="请输入官网地址" clearable />
          </n-form-item>
          <n-form-item
            label="用户限额"
            path="number"
            class="flex-1"
            :rule="{ required: true, message: '请输入用户限额', trigger: 'blur' }"
          >
            <number-input v-model="formData.number" placeholder="请输入用户限额" clearable />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="过期时间"
            path="expireTime"
            class="flex-1"
            :rule="{ type: 'date', required: true, message: '请选择过期时间', trigger: 'change' }"
          >
            <n-date-picker
              type="datetime"
              placeholder="请选择过期时间"
              v-model:value="formData.expireTime"
              format="yyyy-MM-dd HH:mm:ss"
              valueFormat="yyyy-MM-dd HH:mm:ss"
              clearable
            />
          </n-form-item>
          <n-form-item
            label="租户地址"
            path="contactAddress"
            class="flex-1"
            :rule="{ required: true, message: '请输入租户地址', trigger: 'blur' }"
          >
            <n-input
              v-model:value="formData.contactAddress"
              placeholder="请输入租户地址"
              clearable
            />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item
            label="简介"
            path="contactIntro"
            class="flex-1"
            :rule="{ required: true, message: '请输入简介', trigger: 'blur' }"
          >
            <n-input
              v-model:value="formData.contactIntro"
              type="textarea"
              placeholder="请输入简介"
              clearable
            />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item label="备注" path="contactNote" class="flex-1">
            <n-input
              v-model:value="formData.contactNote"
              type="textarea"
              placeholder="请输入备注"
              clearable
            />
          </n-form-item>
        </div>
        <div class="flex">
          <n-form-item label="租户状态" path="status" class="flex-1">
            <n-radio-group v-model:value="formData.status" name="status">
              <n-radio :value="0">正常</n-radio>
              <n-radio :value="1">禁用</n-radio>
            </n-radio-group>
          </n-form-item>
        </div>
      </n-form>
    </template>
  </basicModal>
</template>

<script lang="ts" setup>
  import { getTenantDetail, tenantAdd, tenantUpdate } from '@/api/system/tenant';
  import { onMounted, reactive, ref } from 'vue';
  import { getRoleAllList } from '@/api/system/role';
  import { getDeptList } from '@/api/system/dept';
  import { getLevelAllList } from '@/api/system/level';
  import { getPositionAllList } from '@/api/system/position';
  import UploadImg from '@/components/Upload/Image.vue';
  import { buildTree } from '@/utils/auth';
  import { useMessage } from 'naive-ui';
  import { useModal } from '@/components/Modal';

  /**
   * 定义参数变量
   */
  const formRef = ref();
  const emit = defineEmits(['success', 'update:visible']);

  /**
   * 定义接收的参数
   */
  const props = defineProps({
    visible: {
      type: Boolean,
      required: true,
      default: false,
    },
    tenantId: {
      type: Number,
      required: true,
      default: 0,
    },
  });

  /**
   * 定义接收的参数
   */
  const [modalRegister, { openModal, setSubLoading }] = useModal({
    title: props.tenantId ? '编辑租户' : '添加租户',
    subBtuText: '确定',
    width: 800,
  });

  /**
   * 定义表单参数
   */
  const formData = reactive({
    id: 0,
    code: '',
    name: '',
    image: '',
    license: '',
    contactUser: '',
    contactMobile: '',
    contactEmail: '',
    contactAddress: '',
    contactIntro: '',
    contactSite: '',
    contactNote: '',
    expireTime: null,
    status: 0,
    number: '',
  });
  const modalRef = ref();
  const message = useMessage();
  /**
   * 关闭窗体
   */
  const handleClose = () => {
    emit('update:visible', false);
  };

  /**
   * 设置表单数据
   * @param row 参数
   */
  const setFormData = async (row: any) => {
    const data = await getTenantDetail(row.tenantId);
    for (const key in formData) {
      if (data[key] != null && data[key] != undefined) {
        formData[key] = data[key];
      }
    }
    formData.number = formData.number + '';
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    formRef.value
      .validate()
      .then(async () => {
        props.tenantId ? await tenantUpdate(formData) : await tenantAdd(formData);
        setSubLoading(false);
        message.success('操作成功');
        emit('update:visible', false);
        emit('success');
      })
      .catch((error) => {
        setSubLoading(false);
      });
  };

  /**
   * 定义选项数据
   */
  const optionData = reactive({
    roleList: [],
    deptList: [],
    levelList: [],
    positionList: [],
  });

  /**
   * 上传发生变化
   * @param data 参数
   */
  function uploadChange(data: string[]) {
    formData.avatar = data.fileUrl;
    formData.avatarName = data.fileName;
  }

  /**
   * 执行删除文件
   * @param file 文件参数
   */
  const handleDelete = async (file) => {
    console.log(file);
  };

  /**
   * 获取全部字典数据
   */
  const getAllDict = async () => {
    let list = await getRoleAllList();
    optionData.roleList = list ? list : [];
    list = await getDeptList();
    optionData.deptList = list ? buildTree(list) : [];
    list = await getLevelAllList();
    optionData.levelList = list ? list : [];
    list = await getPositionAllList();
    optionData.positionList = list ? list : [];
  };

  /**
   * 钩子函数
   */
  onMounted(() => {
    getAllDict();
    if (props.tenantId) {
      setFormData({ tenantId: props.tenantId });
    }
  });

  /**
   * 定义函数
   */
  defineExpose({
    openModal,
  });
</script>
