/**
 * 签到功能工具函数
 */

import type { CheckinRecord, CheckinType, LocationInfo, CheckinPhoto } from '@/api/checkin';
import { getUserInfo } from './auth';

const OFFLINE_CHECKIN_KEY = 'offline_checkin_records';
const MAX_OFFLINE_RECORDS = 50;

export interface WatermarkConfig {
  time: string;
  location: string;
  userName: string;
  userNo: string;
  checkinType: string;
}

export function getCurrentLocation(): Promise<LocationInfo> {
  return new Promise((resolve, reject) => {
    uni.getLocation({
      type: 'gcj02',
      geocode: true,
      success: (res) => {
        resolve({
          latitude: res.latitude,
          longitude: res.longitude,
          address: res.address 
            ? `${res.address.province || ''}${res.address.city || ''}${res.address.district || ''}${res.address.street || ''}${res.address.streetNum || ''}`
            : '未知位置',
          accuracy: res.accuracy || 0
        });
      },
      fail: (err) => {
        console.error('获取位置失败', err);
        reject(new Error('获取位置失败，请检查定位权限'));
      }
    });
  });
}

export function formatWatermarkTime(date: Date = new Date()): string {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

export function formatWatermarkLocation(location: LocationInfo): string {
  return `${location.latitude.toFixed(6)}, ${location.longitude.toFixed(6)}\n${location.address}`;
}

export function getCheckinTypeName(type: CheckinType): string {
  const typeMap: Record<CheckinType, string> = {
    [CheckinType.INVENTORY_TALLY]: '理货盘点',
    [CheckinType.DELIVERY_REPLENISH]: '补货确认'
  };
  return typeMap[type] || '未知类型';
}

export function createWatermarkConfig(
  type: CheckinType,
  location: LocationInfo
): WatermarkConfig {
  const userInfo = getUserInfo() || { nickname: '未知用户', userNo: 'N/A' };
  
  return {
    time: formatWatermarkTime(),
    location: formatWatermarkLocation(location),
    userName: userInfo.nickname || userInfo.username || '未知用户',
    userNo: userInfo.userNo || 'N/A',
    checkinType: getCheckinTypeName(type)
  };
}

export function drawWatermarkOnCanvas(
  canvasContext: UniApp.CanvasContext,
  imagePath: string,
  config: WatermarkConfig,
  canvasWidth: number,
  canvasHeight: number
): Promise<string> {
  return new Promise((resolve, reject) => {
    canvasContext.drawImage(imagePath, 0, 0, canvasWidth, canvasHeight);
    
    const padding = 20;
    const lineHeight = 24;
    const startY = canvasHeight - padding - lineHeight * 5;
    
    canvasContext.setGlobalAlpha(0.7);
    canvasContext.setFillStyle('#000000');
    canvasContext.fillRect(
      padding - 10,
      startY - 10,
      canvasWidth - padding * 2 + 20,
      lineHeight * 5 + 20
    );
    
    canvasContext.setGlobalAlpha(1);
    canvasContext.setFillStyle('#ffffff');
    canvasContext.setFontSize(14);
    
    const lines = [
      `时间: ${config.time}`,
      `位置: ${config.location.split('\n')[0]}`,
      `地址: ${config.location.split('\n')[1] || ''}`,
      `人员: ${config.userName} (${config.userNo})`,
      `类型: ${config.checkinType}`
    ];
    
    lines.forEach((line, index) => {
      canvasContext.fillText(line, padding, startY + lineHeight * (index + 1));
    });
    
    canvasContext.draw(false, () => {
      uni.canvasToTempFilePath({
        canvasId: 'watermarkCanvas',
        success: (res) => {
          resolve(res.tempFilePath);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  });
}

export function takePhotoWithWatermark(
  type: CheckinType,
  location: LocationInfo
): Promise<CheckinPhoto> {
  return new Promise((resolve, reject) => {
    const config = createWatermarkConfig(type, location);
    
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0];
        
        const photo: CheckinPhoto = {
          id: `photo_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
          path: tempFilePath,
          watermarkPath: tempFilePath,
          timestamp: Date.now(),
          location: { ...location }
        };
        
        resolve(photo);
      },
      fail: (err) => {
        reject(new Error('拍照失败'));
      }
    });
  });
}

export function saveOfflineCheckin(record: CheckinRecord): void {
  try {
    const records = getOfflineCheckins();
    records.unshift(record);
    
    if (records.length > MAX_OFFLINE_RECORDS) {
      records.splice(MAX_OFFLINE_RECORDS);
    }
    
    uni.setStorageSync(OFFLINE_CHECKIN_KEY, JSON.stringify(records));
  } catch (error) {
    console.error('保存离线签到记录失败', error);
  }
}

export function getOfflineCheckins(): CheckinRecord[] {
  try {
    const data = uni.getStorageSync(OFFLINE_CHECKIN_KEY);
    return data ? JSON.parse(data) : [];
  } catch (error) {
    console.error('读取离线签到记录失败', error);
    return [];
  }
}

export function removeOfflineCheckin(offlineId: string): void {
  try {
    const records = getOfflineCheckins();
    const index = records.findIndex(r => r.offlineId === offlineId || r.id === offlineId);
    if (index > -1) {
      records.splice(index, 1);
      uni.setStorageSync(OFFLINE_CHECKIN_KEY, JSON.stringify(records));
    }
  } catch (error) {
    console.error('删除离线签到记录失败', error);
  }
}

export function updateOfflineCheckinStatus(offlineId: string, status: 'synced' | 'failed'): void {
  try {
    const records = getOfflineCheckins();
    const record = records.find(r => r.offlineId === offlineId || r.id === offlineId);
    if (record) {
      record.status = status;
      if (status === 'synced') {
        record.syncedAt = new Date().toISOString();
      }
      uni.setStorageSync(OFFLINE_CHECKIN_KEY, JSON.stringify(records));
    }
  } catch (error) {
    console.error('更新离线签到状态失败', error);
  }
}

export function generateOfflineId(): string {
  return `offline_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
}

export function isOnline(): boolean {
  const networkInfo = uni.getNetworkType && uni.getNetworkType();
  return true;
}

export function checkLocationPermission(): Promise<boolean> {
  return new Promise((resolve) => {
    // #ifdef MP-WEIXIN
    uni.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation'] === false) {
          uni.showModal({
            title: '定位权限',
            content: '需要获取您的位置信息用于签到，请在设置中开启',
            success: (modalRes) => {
              if (modalRes.confirm) {
                uni.openSetting();
              }
            }
          });
          resolve(false);
        } else {
          resolve(true);
        }
      },
      fail: () => {
        resolve(true);
      }
    });
    // #endif
    
    // #ifndef MP-WEIXIN
    resolve(true);
    // #endif
  });
}

export function checkCameraPermission(): Promise<boolean> {
  return new Promise((resolve) => {
    // #ifdef MP-WEIXIN
    uni.getSetting({
      success: (res) => {
        if (res.authSetting['scope.camera'] === false) {
          uni.showModal({
            title: '相机权限',
            content: '需要使用相机拍照签到，请在设置中开启',
            success: (modalRes) => {
              if (modalRes.confirm) {
                uni.openSetting();
              }
            }
          });
          resolve(false);
        } else {
          resolve(true);
        }
      },
      fail: () => {
        resolve(true);
      }
    });
    // #endif
    
    // #ifndef MP-WEIXIN
    resolve(true);
    // #endif
  });
}

export function validateCheckinPermission(type: CheckinType): boolean {
  const userInfo = getUserInfo();
  if (!userInfo) {
    return false;
  }
  
  const permissions = userInfo.permissions || [];
  
  if (type === CheckinType.INVENTORY_TALLY) {
    return permissions.includes('inventory:checkin') || permissions.includes('inventory:view');
  }
  
  if (type === CheckinType.DELIVERY_REPLENISH) {
    return permissions.includes('delivery:checkin') || permissions.includes('inventory:edit');
  }
  
  return true;
}

export function formatCheckinDuration(createdAt: string): string {
  const date = new Date(createdAt);
  const now = new Date();
  const diff = now.getTime() - date.getTime();
  
  const minutes = Math.floor(diff / (1000 * 60));
  const hours = Math.floor(diff / (1000 * 60 * 60));
  const days = Math.floor(diff / (1000 * 60 * 60 * 24));
  
  if (minutes < 1) {
    return '刚刚';
  } else if (minutes < 60) {
    return `${minutes}分钟前`;
  } else if (hours < 24) {
    return `${hours}小时前`;
  } else if (days < 7) {
    return `${days}天前`;
  } else {
    return createdAt.split(' ')[0];
  }
}
