import http from './interface'
import {
	decrypt
} from '../utils/aes.js'

//解密脱敏字段集合 type(姓名 1、手机号 2、身份证 3)
const tmList = [
	{
		prop: 'card',
		type: 3
	},
	{
		prop: 'phone',
		type: 2
	},
	{
		prop: 'passengerName',
		type: 1
	},
	{
		prop: 'contactNum',
		type: 2
	},
	{
		prop: 'linkPerson',
		type: 1
	},
	{
		prop: 'linkPhone',
		type: 2
	},
	{
		prop: 'passName',
		type: 1
	},
	{
		prop: 'credentialNum',
		type: 3
	},
	{
		prop: 'phoneNum',
		type: 2
	},
	{
		prop: 'guestName',
		type: 1
	},
	{
		prop: 'guestPhone',
		type: 2
	},
	{
		prop: 'touristName',
		type: 1
	},
	{
		prop: 'touristCode',
		type: 3
	},
	{
		prop: 'touristPhone',
		type: 2
	},
	// {
	// 	prop: 'landlinePhone',
	// 	type: 2
	// },
	{
		prop: 'linkName',
		type: 1
	},
	{
		prop: 'linkMobile',
		type: 2
	},
	{
		prop: 'idCode',
		type: 3
	},
	{
		prop: 'complainantName',
		type: 1
	},
	{
		prop: 'complainantPhone',
		type: 2
	},
	{
		prop: 'idCard',
		type: 3
	},
	{
		prop: 'guestName',
		type: 1
	},
	{
		prop: 'guestPhone',
		type: 2
	},
	{
		prop: 'checkInName',
		type: 1
	},
	{
		prop: 'checkInPhone',
		type: 2
	},
	{
		prop: 'legalPerson',
		type: 1
	},
	{
		prop: 'operatorCard',
		type: 3
	}
];
// 不做脱敏处理的api集合(页面上需要编辑单独处理的)
const apiList = [
	'/api/commonPerson/list',
	'/scenic/api/order/scanCode',
	'/merchant/hotel/order/getOrderDetail',
	'/merchant/hotel/repast/getRepastOrderInfo',
	'/merchant/hotel/order/getMerchantOrderPageList',
	'/merchant/hotel/room/state/getRoomStateCount',
	'/api/merchant/food/merchant'
]
//解密脱敏处理
function dealJmTmData(data, isTm) {
	if (!data) return;
	let keys = Object.keys(data);
	keys.forEach(k => {
		let _t = tmList.find(t => t.prop == k);
		if (_t) {
			data[k] = data[k] ? (decrypt(data[k]) || data[k]) : '';
			if (isTm) data[k] = tmRules(data[k], _t.type);
		}

		if (typeof data[k] === 'object') {
			dealJmTmData(data[k], isTm);
		} else if (Array.isArray(data[k])) {
			data[k].forEach(dk => {
				if (typeof dk === 'object') {
					dealJmTmData(dk, isTm);
				}
			})
		}
	})
}

//将null和undefined转为空字符串
function nullToKongStr(data){
	if (!data) return;
	let keys = Object.keys(data);
	keys.forEach(k => {
		if(data[k]===null||data[k]===undefined) data[k] = "";
	
		if (typeof data[k] === 'object') {
			nullToKongStr(data[k]);
		} else if (Array.isArray(data[k])) {
			data[k].forEach(dk => {
				if (typeof dk === 'object') {
					nullToKongStr(dk);
				}
			})
		}
	})
}

// 脱敏规则
function tmRules(value, type) {
	if (!value) return;
	let res = '';
	if (type == 1) {
		let arr = Array.from(value)
		if (arr.length === 2) {
			res = arr[0] + '*'
		} else if (arr.length > 2) {
			for (let i = 1; i < arr.length - 1; i++) {
				arr[i] = '*'
			}
			res = arr.join("")
		} else {
			res = value
		}
	} else if (type == 2) {
		res = value.replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2");
	} else if (type == 3) {
		res = value.replace(/^(.{4})(?:\d+)(.{4})$/, "$1**********$2");
	}

	return res;
}

export const $http = (url, method, data, json, isAuth, isBuffer) => {
	let authorization = uni.getStorageSync('authorization') || 'Basic cmluZ3psZV9tZXJjaGFudDpyaW5nemxlX21lcmNoYW50';
	let access_token = uni.getStorageSync('access_token') || '';
	//设置请求前拦截器
	http.interceptor.request = (config) => {
		uni.showLoading({
			title: '加载中...'
		})
		config.header = {
			'content-type': json ? 'application/json' : 'application/x-www-form-urlencoded',
			'access_token': access_token
		}
		if (isAuth) config.header.authorization = authorization;
		if (isBuffer) config.responseType = 'arrayBuffer';
	}
	//设置请求结束后拦截器
	http.interceptor.response = async (response) => {
		//判断返回状态 执行相应操作

		uni.hideLoading()
		//数据解密脱敏处理
		if (response.data && response.data.data) {
			nullToKongStr(response.data.data);
			if (url.indexOf('/merchant/hotel/order/getOrderDetail/') > -1) {
				//房态入住人不脱敏不加密数据备份
				let checkInPersonList = response.data.data.detailFormList[0].checkInPersonList;
				if (checkInPersonList.length != 0) {
					checkInPersonList.forEach((ele, i) => {
						ele.checkInName2 = ele.checkInName;
						ele.idCard2 = ele.idCard;
						ele.checkInPhone2 = ele.checkInPhone;
					})
				}
			}
			let t = apiList.find(a => url.indexOf(a) > -1);
			if (!t) dealJmTmData(response.data.data, true);
			else dealJmTmData(response.data.data, false);
		}

		if ((response.data && response.data.code && response.data.code === 401) ||
			(response.data && response.data.msg && (response.data.msg.indexOf('未授权') > -1 ||
				response.data.msg.indexOf('重新登录') > -1))) {
			return uni.showModal({
				title: '温馨提示',
				content: '当前登录已失效，是否重新登录？',
				success: (res) => {
					if (res.confirm) {
						uni.clearStorageSync();
						// #ifdef APP-PLUS
						uni.reLaunch({
							url: '/pages/login/appIndex'
						})
						// #endif
						// #ifdef MP-WEIXIN
						uni.reLaunch({
							url: '/pages/login/index'
						})
						// #endif
					}
				}
			})
		}

		// 请根据后端规定的状态码判定
		if (response.data.code === 300) { //token失效
			//	return response.data = await doRequest(response, url)//动态刷新token,并重新完成request请求
		} else {
			if (response.data.code == 10021 && response.data.msg) {
				uni.showToast({
					title: response.data.msg,
					icon: 'none',
					duration: 1500
				})
			}
		}

		return response;
	}
	return http.request({
		method: method,
		url: url,
		dataType: 'json',
		data,
	})
}

async function login() {
	return new Promise(resolve => {
		uni.login({
			provider: 'weixin',
			success(loginRes) {
				resolve(loginRes.code)
			},
			fail() {}
		});
	})
}

function postJson(url, data, json = true, isAuth = true, isBuffer = false) {
	return $http(url, 'POST', data, json, isAuth, isBuffer)
}

function get(url, data, json = true, isAuth = true, isBuffer = false) {

	return $http(url, 'GET', data, json, isAuth, isBuffer)
}

function post(url, data, json = true, isAuth = true, isBuffer = false) {
	return $http(url, 'POST', data, json, isAuth, isBuffer)
}

function put(url, data, json = true, isAuth = true, isBuffer = false) {
	return $http(url, 'PUT', data, json, isAuth, isBuffer)
}

function del(url, data, json = true, isAuth = true, isBuffer = false) {
	return $http(url, 'DELETE', data, json, isAuth, isBuffer)
}

//检测文本和图像
import { BaseApi } from './baseApi.js';
const labelCfg = {
	10001:'含有广告内容',
	20001:'含有时政内容',
	20002:'含有色情内容',
	20003:'含有辱骂内容',
	20006:'含有违法犯罪内容',
	20008:'含有欺诈内容',
	20012:'含有低俗内容',
	20013:'含有版权内容',
	21000:'含有其他违规内容'
}
async function detectionContent(content,type=1){
	if(type==1){
		if(!uni.getStorageSync('userInfo')){
			return uni.showToast({
				title:'请先进行登录',
				icon:'none',
				duration:1500
			})
		}
		return new Promise((resolve,reject)=>{
			wx.request({
				method: 'POST',
				url:`${BaseApi}/api/app/wx/secCheckMsg`,
				dataType:'json',
				data:{
					content,
					openId:uni.getStorageSync('userInfo').openId
				},
				success:res=>{
					let result = {};
					if(res.data.code===0){
						let errcode = res.data.data.errcode;
						result.code = errcode;
						
						if(errcode===0){
							let resu = res.data.data.result;
							if(resu.label===100){
								result.code = 0;
								result.msg = '系统繁忙,请稍后再试';
							}else{
								result.code = resu.label;
								result.msg = labelCfg[resu.label]||'含有其他违规内容';
							}
						}else{
							if(errcode==-1) result.msg = '系统繁忙,请稍后再试';
							else if(errcode==87014) result.msg = '内容包含敏感违规信息';
							else if(errcode==40003) result.msg = 'openid无效，请重新登录';
							else result.msg = '系统错误';
						}
					}
					return resolve(result)
				},
				fail: err => {
					return reject(err)
				}
			})
		})
	}else if(type==2){
		return new Promise((resolve,reject)=>{
			wx.uploadFile({
				method:'POST',
				url:`${BaseApi}/api/app/wx/secCheckImg`,
				filePath: content,
				name: 'file',
				header: {
					'Content-Type': 'application/octet-stream'
				},
				formData:{
					media:content
				},
				success: res => {
					let data = JSON.parse(res.data);
					let result = {code:999,msg:'数据错误'};
					if(data&&data.code===0){
						let resu = JSON.parse(data.data);
						if(!resu) return;
						result.code = resu.errcode;
						if(resu.errcode==87014) result.msg = '图片含有敏感违规信息';
						else if(resu.errcode==40001) result.msg = 'token无效';
						else if(resu.errcode==40003) result.msg = 'openid无效';
						else if(resu.errcode==61010) result.msg = '用户访问记录超时';
						else{
							result.code = 0;
							result.msg = '内容正常';
						}
					}
					return resolve(result)
				},
				fail: err => {
					return reject(err)
				}
			});
		})
	} 
}

export default {
	postJson,
	get,
	post,
	put,
	del,
	detectionContent
}