<script setup lang="ts">
import type { FormInstance } from 'element-plus';

import { ref } from 'vue';

import { EasyFlowFormModal } from '@easyflow/common-ui';

import {
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElTreeSelect,
} from 'element-plus';

import { api } from '#/api/request';
import DictSelect from '#/components/dict/DictSelect.vue';
import { $t } from '#/locales';

const emit = defineEmits(['reload']);
defineExpose({
  openDialog,
});
const saveForm = ref<FormInstance>();
// variables
const ENABLED_STATUS = 1;
const dialogVisible = ref(false);
const isAdd = ref(true);
const entity = ref<any>(buildDefaultEntity());
const btnLoading = ref(false);
const parentDepartmentOptions = ref<any[]>([]);
let parentDepartmentOptionsLoaded = false;
const rules = ref({
  parentId: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
  deptName: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
  status: [
    { required: true, message: $t('message.required'), trigger: 'blur' },
  ],
});
// functions
function buildDefaultEntity() {
  return {
    ancestors: '',
    deptCode: '',
    deptName: '',
    parentId: '',
    remark: '',
    sortNo: '',
    status: ENABLED_STATUS,
  };
}
async function openDialog(row: any = {}) {
  isAdd.value = !row.id;
  entity.value = {
    ...buildDefaultEntity(),
    ...row,
  };
  dialogVisible.value = true;
  if (!parentDepartmentOptionsLoaded) {
    try {
      const res = await api.get('/api/v1/sysDept/list', {
        params: {
          asTree: true,
          sortKey: 'sortNo',
          sortType: 'asc',
        },
      });
      parentDepartmentOptions.value = [
        { id: 0, deptName: $t('sysDept.root'), children: [] },
        ...(Array.isArray(res.data) ? res.data : []),
      ];
      parentDepartmentOptionsLoaded = true;
    } catch {
      parentDepartmentOptions.value = [];
    }
  }
}
async function save() {
  if (btnLoading.value) {
    return;
  }
  btnLoading.value = true;
  try {
    const valid = await saveForm.value?.validate().catch(() => false);
    if (!valid) {
      return;
    }
    const res = await api.post(
      isAdd.value ? 'api/v1/sysDept/save' : 'api/v1/sysDept/update',
      entity.value,
    );
    if (res.errorCode === 0) {
      ElMessage.success(res.message);
      emit('reload');
      closeDialog();
    }
  } finally {
    btnLoading.value = false;
  }
}
function closeDialog() {
  saveForm.value?.resetFields();
  isAdd.value = true;
  entity.value = buildDefaultEntity();
  dialogVisible.value = false;
}
</script>

<template>
  <EasyFlowFormModal
    v-model:open="dialogVisible"
    :closable="!btnLoading"
    :title="isAdd ? $t('button.add') : $t('button.edit')"
    :before-close="closeDialog"
    :confirm-loading="btnLoading"
    :confirm-text="$t('button.save')"
    :submitting="btnLoading"
    @confirm="save"
  >
    <ElForm
      ref="saveForm"
      :model="entity"
      status-icon
      :rules="rules"
      label-position="top"
      class="easyflow-modal-form easyflow-modal-form--compact"
    >
      <ElFormItem prop="parentId" :label="$t('sysDept.parentId')">
        <ElTreeSelect
          :disabled="entity.deptCode === 'root_dept'"
          v-model="entity.parentId"
          :data="parentDepartmentOptions"
          :props="{ label: 'deptName', value: 'id', children: 'children' }"
          check-strictly
          clearable
          filterable
        />
      </ElFormItem>
      <ElFormItem prop="deptName" :label="$t('sysDept.deptName')">
        <ElInput v-model.trim="entity.deptName" />
      </ElFormItem>
      <ElFormItem prop="deptCode" :label="$t('sysDept.deptCode')">
        <ElInput
          :disabled="entity.deptCode === 'root_dept'"
          v-model.trim="entity.deptCode"
        />
      </ElFormItem>
      <ElFormItem prop="sortNo" :label="$t('sysDept.sortNo')">
        <ElInput v-model.trim="entity.sortNo" />
      </ElFormItem>
      <ElFormItem prop="status" :label="$t('sysDept.status')">
        <DictSelect
          v-model="entity.status"
          :clearable="false"
          dict-code="dataStatus"
        />
      </ElFormItem>
      <ElFormItem prop="remark" :label="$t('sysDept.remark')">
        <ElInput v-model.trim="entity.remark" />
      </ElFormItem>
    </ElForm>
  </EasyFlowFormModal>
</template>

<style scoped></style>
