<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-16px 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 v-if="props.modalTitle === '新增部门'" label="上级部门">
            <n-tag class="rounded">{{ props.rootDeptName }}</n-tag>
          </n-form-item>
          <n-form-item label="部门名称" path="deptName">
            <n-input v-model:value="modalForm.deptName" :clearable="true" placeholder="请输入部门名称" />
          </n-form-item>
          <n-form-item label="显示排序" path="orderNum">
            <n-input-number
              v-model:value="modalForm.orderNum"
              :min="0"
              :max="99"
              clearable
              placeholder="请输入显示排序"
            />
          </n-form-item>
          <n-form-item label="负责人" path="leader">
            <n-input v-model:value="modalForm.leader" :clearable="true" placeholder="请输入负责人" />
          </n-form-item>
          <n-form-item label="联系电话" path="phone">
            <n-input v-model:value="modalForm.phone" :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="item in SYSTEM_DEPT_STATUS" :key="item.value" :value="item.value">
                  {{ item.label }}
                </n-radio>
              </n-space>
            </n-radio-group>
          </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, watch } from 'vue';
import { Icon } from '@iconify/vue';
import type { FormInst, FormRules } from 'naive-ui';
import { fetchAddDept, fetchEditDept, fetchGetDeptDetail } from '@/service';
import { SYSTEM_DEPT_STATUS, SYSTEM_DEPT_STATUS_ENABLE } from '@/const/system';

interface Props {
  modalTitle: string;
  curEditDeptId: number;
  rootDeptName: string;
}
const props = defineProps<Props>();
const emits = defineEmits(['get-dept-tree']);
const showModal = ref(false);
const submitLoading = ref(false);
const modalForm = ref<System.DeptForm>({
  deptName: '',
  orderNum: 0,
  leader: '',
  phone: '',
  status: SYSTEM_DEPT_STATUS_ENABLE
});
const rules = ref<FormRules>({
  deptName: { required: true, message: '部门名称不能为空', trigger: ['input', 'blur'] }
});
const formRef = ref<FormInst | null>(null);
/** 提交 */
function handleSubmit() {
  formRef.value?.validate(async errors => {
    if (!errors) {
      submitLoading.value = true;
      const apis = {
        fetchAddDept,
        fetchEditDept
      };
      const apikey = props.modalTitle === '修改部门' ? 'fetchEditDept' : 'fetchAddDept';
      const params = {
        parentId: props.curEditDeptId,
        ...modalForm.value
      };
      const { data } = await apis[apikey](params);
      if (data?.ok) {
        window.$message?.success('操作成功');
        handleCloseModal();
        emits('get-dept-tree');
      }
    }
    submitLoading.value = false;
    return errors;
  });
}

/** 打开弹窗 */
function handleShowModal() {
  showModal.value = true;
}
/** 关闭弹窗 */
function handleCloseModal() {
  showModal.value = false;
  modalForm.value = {
    deptName: '',
    orderNum: 0,
    leader: '',
    phone: '',
    status: SYSTEM_DEPT_STATUS_ENABLE
  };
}

/** 获取部门详情 */
async function getDeptDetail<T>(deptId: T) {
  const { data } = await fetchGetDeptDetail(deptId);
  modalForm.value = data.data;
}

watch(showModal, val => {
  if (val) {
    setTimeout(() => {
      if (props.curEditDeptId !== -1 && props.modalTitle === '修改部门') getDeptDetail(props.curEditDeptId);
    });
  }
});

defineExpose({
  handleShowModal
});
</script>
