import type { VbenFormProps } from '#/adapter/form';

import { useUserStore } from '@vben/stores';

import { z } from '#/adapter/form';
import { getDeliveryWarehouseOption } from '#/views/system/delivery-warehouse/api';
import { getSupplierOption } from '#/views/system/supplier/api';

import type { AdminFormType } from './role-meta';
import { ROLE_CITY_MANAGER, ROLE_SALESPERSON } from './role-meta';

const defaultPassword = 'Xk123456@';
const defaultAvatar =
  'https://xiaokang88.oss-cn-hangzhou.aliyuncs.com/xk_upload_20251022/20251022104156946505ca86d97626c08882f31797dbcef49c.png';

function passwordFields() {
  return [
    {
      fieldName: 'password',
      label: '密码',
      component: 'InputPassword',
      help: '5-18位数字、字母、特殊字符组成。',
      componentProps: {
        placeholder: '请输入密码',
        allowClear: true,
      },
      defaultValue: defaultPassword,
      rules: z
        .string()
        .regex(
          /^(?=.*[A-Z0-9])(?=.*[!@#$%^&*])[A-Z0-9!@#$%^&*]{5,18}$/i,
          '密码由5-18位数字、字母、特殊字符组成。',
        ),
      dependencies: {
        if({ id }: { id?: number }) {
          return !id;
        },
        triggerFields: ['id'],
      },
      formItemClass: 'col-span-6',
    },
    {
      fieldName: 'confirmPassword',
      label: '确认密码',
      component: 'InputPassword',
      componentProps: {
        placeholder: '请输入确认密码',
        allowClear: true,
      },
      defaultValue: defaultPassword,
      rules: z
        .string()
        .regex(/[\w!@#$%^&*]{5,18}/, '密码由5-18位数字、字母、特殊字符组成。'),
      dependencies: {
        if({ id }: { id?: number }) {
          return !id;
        },
        triggerFields: ['id', 'confirmPassword'],
        rules: (values: { password?: string }) => {
          return z
            .string()
            .regex(
              /[\w!@#$%^&*]{5,18}/,
              '密码由5-18位数字、字母、特殊字符组成。',
            )
            .refine(
              (confirmPassword) => confirmPassword === values.password,
              { message: '确认密码必须与密码一致' },
            );
        },
      },
      formItemClass: 'col-span-6',
    },
  ];
}

function shouldShowAddress(roleId: number, formType: AdminFormType): boolean {
  if (formType !== 'address') {
    return false;
  }
  const userStore = useUserStore();
  const currentRoleId = (userStore.userInfo as { roles?: { id?: number } })
    ?.roles?.id;
  if (
    roleId === ROLE_SALESPERSON &&
    currentRoleId === ROLE_CITY_MANAGER
  ) {
    return false;
  }
  return true;
}

export function createAdminModalFormProps(
  roleId: number,
  formType: AdminFormType,
): VbenFormProps {
  const schema: VbenFormProps['schema'] = [
    {
      component: 'VbenInput',
      fieldName: 'id',
      label: 'ID',
      formItemClass: 'col-span-6',
      dependencies: {
        show: false,
        triggerFields: ['id'],
      },
    },
    {
      component: 'VbenInput',
      fieldName: 'role_id',
      label: '角色ID',
      defaultValue: roleId,
      dependencies: {
        show: false,
        triggerFields: ['role_id'],
      },
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入管理员昵称',
      },
      fieldName: 'nick_name',
      label: '昵称',
      rules: 'required',
      formItemClass: 'col-span-6',
    },
    {
      component: 'Avatar',
      fieldName: 'avatar',
      label: '头像',
      rules: 'required',
      formItemClass: 'col-span-6',
      defaultValue: defaultAvatar,
    },
    {
      component: 'VbenInput',
      componentProps: {
        placeholder: '请输入管理员手机号码',
      },
      fieldName: 'phone',
      label: '手机号',
      // 与后端 checkPhone 一致：必填 + 大陆 11 位号段
      rules: 'mobile',
      formItemClass: 'col-span-6',
    },
  ];

  if (shouldShowAddress(roleId, formType)) {
    schema.push({
      component: 'RegionAddressPicker',
      fieldName: 'address',
      label: '省市区',
      rules: 'required',
      formItemClass: 'col-span-12',
    });
  }

  if (formType === 'supplier') {
    schema.push({
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        afterFetch: (data: { id: number; name: string }[]) => {
          return data.map((item) => ({
            label: item.name,
            value: item.id,
          }));
        },
        api: getSupplierOption,
        placeholder: '请选择',
      },
      fieldName: 'supplier_id',
      formItemClass: 'col-span-6',
      label: '所属供应商',
      rules: 'required',
    });
  }

  if (formType === 'deliveryWarehouse') {
    schema.push({
      component: 'ApiSelect',
      componentProps: {
        allowClear: true,
        filterOption: true,
        showSearch: true,
        afterFetch: (data: { id: number; name: string }[]) => {
          return data.map((item) => ({
            label: item.name,
            value: item.id,
          }));
        },
        api: getDeliveryWarehouseOption,
        placeholder: '请选择',
      },
      fieldName: 'delivery_warehouse_id',
      formItemClass: 'col-span-6',
      label: '所属配送仓库',
      rules: 'required',
    });
  }

  if (formType === 'clinic' || formType === 'doctor' || formType === 'pharmacist') {
    schema.push({
      component: 'StorePicker',
      fieldName: 'store_id',
      formItemClass: 'col-span-6',
      label: '所属诊所',
      rules: 'required',
    });
  }

  if (formType === 'doctor') {
    schema.push({
      component: 'DoctorPicker',
      componentProps: (values: { store_id?: number }) => ({
        storeId: values.store_id,
      }),
      dependencies: {
        triggerFields: ['store_id'],
        componentProps: (values: { store_id?: number }) => ({
          storeId: values.store_id,
        }),
      },
      fieldName: 'doctor_id',
      label: '关联医生',
      formItemClass: 'col-span-6',
    });
  }

  if (formType === 'pharmacist') {
    schema.push({
      component: 'VbenInput',
      componentProps: {
        placeholder: '关联药师档案 ID（可选）',
      },
      fieldName: 'pharmacist_id',
      label: '药师ID',
      formItemClass: 'col-span-6',
    });
  }

  schema.push(...passwordFields());

  return {
    wrapperClass: 'grid-cols-12',
    commonConfig: {
      formItemClass: 'col-span-12',
      componentProps: {
        class: 'w-full',
      },
    },
    layout: 'horizontal',
    schema,
    showDefaultActions: false,
  };
}
