<script setup lang="ts">
import { computed, nextTick, ref, watch } from 'vue';
import { commonStatusOptions } from '@/constants/business';
import { fetchCreateRole, fetchGetRole, fetchUpdateRole } from '@/service/api';
import { useForm, useFormRules } from '@/hooks/common/form';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import { $t } from '@/locales';

defineOptions({ name: 'RoleOperateDialog' });

interface Props {
  operateType: UI.TableOperateType;
  rowData?: Api.SystemManage.Role | null;
  scopeType: Api.SystemManage.ScopeType;
  objectType?: Api.SystemManage.ObjectType;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted', roleId: string): void;
}

const emit = defineEmits<Emits>();

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 title = computed(() => {
  const titleMap: Record<UI.TableOperateType, string> = {
    add: $t('page.system.role.addRole'),
    edit: $t('page.system.role.editRole')
  };

  return titleMap[props.operateType];
});

type Model = Api.SystemManage.SaveRoleParams;

const model = ref(createDefaultModel());

function createDefaultModel(): Model {
  return {
    name: '',
    code: '',
    scopeType: props.scopeType,
    objectType: props.scopeType === 'object' ? props.objectType : undefined,
    sort: 0,
    status: 0,
    remark: ''
  };
}

function getCurrentScopeParams(): Api.SystemManage.ScopeQueryParams {
  if (props.scopeType === 'object') {
    return {
      scopeType: 'object',
      objectType: props.objectType
    };
  }

  return {
    scopeType: 'global'
  };
}

const rules = {
  name: createRequiredRule($t('page.system.role.form.roleName')),
  code: createRequiredRule($t('page.system.role.form.roleCode')),
  sort: createRequiredRule($t('page.system.role.form.sort')),
  status: createRequiredRule($t('page.system.role.form.roleStatus'))
} 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 fetchGetRole(props.rowData.id);

  detailLoading.value = false;

  if (!error) {
    model.value = {
      name: data.name,
      code: data.code,
      scopeType: data.scopeType ?? props.scopeType,
      objectType: data.objectType || (props.scopeType === 'object' ? props.objectType : undefined),
      sort: data.sort,
      status: data.status,
      remark: data.remark ?? ''
    };
  }

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

async function handleSubmit() {
  await validate();

  submitting.value = true;

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

  let roleId = props.rowData?.id ?? '';

  if (isEdit.value && props.rowData) {
    const { scopeType: _scopeType, objectType: _objectType, ...updateData } = submitData;
    const { error } = await fetchUpdateRole({ id: props.rowData.id, ...updateData });

    submitting.value = false;

    if (error) {
      return;
    }
  } else {
    const { error, data } = await fetchCreateRole(submitData);

    submitting.value = false;

    if (error) {
      return;
    }

    roleId = data;
  }

  window.$message?.success($t(isEdit.value ? 'common.updateSuccess' : 'common.addSuccess'));

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

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

<template>
  <BusinessFormDialog
    v-model="visible"
    :title="title"
    preset="sm"
    :loading="detailLoading"
    :confirm-loading="submitting"
    :scrollbar="false"
    @confirm="handleSubmit"
  >
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElRow :gutter="16">
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.role.roleName')" prop="name">
            <ElInput v-model="model.name" :placeholder="$t('page.system.role.form.roleName')" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.role.roleCode')" prop="code">
            <ElInput v-model="model.code" :placeholder="$t('page.system.role.form.roleCode')" />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.role.sort')" prop="sort">
            <ElInputNumber
              v-model="model.sort"
              class="w-full"
              :min="0"
              :placeholder="$t('page.system.role.form.sort')"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.role.roleStatus')" prop="status">
            <ElRadioGroup v-model="model.status" class="business-form-radio-group">
              <ElRadio v-for="{ label, value } in commonStatusOptions" :key="value" :value="value">
                {{ $t(label) }}
              </ElRadio>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem :label="$t('page.system.role.remark')" prop="remark">
            <ElInput
              v-model="model.remark"
              type="textarea"
              :rows="4"
              :placeholder="$t('page.system.role.form.remark')"
            />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
  </BusinessFormDialog>
</template>

<style scoped></style>
