<template>
  <n-modal v-model:show="showModal" :on-after-leave="handleCloseModal" :mask-closable="false" :bordered="false">
    <n-card :title="props.modalTitle" class="w-500px rounded-8px shadow-sm">
      <template #header-extra>
        <Icon icon="ic:sharp-close" class="text-size-22px cursor-pointer" @click="showModal = false" />
      </template>
      <div>
        <n-form ref="formRef" label-placement="left" :label-width="80" :model="modalForm" :rules="rules">
          <n-form-item label="用户名" path="userName">
            <n-input
              v-model:value="modalForm.userName"
              maxlength="20"
              show-count
              :disabled="props.curEditUserId !== -1"
              :clearable="true"
              placeholder="请输入用户名称"
            />
          </n-form-item>
          <n-form-item label="用户姓名" path="nickName">
            <n-input
              v-model:value="modalForm.nickName"
              maxlength="20"
              show-count
              :clearable="true"
              placeholder="请输入用户姓名"
            />
          </n-form-item>
          <n-form-item label="手机号" path="phonenumber">
            <n-input
              v-model:value="modalForm.phonenumber"
              maxlength="11"
              show-count
              :clearable="true"
              placeholder="请输入手机号"
            />
          </n-form-item>
          <n-form-item label="所属部门" path="deptId">
            <n-tree-select
              v-model:value="modalForm.deptId"
              filterable
              :options="deptTreeOptions"
              label-field="deptName"
              key-field="deptId"
            />
          </n-form-item>
          <n-form-item label="所属角色" path="roleIds">
            <n-select v-model:value="modalForm.roleIds" multiple :options="roleOptions" />
          </n-form-item>
          <n-form-item v-if="modalTitle === '新增用户'" label="用户密码" path="password">
            <n-input
              v-model:value="modalForm.password"
              maxlength="16"
              type="password"
              show-password-on="mousedown"
              :clearable="true"
              placeholder="请输入用户密码"
            />
          </n-form-item>
          <n-form-item label="用户状态" path="status">
            <n-radio-group v-model:value="modalForm.status" name="radiogroup">
              <n-space>
                <n-radio v-for="status in SYSTEM_USER_STATUS" :key="status.value" :value="status.value">
                  {{ status.label }}
                </n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>
          <!-- <n-form-item label="用户类型" path="userType">
            <n-select v-model:value="modalForm.userType" :options="USER_TYPE_OPTIONS" />
          </n-form-item> -->
        </n-form>
      </div>
      <template #footer>
        <div class="w-full flex justify-center">
          <NButton @click="showModal = false">取消</NButton>
          <NButton :loading="submitLoading" class="ml-4" type="primary" @click="handleSubmit">提交</NButton>
        </div>
      </template>
    </n-card>
  </n-modal>
</template>
<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import type { FormInst, FormRules, FormItemRule, SelectOption, TreeSelectOption } from 'naive-ui';
import { Icon } from '@iconify/vue';
import { fetchGetDetpTree, fetchGetRoles, fetchAddUser, fetchEditUser, fetchGetUserDetail } from '@/service';
import {
  SYSTEM_USER_SEX_MAN,
  SYSTEM_USER_STATUS,
  SYSTEM_USER_STATUS_ENABLE,
  EMAIL_OPTIONS,
  USER_TYPE_SYS
} from '@/const/system';

interface Props {
  modalTitle: string;
  curEditUserId: number;
}
const props = defineProps<Props>();
const emits = defineEmits(['get-user-list']);

const showModal = ref(false);
const submitLoading = ref(false);
const modalForm = ref<System.UserForm>({
  nickName: '',
  userName: '',
  email: '',
  sex: SYSTEM_USER_SEX_MAN,
  password: '',
  status: SYSTEM_USER_STATUS_ENABLE,
  deptId: '',
  roleIds: [],
  remark: '',
  userType: USER_TYPE_SYS,
  phonenumber: ''
});
const rules = ref<FormRules>({
  nickName: { required: true, message: '用户姓名不能为空', trigger: ['input', 'blur'] },
  userName: { required: true, message: '用户名称不能为空', trigger: ['input', 'blur'] },
  password: {
    required: true,
    validator: (rule: FormItemRule, value: string) => {
      if (!value) {
        return new Error('请输入6-16位的除空格、汉字外的字符');
      }
      if (!/^[^\u4e00-\u9fa5 ]{6,16}$/.test(value)) {
        return new Error('请输入6-16位的除空格、汉字外的字符');
      }
      return true;
    }
  },
  phonenumber: { required: true, message: '手机号不能为空', trigger: ['input', 'blur'] },
  // userType: { required: true, message: '用户类型不能为空', trigger: ['input', 'blur'] },
  roleIds: {
    required: true,
    message: '角色不能为空',
    trigger: ['input', 'blur'],
    validator: (rule: FormItemRule, value: any) => {
      if (value.length === 0) {
        return new Error('角色不能为空');
      }
      return true;
    }
  },
  sex: { required: true, trigger: ['blur'] },
  status: { required: true, trigger: ['blur'] }
});

const formRef = ref<FormInst | null>(null);

/** 提交 */
function handleSubmit() {
  formRef.value?.validate(async errors => {
    if (!errors) {
      submitLoading.value = true;
      const apis = {
        fetchEditUser,
        fetchAddUser
      };
      const apikey = props.modalTitle === '修改用户' ? 'fetchEditUser' : 'fetchAddUser';
      const { data } = await apis[apikey](modalForm.value);
      if (data?.ok) {
        window.$message?.success('操作成功');
        handleCloseModal();
        emits('get-user-list');
      }
    }
    submitLoading.value = false;
    return errors;
  });
}

/** 打开弹窗 */
function handleShowModal() {
  showModal.value = true;
}
/** 关闭弹窗 */
function handleCloseModal() {
  showModal.value = false;
  modalForm.value = {
    nickName: '',
    userName: '',
    email: '',
    sex: SYSTEM_USER_SEX_MAN,
    password: '',
    status: SYSTEM_USER_STATUS_ENABLE,
    deptId: '',
    roleIds: [],
    remark: '',
    userType: USER_TYPE_SYS,
    phonenumber: ''
  };
}
/** 所属角色的options */
const roleOptions = ref<SelectOption[]>([]);
/** 获取所属角色的options */
async function getRolesOptions() {
  const { data } = await fetchGetRoles(1, 10000, '');
  if (data?.ok) {
    const roleArray: SelectOption[] = [];
    data.data.rows.forEach((role: { roleName: any; roleId: any }) => {
      roleArray.push({
        label: role.roleName,
        value: role.roleId
      });
    });
    roleOptions.value = roleArray;
  }
}
/** 所属部门的默认值 */
const deptTreeValue = ref(0);
/** 所属部门的options */
const deptTreeOptions = ref<TreeSelectOption[]>([]);
/** 获取所属部门的options */
async function getDeptTreeOptions() {
  const { data } = await fetchGetDetpTree();
  if (data?.ok) {
    deptTreeOptions.value = data.data;
  }
}

/** 邮箱的options */
const emailOptions = computed(() => {
  return EMAIL_OPTIONS.map(suffix => {
    const prefix = modalForm.value.email.split('@')[0];
    return {
      label: prefix + suffix,
      value: prefix + suffix
    };
  });
});
/** 获取用户详情 */
async function getUserDetail<T>(userId: T) {
  const { data } = await fetchGetUserDetail(userId);
  modalForm.value = data.data.user;
  modalForm.value.roleIds = data.data.roleIds;
  deptTreeValue.value = data.data.deptId;
}

watch(showModal, val => {
  if (val) {
    getDeptTreeOptions();
    getRolesOptions();
    setTimeout(() => {
      if (props.curEditUserId !== -1) getUserDetail(props.curEditUserId);
    });
  }
});

defineExpose({
  handleShowModal
});
</script>
