<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { postTypeOptions } from '@/constants/business';
import { fetchCreatePost, fetchGetPost, fetchUpdatePost } from '@/service/api';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';

defineOptions({ name: 'PostOperateDialog' });

interface Props {
  operateType: UI.TableOperateType;
  rowData?: Api.SystemManage.Post | null;
}

const props = defineProps<Props>();

const emit = defineEmits<{
  submitted: [postId: number];
}>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate } = useForm();
const { createRequiredRule } = useFormRules();

const detailLoading = ref(false);
const submitting = ref(false);
const isEdit = computed(() => props.operateType === 'edit');
const statusOptions = [
  { label: '启用', value: 0 as const },
  { label: '停用', value: 1 as const }
];

const title = computed(() => {
  const titleMap: Record<UI.TableOperateType, string> = {
    add: '新增岗位',
    edit: '编辑岗位'
  };

  return titleMap[props.operateType];
});

type Model = Api.SystemManage.SavePostParams;

const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    name: '',
    code: '',
    postType: null,
    levelRank: null,
    sort: 0,
    status: 0,
    remark: ''
  };
}

const rules = {
  name: createRequiredRule('请输入岗位名称'),
  code: createRequiredRule('请输入岗位编码'),
  postType: createRequiredRule('请选择岗位类型'),
  sort: createRequiredRule('请输入排序'),
  status: createRequiredRule('请选择岗位状态')
} satisfies Record<string, App.Global.FormRule>;

function closeModal() {
  visible.value = false;
}

async function initModel() {
  model.value = createDefaultModel();

  if (!isEdit.value || !props.rowData) {
    await nextTick();
    formRef.value?.clearValidate();
    return;
  }

  detailLoading.value = true;

  const { error, data } = await fetchGetPost(props.rowData.id);

  detailLoading.value = false;

  if (!error) {
    model.value = {
      name: data.name,
      code: data.code ?? '',
      postType: data.postType ?? null,
      levelRank: data.levelRank ?? null,
      sort: data.sort ?? 0,
      status: data.status,
      remark: data.remark ?? ''
    };
  }

  await nextTick();
  formRef.value?.clearValidate();
}

async function handleSubmit() {
  await validate();

  submitting.value = true;

  const submitData: Api.SystemManage.SavePostParams = {
    ...model.value,
    name: model.value.name.trim(),
    code: model.value.code?.trim() || null,
    remark: model.value.remark?.trim() || null
  };

  const request =
    isEdit.value && props.rowData
      ? await fetchUpdatePost({ id: props.rowData.id, ...submitData })
      : await fetchCreatePost(submitData);

  const { error, data } = await request;

  submitting.value = false;

  if (error) {
    return;
  }

  const postId = isEdit.value && props.rowData ? props.rowData.id : Number(data);

  window.$message?.success(isEdit.value ? '修改成功' : '新增成功');

  closeModal();
  emit('submitted', postId);
}

watch(visible, value => {
  if (value) {
    initModel();
  }
});
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="title"
    preset="md"
    :loading="detailLoading"
    :confirm-loading="submitting"
    :scrollbar="false"
    @confirm="handleSubmit"
  >
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElRow :gutter="16">
        <ElCol :span="12">
          <ElFormItem label="岗位名称" prop="name">
            <ElInput v-model="model.name" placeholder="请输入岗位名称" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="岗位编码" prop="code">
            <ElInput v-model="model.code" placeholder="请输入岗位编码" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="岗位类型" prop="postType">
            <ElSelect v-model="model.postType" class="w-full" placeholder="请选择岗位类型">
              <ElOption v-for="{ label, value } in postTypeOptions" :key="value" :label="label" :value="value" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="岗位职级" prop="levelRank">
            <ElInputNumber v-model="model.levelRank" class="w-full" :min="0" placeholder="请输入岗位职级" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="排序" prop="sort">
            <ElInputNumber v-model="model.sort" class="w-full" :min="0" placeholder="请输入排序" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="岗位状态" prop="status">
            <ElRadioGroup v-model="model.status" class="business-form-radio-group">
              <ElRadio v-for="{ label, value } in statusOptions" :key="value" :value="value">
                {{ label }}
              </ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="备注" prop="remark">
            <ElInput v-model="model.remark" type="textarea" :rows="4" placeholder="请输入备注" />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped></style>
