import { User, LoginRecord, Enterprise } from '../types/auth';
import { formatDateTime as safeDateFormat, safeNow, getTime } from './safeDate';

// LocalStorage keys
const STORAGE_KEYS = {
  TOKEN: 'auth_token',
  REFRESH_TOKEN: 'refresh_token',
  USER: 'user_info',
  LOGIN_TIME: 'login_time',
  SESSION_ID: 'session_id',
} as const;

// 延迟初始化的Mock数据 - 避免模块加载时的构造函数错误
let _mockEnterprises: Enterprise[] | null = null;
let _mockUsers: User[] | null = null;
let _loginRecords: LoginRecord[] | null = null;
let _mockPasswords: { [username: string]: string } | null = null;

// 格式化日期时间（使用安全的工具函数）
const formatDateTime = (): string => {
  return safeDateFormat();
};

// 获取Mock企业数据库
const getMockEnterprises = (): Enterprise[] => {
  if (_mockEnterprises === null) {
    _mockEnterprises = [
      {
        id: 'ent-1',
        name: '绿野农业科技有限公司',
        code: 'LYNY001',
        type: '种植企业',
        status: 'active',
        auditStatus: 'approved',
        address: '江苏省南京市江宁区农业科技园区',
        contact: '李经理',
        phone: '025-12345678',
        createdAt: '2023-01-01 10:00:00',
      },
      {
        id: 'ent-2',
        name: '丰收农场管理集团',
        code: 'FSNC002',
        type: '综合农场',
        status: 'active',
        auditStatus: 'approved',
        address: '山东省济南市章丘区现代农业示范区',
        contact: '王总',
        phone: '0531-87654321',
        createdAt: '2023-03-15 14:00:00',
      },
      {
        id: 'ent-3',
        name: '智慧农业示范基地',
        code: 'ZHNY003',
        type: '示范基地',
        status: 'active',
        auditStatus: 'pending',
        address: '浙江省杭州市萧山区智慧农业园',
        contact: '陈主任',
        phone: '0571-23456789',
        createdAt: '2023-06-01 09:00:00',
      },
      {
        id: 'ent-4',
        name: '现代农业合作社',
        code: 'XDNY004',
        type: '合作社',
        status: 'active',
        auditStatus: 'not_submitted',
        address: '河南省郑州市中牟县农业园区',
        contact: '赵理事长',
        phone: '0371-34567890',
        createdAt: '2023-08-20 11:00:00',
      },
      {
        id: 'ent-5',
        name: '优质粮食生产基地',
        code: 'YZLS005',
        type: '粮食基地',
        status: 'active',
        auditStatus: 'rejected',
        address: '黑龙江省哈尔滨市五常市',
        contact: '孙场长',
        phone: '0451-45678901',
        createdAt: '2023-10-10 08:00:00',
      },
    ];
  }
  return _mockEnterprises;
};

// 获取Mock用户数据库
const getMockUsers = (): User[] => {
  if (_mockUsers === null) {
    _mockUsers = [
      {
        id: 'user-1',
        username: 'admin',
        phone: '13800138000',
        email: 'admin@agriculture.com',
        realName: '系统管理员',
        role: 'admin',
        permissions: ['*'],
        avatar: '',
        department: '技术部',
        enterpriseId: 'ent-1',
        enterpriseName: '绿野农业科技有限公司',
        createdAt: '2024-01-01 10:00:00',
        lastLoginTime: '2024-10-15 09:30:00',
        lastLoginIp: '192.168.1.100',
        lastLoginDevice: 'Windows PC - Chrome',
      },
      {
        id: 'user-2',
        username: 'zhangsan',
        phone: '13800138001',
        email: 'zhangsan@agriculture.com',
        realName: '张三',
        role: 'manager',
        permissions: ['machinery:*', 'field:*', 'operation:*'],
        avatar: '',
        department: '运营部',
        enterpriseId: 'ent-1',
        enterpriseName: '绿野农业科技有限公司',
        createdAt: '2024-01-15 14:00:00',
        lastLoginTime: '2024-10-14 16:20:00',
        lastLoginIp: '192.168.1.101',
        lastLoginDevice: 'iPhone 14 - Safari',
      },
    ];
  }
  return _mockUsers;
};

// 获取登录记录
const getLoginRecords = (): LoginRecord[] => {
  if (_loginRecords === null) {
    _loginRecords = [
      {
        id: 'log-1',
        userId: 'user-1',
        username: 'admin',
        loginTime: '2024-10-15 09:30:00',
        loginIp: '192.168.1.100',
        loginDevice: 'Windows PC',
        browser: 'Chrome 118',
        os: 'Windows 10',
        loginType: 'password',
        status: 'success',
      },
      {
        id: 'log-2',
        userId: 'user-2',
        username: 'zhangsan',
        loginTime: '2024-10-14 16:20:00',
        loginIp: '192.168.1.101',
        loginDevice: 'iPhone 14',
        browser: 'Safari 17',
        os: 'iOS 17',
        loginType: 'phone',
        status: 'success',
      },
    ];
  }
  return _loginRecords;
};

// 获取Mock密码库
const getMockPasswords = (): { [username: string]: string } => {
  if (_mockPasswords === null) {
    _mockPasswords = {
      admin: 'admin123',
      zhangsan: 'zhang123',
    };
  }
  return _mockPasswords;
};

// 生成随机token
export const generateToken = (): string => {
  try {
    const random = Math.random().toString(36).substring(2);
    const timestamp = safeNow().toString(36);
    return 'token_' + random + timestamp;
  } catch (e) {
    console.warn('Token generation error:', e);
    return 'token_' + Math.random().toString(36).substring(2) + Math.random().toString(36).substring(2);
  }
};

// 生成session ID
export const generateSessionId = (): string => {
  try {
    const random = Math.random().toString(36).substring(2);
    const timestamp = safeNow().toString(36);
    return 'session_' + random + timestamp;
  } catch (e) {
    console.warn('Session ID generation error:', e);
    return 'session_' + Math.random().toString(36).substring(2) + Math.random().toString(36).substring(2);
  }
};

// 获取设备信息
export const getDeviceInfo = (): { device: string; browser: string; os: string } => {
  try {
    if (typeof window === 'undefined' || typeof navigator === 'undefined') {
      return { device: 'Desktop PC', browser: 'Chrome', os: 'Windows' };
    }
    
    const ua = navigator.userAgent || '';
    
    let device = 'Desktop PC';
    let browser = 'Chrome';
    let os = 'Windows';
    
    if (ua.indexOf('Win') !== -1) os = 'Windows';
    else if (ua.indexOf('Mac') !== -1) os = 'macOS';
    else if (ua.indexOf('Linux') !== -1) os = 'Linux';
    else if (ua.indexOf('Android') !== -1) os = 'Android';
    else if (ua.indexOf('iOS') !== -1 || ua.indexOf('iPhone') !== -1) os = 'iOS';
    
    if (ua.indexOf('Chrome') !== -1) browser = 'Chrome';
    else if (ua.indexOf('Safari') !== -1) browser = 'Safari';
    else if (ua.indexOf('Firefox') !== -1) browser = 'Firefox';
    else if (ua.indexOf('Edge') !== -1) browser = 'Edge';
    
    if (ua.indexOf('Mobile') !== -1) device = 'Mobile Device';
    else if (ua.indexOf('Tablet') !== -1) device = 'Tablet';
    else device = 'Desktop PC';
    
    return { device, browser, os };
  } catch (e) {
    return { device: 'Desktop PC', browser: 'Chrome', os: 'Windows' };
  }
};

// 获取客户端IP（模拟）
export const getClientIp = (): string => {
  return '192.168.1.' + Math.floor(Math.random() * 255);
};

// 保存token
export const saveToken = (token: string, refreshToken: string) => {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return;
    
    const timestamp = String(safeNow());
    
    localStorage.setItem(STORAGE_KEYS.TOKEN, token);
    localStorage.setItem(STORAGE_KEYS.REFRESH_TOKEN, refreshToken);
    localStorage.setItem(STORAGE_KEYS.LOGIN_TIME, timestamp);
    localStorage.setItem(STORAGE_KEYS.SESSION_ID, generateSessionId());
  } catch (e) {
    console.error('Failed to save token:', e);
  }
};

// 获取token
export const getToken = (): string | null => {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return null;
    return localStorage.getItem(STORAGE_KEYS.TOKEN);
  } catch (e) {
    return null;
  }
};

// 获取刷新token
export const getRefreshToken = (): string | null => {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return null;
    return localStorage.getItem(STORAGE_KEYS.REFRESH_TOKEN);
  } catch (e) {
    return null;
  }
};

// 保存用户信息
export const saveUser = (user: User) => {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return;
    localStorage.setItem(STORAGE_KEYS.USER, JSON.stringify(user));
  } catch (e) {
    console.error('Failed to save user:', e);
  }
};

// 获取用户信息
export const getUser = (): User | null => {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return null;
    const userStr = localStorage.getItem(STORAGE_KEYS.USER);
    if (!userStr) return null;
    return JSON.parse(userStr);
  } catch (e) {
    return null;
  }
};

// 清除认证信息
export const clearAuth = () => {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return;
    localStorage.removeItem(STORAGE_KEYS.TOKEN);
    localStorage.removeItem(STORAGE_KEYS.REFRESH_TOKEN);
    localStorage.removeItem(STORAGE_KEYS.USER);
    localStorage.removeItem(STORAGE_KEYS.LOGIN_TIME);
    localStorage.removeItem(STORAGE_KEYS.SESSION_ID);
  } catch (e) {
    console.error('Failed to clear auth:', e);
  }
};

// 检查token是否过期（模拟）
export const isTokenExpired = (): boolean => {
  try {
    if (typeof window === 'undefined' || !window.localStorage) return true;
    
    const loginTimeStr = localStorage.getItem(STORAGE_KEYS.LOGIN_TIME);
    if (!loginTimeStr) return true;
    
    const loginTime = parseInt(loginTimeStr, 10);
    if (isNaN(loginTime)) return true;
    
    const now = safeNow();
    const hoursPassed = (now - loginTime) / (1000 * 60 * 60);
    
    return hoursPassed >= 24;
  } catch (e) {
    console.warn('Token expiry check error:', e);
    return true;
  }
};

// 刷新token（模拟）
export const refreshAuthToken = async (): Promise<{ token: string; refreshToken: string } | null> => {
  try {
    const refreshToken = getRefreshToken();
    if (!refreshToken) return null;
    
    await new Promise(resolve => setTimeout(resolve, 500));
    
    const newToken = generateToken();
    const newRefreshToken = generateToken();
    
    saveToken(newToken, newRefreshToken);
    
    return { token: newToken, refreshToken: newRefreshToken };
  } catch (e) {
    return null;
  }
};

// 验证密码登录
export const validatePasswordLogin = async (
  username: string,
  password: string,
  captcha: string
): Promise<{ success: boolean; message: string; user?: User }> => {
  try {
    await new Promise(resolve => setTimeout(resolve, 800));
    
    if (captcha !== 'AUTO' && (!captcha || captcha.length < 4)) {
      return { success: false, message: '请输入图形验证码' };
    }
    
    const mockUsers = getMockUsers();
    const user = mockUsers.find(u => u.username === username);
    if (!user) {
      return { success: false, message: '用户名或密码错误' };
    }
    
    const mockPasswords = getMockPasswords();
    const storedPassword = mockPasswords[username];
    if (password !== storedPassword) {
      return { success: false, message: '用户名或密码错误' };
    }
    
    const deviceInfo = getDeviceInfo();
    const loginIp = getClientIp();
    const loginTime = formatDateTime();
    
    user.lastLoginTime = loginTime;
    user.lastLoginIp = loginIp;
    user.lastLoginDevice = `${deviceInfo.device} - ${deviceInfo.browser}`;
    
    const loginRecord: LoginRecord = {
      id: 'log-' + safeNow(),
      userId: user.id,
      username: user.username,
      loginTime,
      loginIp,
      loginDevice: deviceInfo.device,
      browser: deviceInfo.browser,
      os: deviceInfo.os,
      loginType: 'password',
      status: 'success',
    };
    const records = getLoginRecords();
    records.unshift(loginRecord);
    
    return { success: true, message: '登录成功', user };
  } catch (e) {
    return { success: false, message: '登录失败，请重试' };
  }
};

// 验证手机号登录
export const validatePhoneLogin = async (
  phone: string,
  code: string,
  captcha: string
): Promise<{ success: boolean; message: string; user?: User }> => {
  try {
    await new Promise(resolve => setTimeout(resolve, 800));
    
    if (!captcha || captcha.length < 4) {
      return { success: false, message: '请输入图形验证码' };
    }
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return { success: false, message: '请输入正确的手机号' };
    }
    
    if (code !== '123456') {
      return { success: false, message: '验证码错误' };
    }
    
    const mockUsers = getMockUsers();
    const user = mockUsers.find(u => u.phone === phone);
    if (!user) {
      return { success: false, message: '该手机号未注册' };
    }
    
    const deviceInfo = getDeviceInfo();
    const loginIp = getClientIp();
    const loginTime = formatDateTime();
    
    user.lastLoginTime = loginTime;
    user.lastLoginIp = loginIp;
    user.lastLoginDevice = `${deviceInfo.device} - ${deviceInfo.browser}`;
    
    const loginRecord: LoginRecord = {
      id: 'log-' + safeNow(),
      userId: user.id,
      username: user.username,
      loginTime,
      loginIp,
      loginDevice: deviceInfo.device,
      browser: deviceInfo.browser,
      os: deviceInfo.os,
      loginType: 'phone',
      status: 'success',
    };
    const records = getLoginRecords();
    records.unshift(loginRecord);
    
    return { success: true, message: '登录成功', user };
  } catch (e) {
    return { success: false, message: '登录失败，请重试' };
  }
};

// 用户注册
export const registerUser = async (
  registerForm: {
    username: string;
    password: string;
    phone: string;
    code: string;
    realName: string;
    email?: string;
    enterpriseId: string;
    captcha: string;
  }
): Promise<{ success: boolean; message: string; user?: User }> => {
  try {
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    const { username, password, phone, code, realName, email, enterpriseId, captcha } = registerForm;
    
    if (!captcha || captcha.length < 4) {
      return { success: false, message: '请输入图形验证码' };
    }
    
    if (code !== '123456') {
      return { success: false, message: '手机验证码错误' };
    }
    
    if (!enterpriseId) {
      return { success: false, message: '请选择所属企业' };
    }
    
    const mockEnterprises = getMockEnterprises();
    const enterprise = mockEnterprises.find(e => e.id === enterpriseId);
    if (!enterprise) {
      return { success: false, message: '所选企业不存在' };
    }
    
    if (enterprise.status !== 'active') {
      return { success: false, message: '该企业已停用，无法注册' };
    }
    
    const mockUsers = getMockUsers();
    if (mockUsers.some(u => u.username === username)) {
      return { success: false, message: '用户名已存在' };
    }
    
    if (mockUsers.some(u => u.phone === phone)) {
      return { success: false, message: '该手机号已注册' };
    }
    
    if (password.length < 6) {
      return { success: false, message: '密码长度不能少于6位' };
    }
    
    const newUser: User = {
      id: 'user-' + safeNow(),
      username,
      phone,
      email,
      realName,
      role: 'user',
      permissions: ['machinery:view', 'field:view', 'operation:view'],
      avatar: '',
      department: '待分配',
      enterpriseId,
      enterpriseName: enterprise.name,
      createdAt: formatDateTime(),
    };
    
    mockUsers.push(newUser);
    const mockPasswords = getMockPasswords();
    mockPasswords[username] = password;
    
    return { success: true, message: '注册成功', user: newUser };
  } catch (e) {
    return { success: false, message: '注册失败，请重试' };
  }
};

// 发送短信验证码（模拟）
export const sendSmsCode = async (phone: string): Promise<{ success: boolean; message: string }> => {
  try {
    await new Promise(resolve => setTimeout(resolve, 500));
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      return { success: false, message: '请输入正确的手机号' };
    }
    
    console.log(`验证码已发送到手机：${phone}，验证码：123456（仅测试使用）`);
    
    return { success: true, message: '验证码已发送，请注意查收' };
  } catch (e) {
    return { success: false, message: '发送失败，请重试' };
  }
};

// 导出登录记录（用于外部访问）
export { getLoginRecords };

// 导出所有用户（仅用于开发调试）
export const getAllUsers = (): User[] => {
  return getMockUsers();
};

// 获取所有企业列表
export const getAllEnterprises = (): Enterprise[] => {
  const enterprises = getMockEnterprises();
  return enterprises.filter(e => e.status === 'active');
};

// 根据ID获取企业信息
export const getEnterpriseById = (id: string): Enterprise | undefined => {
  const enterprises = getMockEnterprises();
  return enterprises.find(e => e.id === id);
};
