import store from "@/store";
import CryptoJS from '@/assets/crypto-js.min.js';
var doubleClickList = []; //防连击的数组对象
var keys = "ELAB_AUTHOPENAPI";
var iv = "ELAB_SECRET_APIS";

// 请求地址对象
const endpoints = {
    upload: 'elab-marketing-system/behavior/brandMiniWeb/upload', //埋点接口
    login: 'elab-marketing-analyse/cockpit/login', //用户登录
    uploadBase64: 'elab-marketing-file/upload/uploadBase64', //uploadBase64
	// // webGL接口
	getHouseTypeSpaceDetailsV2: 'elab-marketing-file/space_generation_background/getHouseTypeSpaceDetails/v2', //V1.1.0-城市首页
	getHouseTypeSpaceDetails: 'elab-marketing-file/space_generation_background/getHouseTypeSpaceDetails', //V1.1.0-城市首页
	
	//    // 柔性定制接口
	getHouseTypeSpaceWalls: '/elab-marketing-file/space_generation_background/getHouseTypeSpaceWalls', // 批量获取墙面信息
	
	houseDetail: 'elab-marketing-user/house/detail',
	findHouseTypeSpaceList: 'elab-marketing-file/space_generation_background/findHouseTypeSpaceList',
	findHouseTypeSpaceListByIds: 'elab-marketing-file/space_generation_background/findHouseTypeSpaceListByIds',
	layoutList: 'elab-marketing-content/aiDreamHouse/V3.0/layoutList',
	labelList: 'elab-marketing-content/aiDreamHouse/V3.0/labelList',
	findOverallArrangementList: 'elab-marketing-file/space_generation_background/findOverallArrangementList',
	getOverallArrangementDetailsList: 'elab-marketing-file/space_generation_background/getOverallArrangementDetailsList',
	choiceList: "elab-marketing-content/aiDreamHouse/V3.0/choiceList",
	getHardboundEffects: "elab-marketing-file/space_vary/getHardboundEffects",
	uploadImgControlNet: "elab-marketing-content/aiBeautyFamily/uploadImgControlNet",
	// generateProcess: "elab-marketing-content/aiBeautyFamily/generateProcess",
	getUploadToken: "elab-marketing-file/upload/getUploadToken",
	findSpatialInfoList: "elab-marketing-file/flexible_customization/findSpatialInfoList",
	// AI生成界面
	AIuploadImgControlNet: 'elab-marketing-content/aiGenerateImg/uploadImgControlNet', //ControlNet图片上传
	saveCustomizedRecord: 'elab-marketing-file/space_vary/saveCustomizedRecord', //用户AI信息上传
	getCustomizedRecord: 'elab-marketing-file/space_vary/getCustomizedRecord', //获取用户定制记录
	deleteCustomizedRecord: 'elab-marketing-file/space_vary/deleteCustomizedRecord', //删除用户定制记录
	chineseToPinyin: 'elab-marketing-file/tools/chineseToPinyin', //汉字转拼音
	generateTaskImgToImgForAliyun: 'elab-marketing-content/aiGenerateImg/img2Img', // 生成识别任务-阿里云(图生图)
	generateTaskWordToImgForAliyun: 'elab-marketing-content/aiGenerateImg/addTaskWithWord2Img', // 生成识别任务-阿里云(文生图)
	generateProcess: 'elab-marketing-content/aiGenerateImg/getResult', // 获取任务进度-阿里云
	img2img_local: 'elab-marketing-content/aiGenerateImg/img2img_local', // 生成图第一次请求
	getPredictions: 'elab-marketing-content/aiGenerateImg/getPredictions', // 获取任务进度-新版
	shareDetail: 'elab-marketing-content/aiDreamHouse/V3.0/shareDetail', // 分享查看
	queryEnumList: 'elab-marketing-user/enum/queryEnumList', // 获取数字人
	rob: 'elab-marketing-file/redpack/rob', // 抢红包
	robust_video: 'https://robustvideomatting.elab-plus.com/robust_video', // 上传视频
	// robust_video: 'http://192.168.50.52:5000/robust_video', // 上传视频
	get_result: 'https://robustvideomatting.elab-plus.com/get_result', // 获取视频上传结果
	getUserVirtural: 'elab-marketing-file/virtual/getUserVirtural', // 查询用户上传的数字人 
	addUserVirtural: 'elab-marketing-file/virtual/addUserVirtural', // 修改数字人信息
	aliyunOpenapiUploadOss: "elab-marketing-sms/aliyun/openapi/uploadOss", // 上传文件到oss
	queryTestcaseSingle: "elab-marketing-content/testcase/queryTestcaseSingle/v2", // 查询单个测试数据
	add: "elab-marketing-file/browse/records/add", // 是否喜欢
	send: 'elab-marketing-user/vcode/send/verifyCode', //发送短信验证码
	validate: 'elab-marketing-user/vcode/verifyCode/validate',//短信验证码验证
	authorizedMobile: 'elab-marketing-user/applet/auth_mobile', //解密手机号接口
	generateShareSign: 'elab-marketing-user/brand/shareSign/generateShareSign',//用户信息加密 获取 秘钥
	submitAnswer: 'elab-marketing-content/question/submitAnswer',//答题
	leavephone: 'elab-marketing-user/brandXcx/leavePhone',//web留电
	webXcxLogin: 'elab-marketing-user/htmlLogin/login', //H5平台登录
	// predictions: "https://api.replicate.com/v1/deployments/feathers-wing/spacely-realistic-style-softedge-a100/predictions", // 分享查看
};
/**
 * 加密参数
 * @param content
 * @returns {string}
 * @constructor
 */
function AES_encrypt(content) {
	content = JSON.stringify(content);
	let param = CryptoJS.enc.Utf8.parse(content);
	let _key = CryptoJS.enc.Utf8.parse(keys);
	let _iv = CryptoJS.enc.Utf8.parse(iv);
	let encrypted = CryptoJS.AES.encrypt(param, _key, {
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.Pkcs7,
		iv: _iv,
	});
	return encrypted.ciphertext.toString();
}
// var source = CancelToken.source();
window.requestConfig = async(endpoint, options, isHideLoading = false, preventDoubleClick = false, method = 'post',uploadProgress=null,cancel=null) => {
	if (!endpoints.hasOwnProperty(endpoint)) {
        console.error(`no such endpoint: ${endpoint}`);
        return {
            message: "不存在该接口"
        };
    }
    const requestOptions = {
        path: endpoints[endpoint],
        data: options,
    };
	let encryptedData = '';
	if (endpoint.indexOf('authorizedMobile') >= 0) {
	    encryptedData = await AES_encrypt(requestOptions.data);
	    requestOptions.data = {};
	}
    if (preventDoubleClick) {
        //说明该接口需要防止连击
        if (doubleClickList[requestOptions.path] && doubleClickList[requestOptions.path].isRunning) {
            console.log(`${requestOptions.path}触发连击，屏蔽该请求`)
            return
        } else {
            console.log(`${requestOptions.path}触发连击，通过`)
            doubleClickList[requestOptions.path] = {
                isRunning: true
            }
        }
    }
    console.log(`获取${requestOptions.path}请求的参数:`, requestOptions.data)
    requestOptions.url = requestOptions.path;
    // var t = Math.round(new Date());
    // requestOptions.time = t;
    if (!requestOptions.url.includes('/elab-marketing-user/aysn/task/byone') &&
        !requestOptions.url.includes('elab-marketing-analyse/heavenlyEye/saleTarget/add') &&
        !requestOptions.url.includes('elab-marketing-analyse/heavenlyEye/customer/coverPopulation') &&
        !requestOptions.url.includes('elab-marketing-analyse/heavenlyEye/customer/intention') &&
        !requestOptions.url.includes('elab-marketing-analyse/urbanCockpit/sky_eye_marketing/getAdCreativeDraftCheckResult') &&
        !requestOptions.url.includes('elab-marketing-analyse/heavenlyEye/getCompareMapTotalPopulation') &&
        !requestOptions.url.includes('aiGenerateImg/uploadImgControlNet') &&
        !requestOptions.url.includes('aiGenerateImg/img2Img') &&
        !requestOptions.url.includes('aiGenerateImg/img2img_local') &&
        !requestOptions.url.includes('aiGenerateImg/getPredictions') &&
        !requestOptions.url.includes('aiGenerateImg/getResult')
    ) {
        store.state.loading = true; //显示loading态
    }
    if (isHideLoading) {
        store.state.loading = false; //显示loading态
    }
	if (encryptedData) {
		requestOptions.headers = {};
	    requestOptions.headers.sign = encryptedData;
	}
    if (requestOptions.url.includes('elab-marketing-analyse/heavenlyEye/importLocations') ||
        requestOptions.url.includes('elab-marketing-sms/aliyun/openapi/uploadOss') ||
		requestOptions.url.includes('/robust_video')) {
        requestOptions.ContentType = 'multipart/form-data';
		if(uploadProgress && typeof(uploadProgress)==='function'){
			requestOptions.uploadProgress = uploadProgress;
		}
		
    }
    if (requestOptions) {
        let platform = (window.userInfo && window.userInfo['userAccount'] && window.userInfo['userAccount'].platform) ? window.userInfo['userAccount'].platform : ''; //TODO 要还原成‘’的
        let currentProject = store.state.currentProject ? store.state.currentProject : null;
        let landId = currentProject ? currentProject.id : '';
        requestOptions.data = requestOptions.data ? requestOptions.data : {};
    }
    var response;
    if (!requestOptions.url.includes('robust_video') && (requestOptions.url.includes('http') || method == 'get')) {
        let params = requestOptions.data;
        response = await axios.get(requestOptions.url, { params });
    } else {
		if(requestOptions.uploadProgress && typeof(requestOptions.uploadProgress)==='function'){
			let _dt = {
				onUploadProgress: progressEvent => {
					requestOptions.uploadProgress(progressEvent)
				}
			}
			if(cancel){//外界传递进来的取消函数
				let cancelTokenSource = axios.CancelToken.source();
				_dt.cancelToken = cancelTokenSource.token,
				cancel(cancelTokenSource)
			}
			response = await axios.post(requestOptions.url, requestOptions.data,_dt);
		}else{
			if(requestOptions.headers){
				response = await axios.post(requestOptions.url, requestOptions.data,{
					headers:requestOptions.headers
				});
			}else{
				response = await axios.post(requestOptions.url, requestOptions.data);
			}
		}
        
    }
    //说明该接口需要防止连击
    if (preventDoubleClick && doubleClickList[requestOptions.path] && doubleClickList[requestOptions.path]
        .isRunning) {
        console.log(`${requestOptions.path}连击接口已返回，清空连击数组`)
        doubleClickList[requestOptions.path].isRunning = false
    }
    // console.log('返回' + requestOptions.path + '请求的结果:', response)
    return response;
}
