import type { Ref } from 'vue';

/**
 * 文件职责：员工管理动作。
 * 1. 管理员工抽屉开关与表单字段。
 * 2. 执行新增、编辑、删除员工请求。
 */
import type { StoreStaffDto } from '#/api/store-staff';
import type {
  StaffDrawerMode,
  StaffEditorFormState,
} from '#/views/store/staff/types';

import { message } from 'ant-design-vue';

import { deleteStoreStaffApi, saveStoreStaffApi } from '#/api/store-staff';

import { DEFAULT_STAFF_FORM } from './constants';
import { cloneStaffForm } from './helpers';

interface CreateStaffActionsOptions {
  deletingStaffId: Ref<string>;
  isStaffSaving: Ref<boolean>;
  isStaffDrawerOpen: Ref<boolean>;
  reloadStoreData: () => Promise<void>;
  selectedStoreId: Ref<string>;
  staffDrawerMode: Ref<StaffDrawerMode>;
  staffForm: StaffEditorFormState;
}

export function createStaffActions(options: CreateStaffActionsOptions) {
  /** 重置员工表单。 */
  function resetStaffForm() {
    Object.assign(options.staffForm, cloneStaffForm(DEFAULT_STAFF_FORM));
  }

  /** 打开员工抽屉。 */
  function openStaffDrawer(mode: StaffDrawerMode, staff?: StoreStaffDto) {
    options.staffDrawerMode.value = mode;
    if (mode === 'edit' && staff) {
      Object.assign(options.staffForm, {
        id: staff.id,
        name: staff.name,
        phone: staff.phone,
        email: staff.email,
        roleType: staff.roleType,
        status: staff.status,
        permissions: [...staff.permissions],
      } satisfies StaffEditorFormState);
    } else {
      resetStaffForm();
    }
    options.isStaffDrawerOpen.value = true;
  }

  /** 设置员工姓名。 */
  function setStaffName(value: string) {
    options.staffForm.name = value;
  }

  /** 设置员工手机号。 */
  function setStaffPhone(value: string) {
    options.staffForm.phone = value;
  }

  /** 设置员工邮箱。 */
  function setStaffEmail(value: string) {
    options.staffForm.email = value;
  }

  /** 设置员工角色。 */
  function setStaffRoleType(value: StaffEditorFormState['roleType']) {
    options.staffForm.roleType = value;

    // 1. 店长默认拥有“全部权限”。
    if (value === 'manager' && options.staffForm.permissions.length === 0) {
      options.staffForm.permissions = ['全部权限'];
    }
  }

  /** 设置员工状态。 */
  function setStaffStatus(value: StaffEditorFormState['status']) {
    options.staffForm.status = value;
  }

  /** 设置员工权限。 */
  function setStaffPermissions(value: string[]) {
    options.staffForm.permissions = [
      ...new Set(value.map((item) => item.trim()).filter(Boolean)),
    ];
  }

  /** 提交新增/编辑员工。 */
  async function handleSubmitStaff() {
    if (!options.selectedStoreId.value) return;

    const name = options.staffForm.name.trim();
    const phone = options.staffForm.phone.replaceAll(/\D/g, '');

    if (!name) {
      message.error('请输入员工姓名');
      return;
    }

    if (phone.length !== 11) {
      message.error('请输入 11 位手机号');
      return;
    }

    options.isStaffSaving.value = true;
    try {
      await saveStoreStaffApi({
        storeId: options.selectedStoreId.value,
        id: options.staffForm.id || undefined,
        name,
        phone,
        email: options.staffForm.email.trim(),
        roleType: options.staffForm.roleType,
        status: options.staffForm.status,
        permissions: [...options.staffForm.permissions],
      });

      message.success(
        options.staffDrawerMode.value === 'edit'
          ? '员工信息已更新'
          : '员工已添加',
      );
      options.isStaffDrawerOpen.value = false;
      resetStaffForm();
      await options.reloadStoreData();
    } catch (error) {
      console.error(error);
    } finally {
      options.isStaffSaving.value = false;
    }
  }

  /** 删除员工。 */
  async function handleDeleteStaff(staff: StoreStaffDto) {
    if (!options.selectedStoreId.value) return;

    options.deletingStaffId.value = staff.id;
    try {
      await deleteStoreStaffApi({
        storeId: options.selectedStoreId.value,
        staffId: staff.id,
      });
      message.success('员工已删除');
      await options.reloadStoreData();
    } catch (error) {
      console.error(error);
    } finally {
      options.deletingStaffId.value = '';
    }
  }

  return {
    handleDeleteStaff,
    handleSubmitStaff,
    openStaffDrawer,
    resetStaffForm,
    setStaffEmail,
    setStaffName,
    setStaffPermissions,
    setStaffPhone,
    setStaffRoleType,
    setStaffStatus,
  };
}
