import config from '@/config.js'
// 获取AccessToken
export function getAccessToken(callback) {
	uni.request({
		url: '/baiduApi/oauth/2.0/token',
		data: {
			grant_type: 'client_credentials',
			client_id: config.face_client_id,
			client_secret: config.face_client_secret
		},
		method: 'POST',
		header: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		success: (res) => {
			// res.data.access_token
			callback(res.data.access_token)
		}
	})
}

// 身份证识别
export function idcard(path, token, type, callback) {
	if (!type) type = 'front'
	uni.request({
		url: '/baiduApi/rest/2.0/ocr/v1/idcard',
		data: {
			image: path,
			access_token: token,
			id_card_side: type,
			detect_photo: true,
			detect_risk: true,
			detect_card: true,
			detect_ps:true,
		},
		timeout: 30000,
		method: 'POST',
		header: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		success: (res) => {
			callback(res.data)
		}
	})
}

// 对比
export function match(token, face1, face2, callback) {
	let data = [{
		image: face1,
		image_type: 'BASE64',
		liveness_control: 'NORMAL',
	}, {
		image: face2,
		image_type: 'BASE64'
	}]
	uni.request({
		url: '/baiduApi/rest/2.0/face/v3/match?access_token=' + token,
		data: data,
		method: 'POST',
		header: {
			'Content-Type': 'application/json'
		},
		success: (res) => {
			callback(res)
		},
		error: (err) => {
			console.log("对比失败,", err);
		}
	})
}

// 创建组
export function createGroup(token, groupId, callback) {
	uni.request({
		url: '/baiduApi/rest/2.0/face/v3/faceset/group/add?access_token=' + token,
		data: {
			group_id: groupId,
		},
		method: 'POST',
		header: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		success: (res) => {
			callback(res)
		},
		error: (err) => {
			console.log("创建组失败,", err);
		}
	})
}


// 人脸注册
export function faceAdd(token, face, groupId, user_id, callback) {
	// https://cloud.baidu.com/doc/FACE/s/Gk37c1uzc#%E4%BA%BA%E8%84%B8%E6%B3%A8%E5%86%8C
	let data = {
		image: face,
		image_type: 'BASE64',
		group_id: groupId,
		user_id: user_id,
		action_type: 'REPLACE', // 操作方式 APPEND: 当user_id在库中已经存在时，对此user_id重复注册时，新注册的图片默认会追加到该user_id下 REPLACE : 当对此user_id重复注册时,则会用新图替换库中该user_id下所有图片 默认使用APPEND
	}
	uni.request({
		url: '/baiduApi/rest/2.0/face/v3/faceset/user/add?access_token=' + token,
		data: data,
		method: 'POST',
		header: {
			'Content-Type': 'application/json'
		},
		success: (res) => {
			callback(res)
		},
		error: (err) => {
			console.log("人脸注册失败,", err);
		}
	})
}


// 人脸搜索
export function faceSearch(token, face, groupId, callback) {
	let data = {
		image: face,
		image_type: 'BASE64',
		group_id_list: groupId,
		match_threshold: config.score,
		max_user_num: 50
	}
	uni.request({
		url: '/baiduApi/rest/2.0/face/v3/search?access_token=' + token,
		data: data,
		method: 'POST',
		header: {
			'Content-Type': 'application/json'
		},
		success: (res) => {
			callback(res)
		},
		error: (err) => {
			console.log("人脸搜索失败,", err);
		}
	})
}