<template>
  <vxe-modal
    resize
    v-model="showModal"
    :title="modalTitle"
    @hide="onHide"
    width="400px"
    show-footer
    esc-closable
  >
    <el-form ref="formRef" inline :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item class="w-full" label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="w-full" label="用户名称" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="w-full" label="调解中心">
            <el-select v-model="form.tenant" placeholder="请选择调解中心" clearable>
              <el-option
                v-for="item in Tenantlist"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="w-full" label="部门">
            <el-tree-select
              placeholder="请选择部门"
              clearable
              v-model="form.departmentId"
              ref="treeselect"
              :checkStrictly="true"
              :props="{ value: 'id', label: 'name', children: 'children' }"
              :data="departlist"
              :render-after-expand="false"
            />
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item class="w-full" label="角色" prop="roles">
            <el-select
              v-model="form.roles"
              multiple
              collapse-tags
              clearable
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in options"
                :key="item.roleCode"
                :label="item.roleName"
                :value="item.roleCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="w-full" label="是否启用IP验证" prop="ipStatus">
            <el-radio-group v-model="form.ipStatus">
              <el-radio value="Y">是</el-radio>
              <el-radio value="N">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.ipStatus === 'Y'">
          <el-form-item class="w-full" label="IP地址" prop="ip">
            <el-input v-model="form.ip" placeholder="请输入IP地址" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="w-full" label="是否启用MAC验证" prop="macStatus">
            <el-radio-group v-model="form.macStatus">
              <el-radio value="Y">是</el-radio>
              <el-radio value="N">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.macStatus === 'Y'">
          <el-form-item class="w-full" label="MAC地址" prop="mac">
            <el-input v-model="form.mac" placeholder="请输入MAC地址" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item class="w-full" label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio value="enable">启用</el-radio>
              <el-radio value="disable">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <el-button type="default" @click="showModal = false">取消</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </template>
  </vxe-modal>
</template>

<script setup>
  import { computed } from 'vue';
  import { ref } from 'vue';
  import { saveUser } from '@/api/user';
  import { getDefualtRoles } from '@/api/role';
  import { ElMessage } from 'element-plus';
  import { getTenantPage } from '@/api/tenant';
  import { getdepartmentTree } from '@/api/departmentManage';

  const emits = defineEmits(['success']);
  const formRef = ref();
  const treeselect = ref();
  const showModal = ref(false);
  const loading = ref(false);
  const form = ref({
    username: '',
    ip: '',
    mac: '',
    roles: [],
    phone: '',
    departmentId: null,
    tenant: null,
    status: 'enable',
    macStatus: 'N',
    ipStatus: 'N'
  });
  const options = ref([]);
  const departlist = ref([]);
  const Tenantlist = ref([]);
  const validatePhone = (rule, value, callback) => {
    const reg = /^1[3-9]\d{9}$/;
    if (!value) {
      callback(new Error('请输入手机号'));
    } else if (!reg.test(value)) {
      callback(new Error('请输入正确的手机号'));
    } else {
      callback();
    }
  };
  const rules = ref({
    username: { required: true, message: '请输入用户名称', trigger: 'blur' },
    ip: { required: true, message: '请输入IP地址', trigger: 'blur' },
    mac: { required: true, message: '请输入MAC地址', trigger: 'blur' },
    phone: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validatePhone, trigger: 'blur' },
    ],
  });

  const currentAccount = ref(null);
  const isEdit = computed(() => !!currentAccount.value);
  const modalTitle = computed(() => (isEdit.value ? '编辑账号' : '新增账号'));
  const treeToArray = (tree) => {
    return tree.reduce((res, item) => {
      const { children, ...i } = item;
      return res.concat(i, children && children.length ? treeToArray(children) : []);
    }, []);
  };
  const submitForm = async () => {
    try {
      await formRef.value.validate();
      loading.value = true;
      if (form.value.tenant) {
        const item = Tenantlist.value.find((v) => v.id === form.value.tenant);
        form.value.tenant = item;
      }
      if (form.value.departmentId) {
        const list = treeToArray(departlist.value);
        const item = list.find((v) => v.id === form.value.departmentId);
      }
      await saveUser(form.value);
      ElMessage({
        type: 'success',
        message: isEdit.value ? '修改成功！' : '添加成功！',
        plain: true,
      });
      emits('success');
      showModal.value = false;
    } catch {}
    loading.value = false;
  };

  const onHide = () => {
    form.value = {
      username: '',
      ip: '',
      mac: '',
      roles: [],
      phone: '',
      departmentId: null,
      tenant: null,
      status: 'enable',
      macStatus: 'N',
      ipStatus: 'N'
    };
    formRef.value.clearValidate();
    currentAccount.value = null;
    showModal.value = false;
  };

  const openModal = (account) => {
    if (account) {
      form.value = account;
      if (account.tenant) {
        form.value.tenant = account.tenant.id;
      }
    }
    getDefualtRoles().then((res) => {
      options.value = res.result;
    });
    getTenantPage({ current: 1, size: 9999999, status: 'enable' }).then((res) => {
      if (res.success) {
        Tenantlist.value = res.result.content;
      }
    });
    getdepartmentTree().then((res) => {
      if (res.success) {
        departlist.value = res.result;
      }
    });
    currentAccount.value = account;
    showModal.value = true;
  };

  defineExpose({
    openModal,
  });
</script>
<style lang="scss" scoped></style>
