/**
 * 通用函数
 */
var config = require('./config.js');

/**
 * 时间戳转为 xxxx-xx-xx xx:xx:xx 格式
 */

function scanOCRText(imageData) {
    return new Promise((resolve, reject) => {
        var apiKey = 'OLfS8e2NvaU84kLfx5XgFPf1';
        var secKey = 'x9IKrn6GRTPRfAqnPXn9FivbCWsd9okg';
        var tokenUrl = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${apiKey}&client_secret=${secKey}`;
        uni.request({
            url: tokenUrl,
            method: 'POST',
            dataType: 'json',
            header: {
                'content-type': 'application/json; charset-UTF-8'
            },
            success: function (res) {
				//六位数
                // scanImageInfo(imageData, res.data.access_token).then((words) => {
                //     console.log('words', words);
                //     resolve(words);
                // });
				//可多位数
				scanlicensePlate(imageData, res.data.access_token).then((words) => {
				    console.log('words', words);
				    resolve(words);
				});
            },
            fail: function (res) {
                console.log('[BaiduToken获取失败]', res);
            }
        });
    });
}
function scanImageInfo(imageData, token) {
    // 这里的imageData是图片转换成base64格式的数据
    const detectUrl = `https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=${token}`; // baiduToken是已经获取的access_Token
    return new Promise(function (resolve, reject) {
        uni.request({
            url: detectUrl,
            data: {
                image: imageData
            },
            method: 'POST',
            dataType: 'json',
            header: {
                'content-type': 'application/x-www-form-urlencoded' // 必须的
            },

            success: function (res) {
                console.log(res);
                var words_result = res.data.words_result;
                console.log(words_result);
                var words = '';
                var wordMax = 0;
                var indexMax = -1;
				for (var i = 0; words_result.length > i; i++) {
					if (words_result[i].words.length > wordMax && filtrationNum(words_result[i].words)) {
						wordMax = words_result[i].words.length;
						indexMax = i;
					}
				}
				if (indexMax != -1) {
					words = words_result[indexMax].words;
				}
				resolve(words);
            },
            fail: function (res, reject) {
                console.log('get word fail：', res.data);
            }
        });
    });
}

function scanlicensePlate(imageData, token) {
	// 这里的imageData是图片转换成base64格式的数据
	const detectUrl =
		`https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=${token}`; // baiduToken是已经获取的access_Token
	return new Promise(function(resolve, reject) {
		uni.request({
			url: detectUrl,
			data: {
				image: imageData
			},
			method: 'POST',
			dataType: 'json',
			header: {
				'content-type': 'application/x-www-form-urlencoded' // 必须的
			},
			success: function(res) {
				var words_result = res.data.words_result;
				var licensePlate = '';
				var licensePlatePrefix = '';
				var wordMax = 0;
				var indexMax = -1;
				for (var i = 0; words_result.length > i; i++) {
					if (words_result[i].words.length > wordMax && filtrationNum(words_result[i]
							.words)&&words_result[i].words.length < 11) {
						wordMax = words_result[i].words.length;
						indexMax = i;
					}
				}
				if (indexMax != -1) {
					licensePlate = words_result[indexMax].words;
				}

				if (indexMax != 0 && indexMax != -1) {
					licensePlatePrefix = words_result[indexMax - 1].words;
					licensePlatePrefix = licensePlatePrefix.replaceAll("。", ".");
				}
				resolve({
					licensePlatePrefix: licensePlatePrefix,
					licensePlate: licensePlate
				});
			},
			fail: function(res, reject) {
				console.log('get word fail：', res.data);
			}
		});
	});
}

function filtrationNum(data) {
    var reg = /^[\da-z]+$/i;
    if (reg.test(data)) {
        return true;
    } else {
        return false;
    }
}
module.exports = {
    scanOCRText: scanOCRText,
	scanlicensePlate: scanlicensePlate
};
