import request from '@/utils/request'
import { getToken, removeToken, removeApiToken, getCurrentUserNameSync } from '@/utils/auth';
import { constant } from '@/utils/constant';
// #ifdef APP-ANDROID
import {selectTableData, insertTableData} from '@/utils/sqlite'
// #endif


export function offlineData(data:UTSJSONObject):Promise<UTSJSONObject> {
	return new Promise((resolve, reject) => {	
		let result = JSON.parseObject(JSON.stringify(data)) as UTSJSONObject
		let ret = {} as UTSJSONObject
		ret['errMsg']= 'ok'
		ret['data'] = [result]
		resolve(ret)
	});	
}

// 登录方法
export function login(username:string, password:string, code:string, uuid:string):Promise<UTSJSONObject> {
  const data = {
    username,
    password,
    code,
    uuid
  } as UTSJSONObject
  
  let data2 = {
    username: "admin",
    password: "admin123",
    code: "",
    uuid: '1',
  	token: '123456',
	roles:['admin']
  } as UTSJSONObject
  
    // #ifdef APP-ANDROID
    const result = selectTableData('app_user', 'username', username, 'password', password);
    console.log(result);
	return result;
	// #endif
   
  // #ifdef H5
   return offlineData(data2)
  // #endif
  
  
  /*
  return request({
    'url': '/login',
    headers: {
      isToken: false
    },
    'method': 'post',
    'data': data
  })*/ 
}
export type RegForm={
			username: string,
			name: string,
			password: string,
			token: string,
			confirmPassword: string,
			code: string,
			uuid: string
}
// 注册方法
export function register(data:RegForm):Promise<UTSJSONObject> {
  /*	
  return request({
    url: '/register',
    headers: {
      isToken: false
    },
    method: 'post',
    data
  }) */
  // #ifdef APP-ANDROID
	let condition = 'username,name,password,role,status,createtime,updatetime'
	let date = "strftime('%Y-%m-%d %H:%M:%S', 'now', 'localtime')"
	let dataStr = `'${data.username}','${data.name}','${data.password}','user',1, ${date}, ${date}`;  
	console.log(dataStr)
	const result = insertTableData('app_user', dataStr, condition);
	console.log(result);
	return result;
  // #endif
  
  // #ifdef H5
   return offlineData(data)
  // #endif  
}

// 获取用户详细信息
export function getInfo():Promise<UTSJSONObject> {
  /*	
  return request({
    'url': '/getInfo',
    'method': 'get'
  })*/
  let data = {
    username: "admin",
	name: "管理员"
    password: "admin123",
    code: "",
    uuid: '1',
	token: '123456', 
	roles:[] as string[]
  } as UTSJSONObject
      
	// #ifdef APP-ANDROID
	console.log('getCurrentUserNameSync', getCurrentUserNameSync())
	const result = selectTableData('app_user', 'username', getCurrentUserNameSync(), null, null);
	console.log(result);
	return result;
  // #endif
  // #ifdef H5  
  return offlineData(data)
  // #endif
}

// 退出方法
export function logout():Promise<UTSJSONObject> {
  return new Promise((resolve, reject) => {
    try {
      // 移除用户token
      removeToken();
      removeApiToken();
      
      // 清除用户相关信息
      uni.removeStorageSync(constant.name);
      uni.removeStorageSync(constant.username);
      uni.removeStorageSync(constant.roles);
      uni.removeStorageSync(constant.permissions);
      uni.removeStorageSync(constant.avatar);
      
      // 直接返回成功，因为本地已经清理了用户数据
      resolve({ code: 200, message: '退出成功' });
    } catch (error) {
      console.error('退出登录时发生错误:', error);
      reject({ code: 500, message: '退出失败' });
    }
  });
}

// 获取验证码
export function getCodeImg():Promise<UTSJSONObject> {
  return request({
    'url': '/captchaImage',
    headers: {
      isToken: false
    },
    method: 'get',
    timeout: 20000
  })
}
