import request from '../request'
import md5 from 'crypto-js/md5'

let pddKeyword = [],
	keyIndex = 0

//首页模块
const home = {
	/**
	 * 查询轮播图列表
	 */
	getHomePageDataList(keys) {
		return request({
			url: `student/applet/homePage/dictValueHomePageDataList/` + keys,
			method: 'get'
		})
	},
	async getPddKeyword() {
		if (pddKeyword.length != 0) {
			keyIndex++
			return pddKeyword[keyIndex % pddKeyword.length]
		}
		let {
			data
		} = await request({
			url: `/system/config/configKey/pdd_keyword`,
		})
		pddKeyword = data.split('/')
		return pddKeyword[keyIndex % pddKeyword.length]
	},
	/**
	 * 查询轮播图列表
	 * @param {Object} data
	 */
	async getPDD(data) {
		let keyword = await home.getPddKeyword()
		let params = {
			// type: 'pdd.ddk.goods.recommend.get',
			type: 'pdd.ddk.goods.search',
			data_type: 'JSON',
			client_id: 'fa0f2debb5b0444b9719919d7b8204d1',
			pid: '1642187_203462988',
			timestamp: new Date().getTime().toString().slice(0, 10),
			keyword,
			...data
		}
		let client_secret = '3305b6bb37252495848e67fd991134651e308495'
		params.sign = calcAuth(params, client_secret)
		return request({
			url: `https://gw-api.pinduoduo.com/api/router`,
			method: 'get',
			params
		})
	},
	/**
	 * 查询小程序跳转参数
	 * @param {Object} data
	 */
	async getPddWxData(data) {
		let params = {
			type: 'pdd.ddk.goods.promotion.url.generate',
			data_type: 'JSON',
			client_id: 'fa0f2debb5b0444b9719919d7b8204d1',
			p_id: '1642187_203462988',
			timestamp: new Date().getTime().toString().slice(0, 10),
			generate_we_app: true
		}
		let getPDDRes = await home.getPDD(data)
		params.search_id = getPDDRes.goods_search_response.search_id
		let arr = '['
		getPDDRes.goods_search_response.goods_list.map((val) => {
			arr += '"' + val.goods_sign + '",'
		})
		params.goods_sign_list = arr.slice(0, -1) + ']'
		let client_secret = '3305b6bb37252495848e67fd991134651e308495'
		params.sign = calcAuth(params, client_secret)
		let wxDataRes = await request({
			url: `https://gw-api.pinduoduo.com/api/router`,
			method: 'get',
			params
		})
		let dataArr = []
		getPDDRes.goods_search_response.goods_list.map((val, index) => {
			val.we_app_info = wxDataRes.goods_promotion_url_generate_response.goods_promotion_url_list[
				index].we_app_info
		})
		return getPDDRes.goods_search_response.goods_list
	}

}

//拼多多密钥计算
function calcAuth(params, client_secret) {
	var arr = []
	Object.keys(params).sort().forEach((key) => {
		arr.push(key + params[key])
	})
	arr[0] = client_secret + arr[0]
	arr[arr.length - 1] += client_secret
	return md5(arr.join('')).toString().toUpperCase()
}


export default home
