<template>
  <a-modal
    v-model:visible="props.visible"
    :title="props.tenantId ? '编辑' : '新增'"
    :width="800"
    style="top: 20px"
    @cancel="dialogClose"
  >
    <a-form ref="formRef" :model="formData" :label-col="{ style: { width: '140px' } }">
      <div class="flex">
        <a-form-item
          label="租户图片"
          name="image"
          :rules="{ 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>
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="名称"
          name="name"
          class="flex-1"
          :rules="{ required: true, message: '请输入名称', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.name" placeholder="请输入名称" allow-clear />
        </a-form-item>
        <a-form-item
          label="编号"
          name="code"
          class="flex-1"
          :rules="{ required: true, message: '请输入编号', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.code" allow-clear placeholder="请输入编号" />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="统一社会信用代码"
          name="license"
          class="flex-1"
          :rules="{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }"
        >
          <a-input
            v-model:value="formData.license"
            placeholder="请输入统一社会信用代码"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          label="联系人"
          name="contactUser"
          class="flex-1"
          :rules="{ required: true, message: '请输入联系人', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.contactUser" placeholder="请输入联系人" allow-clear />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="联系电话"
          name="contactMobile"
          class="flex-1"
          :rules="{ required: true, message: '请输入联系电话', trigger: 'blur' }"
        >
          <a-input
            v-model:value="formData.contactMobile"
            placeholder="请输入联系电话"
            allow-clear
          />
        </a-form-item>
        <a-form-item
          label="邮箱地址"
          name="contactEmail"
          class="flex-1"
          :rules="[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确邮箱地址', trigger: 'blur' },
          ]"
        >
          <a-input v-model:value="formData.contactEmail" placeholder="请输入邮箱地址" allow-clear />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="官网地址"
          name="contactSite"
          class="flex-1"
          :rules="{ required: true, message: '请输入官网地址', trigger: 'blur' }"
        >
          <a-input v-model:value="formData.contactSite" placeholder="请输入官网地址" allow-clear />
        </a-form-item>
        <a-form-item
          label="用户限额"
          name="number"
          class="flex-1"
          :rules="{ required: true, message: '请输入用户限额', trigger: 'blur' }"
        >
          <number-input v-model="formData.number" placeholder="请输入用户限额" allow-clear />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="过期时间"
          name="expireTime"
          class="flex-1"
          :rules="{ required: true, message: '请选择过期时间', trigger: 'change' }"
        >
          <a-date-picker
            show-time
            placeholder="请选择过期时间"
            v-model:value="formData.expireTime"
            format="YYYY-MM-DD HH:mm:ss"
            valueFormat="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
        <a-form-item
          label="租户地址"
          name="contactAddress"
          class="flex-1"
          :rules="{ required: true, message: '请输入租户地址', trigger: 'blur' }"
        >
          <a-input
            v-model:value="formData.contactAddress"
            placeholder="请输入租户地址"
            allow-clear
          />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item
          label="简介"
          name="contactIntro"
          class="flex-1"
          :rules="{ required: true, message: '请输入简介', trigger: 'blur' }"
        >
          <a-input
            v-model:value="formData.contactIntro"
            type="textarea"
            placeholder="请输入简介"
            allow-clear
          />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item label="备注" name="contactNote" class="flex-1">
          <a-input
            v-model:value="formData.contactNote"
            type="textarea"
            placeholder="请输入备注"
            allow-clear
          />
        </a-form-item>
      </div>
      <div class="flex">
        <a-form-item label="租户状态" name="status" class="flex-1">
          <a-radio-group v-model:value="formData.status" name="status">
            <a-radio :value="0">正常</a-radio>
            <a-radio :value="1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </div>
    </a-form>
    <template #footer>
      <span class="dialog-footer">
        <a-button @click="dialogClose">取消</a-button>
        <a-button :loading="subLoading" type="primary" @click="submit"> 确定 </a-button>
      </span>
    </template>
  </a-modal>
</template>

<script lang="ts" setup>
  import { getTenantDetail, tenantAdd, tenantUpdate } from '@/api/system/tenant';
  import { onMounted, reactive, shallowRef } 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 type { FormInstance } from 'ant-design-vue';
  import { useLockFn } from '@/utils/useLockFn';

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

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

  /**
   * 定义接收的参数
   */
  const formData = reactive({
    id: 0,
    code: '',
    name: '',
    image: '',
    license: '',
    contactUser: '',
    contactMobile: '',
    contactEmail: '',
    contactAddress: '',
    contactIntro: '',
    contactSite: '',
    contactNote: '',
    expireTime: '',
    status: 0,
    number: '',
  });
  const passwordConfirmValidator = (rule: object, value: string, callback: any) => {
    if (formData.password) {
      if (!value) callback(new Error('请再次输入密码'));
      if (value !== formData.password) callback(new Error('两次输入密码不一致!'));
    }
    callback();
  };

  /**
   * 关闭窗体
   */
  const dialogClose = () => {
    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];
      }
    }
  };

  /**
   * 执行提交表单
   */
  const handleSubmit = async () => {
    console.log(formData);
    await formRef.value?.validate();
    props.tenantId ? await tenantUpdate(formData) : await tenantAdd(formData);
    emit('update:visible', false);
    emit('success');
  };

  const { isLock: subLoading, lockFn: submit } = useLockFn(handleSubmit);

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

  function uploadChange(data: string[]) {
    formData.avatar = data.fileUrl;
    formData.avatarName = data.fileName;
  }
  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 });
    }
  });
</script>
