<template>
  <el-dialog v-model="props.visible" :title="props.tenantId ? '编辑' : '新增'" width="800" :close-on-click-modal="false"
    :before-close="dialogClose">
    <el-form ref="formRef" :model="formData" label-width="140px">
      <div class="flex">
        <el-form-item label="名称" prop="name" class="flex-1"
          :rules="{ required: true, message: '请输入名称', trigger: 'blur' }">
          <el-input v-model="formData.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="编号" prop="code" class="flex-1"
          :rules="{ required: true, message: '请输入编号', trigger: 'blur' }">
          <el-input v-model="formData.code" clearable
            placeholder="请输入编号" />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="统一社会信用代码" prop="license" class="flex-1"
          :rules="{ required: true, message: '请输入统一社会信用代码', trigger: 'blur' }">
          <el-input v-model="formData.license" placeholder="请输入统一社会信用代码" clearable />
        </el-form-item>
        <el-form-item label="联系人" prop="contactUser" class="flex-1"
        :rules="{ required: true, message: '请输入联系人', trigger: 'blur' }">
          <el-input v-model="formData.contactUser" placeholder="请输入联系人" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="联系电话" prop="contactMobile" class="flex-1"
          :rules="{ required: true, message: '请输入联系电话', trigger: 'blur' }">
          <el-input v-model="formData.contactMobile" placeholder="请输入联系电话" clearable />
        </el-form-item>
        <el-form-item label="邮箱地址" prop="contactEmail" class="flex-1"
          :rules="[{ required: true, message: '请输入邮箱地址', trigger: 'blur' },{ type: 'email', message: '请输入正确邮箱地址', trigger: 'blur'}]">
          <el-input v-model="formData.contactEmail" placeholder="请输入邮箱地址" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="官网地址" prop="contactSite" class="flex-1"
        :rules="{ required: true, message: '请输入官网地址', trigger: 'blur'}">
          <el-input v-model="formData.contactSite" placeholder="请输入官网地址" clearable />
        </el-form-item>
        <el-form-item label="用户数量" prop="number" class="flex-1"
        :rules="{ required: true, message: '请输入用户数量', trigger: 'blur'}">
          <number-input v-model="formData.number" placeholder="请输入用户数量" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="过期时间" prop="expireTime"  class="flex-1"
        :rules="{ required: true, message: '请选择过期时间', trigger: 'blur'}">
          <el-date-picker type="datetime" placeholder="请选择过期时间" v-model="formData.expireTime" />
        </el-form-item>
        <el-form-item label="租户地址" prop="contactAddress" class="flex-1"
        :rules="{ required: true, message: '请输入租户地址', trigger: 'blur'}">
          <el-input v-model="formData.contactAddress" placeholder="请输入租户地址" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="简介" prop="contactIntro" class="flex-1"
        :rules="{ required: true, message: '请输入简介', trigger: 'blur'}">
          <el-input v-model="formData.contactIntro" type="textarea" placeholder="请输入简介" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="备注" prop="contactNote" class="flex-1">
          <el-input v-model="formData.contactNote" type="textarea" placeholder="请输入备注" clearable />
        </el-form-item>
      </div>
      <div class="flex">
        <el-form-item label="租户状态" prop="status" class="flex-1">
          <el-radio-group v-model="formData.status" name="status">
            <el-radio :value="0">正常</el-radio>
            <el-radio :value="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</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 {buildTree } from "@/utils/auth";
import { FormInstance } from "element-plus";

const formRef = shallowRef<FormInstance>();
import { useLockFn } from "@/utils/useLockFn";
const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  tenantId: {
    type: Number,
    required: true,
    default: 0
  }
});

const emit = defineEmits(["success", "update:visible"]);
const formData = reactive({
  id: 0,
  code:'',
  name: '',
  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);
};

const setFormData = async (row: any) => {
  const data = await getTenantDetail(row.tenantId);
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      if(key=='city'){
        if(data.city.length>0){
          formData[key] = [parseInt(data.city[0]),parseInt(data.city[1]),parseInt(data.city[2]),parseInt(data.city[3])];
        }else{
          formData[key] =''
        }
      }else{
        formData[key] = data[key];
      }
    }
  }
};

const handleSubmit = async () => {
  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>