import Request from '../common/request.js';
let request = new Request().http

 //微信小程序登录
 export function loginByMiniApp(data) {
 	 //return request('/course_uniapp/app/wx/miniapp/loginByMa',data,'POST','application/json;charset=UTF-8');
	 return request('/app/wx/loginByMiniApp',data,'POST','application/json;charset=UTF-8');
 }
// 播放错误上报
export function getErrMsg(data) {
	return request('/course_uniapp/app/course/wx/h5/getErrMsg', data, 'POST', 'application/x-www-form-urlencoded','https://h5api.his.cdwjyyh.com');
}
// h5课程简介
export function getH5CourseByVideoId(data) {
	return request('/course_uniapp/app/course/wx/h5/getH5CourseByVideoId', data, 'GET','','https://h5api.his.cdwjyyh.com');
}
// h5课程详情加问答
export function getH5CourseVideoDetails(data) {
	return request('/course_uniapp/app/course/wx/h5/videoDetails', data, 'GET','','https://h5api.his.cdwjyyh.com');
}
// 答题发红包
export function courseAnswer(data) {
	return request('/course_uniapp/app/course/wx/h5/courseAnswer', data, 'POST', 'application/json;charset=UTF-8','https://h5api.his.cdwjyyh.com');
}
// 记录看课时间（新）
export function getFinishCourseVideo(data) {
	return request('/course_uniapp/app/course/wx/h5/updateWatchDuration', data, 'POST', 'application/json;charset=UTF-8','https://h5api.his.cdwjyyh.com');
}
// 关注客服 是否添加客服
export function getIsAddKf(data) {
	return request('/course_uniapp/app/course/wx/h5/isAddKf', data, 'POST', 'application/json;charset=UTF-8','https://h5api.his.cdwjyyh.com');
}
// 流量(缓冲百分比)
export function getInternetTraffic(data) {
	return request('/course_uniapp/app/course/wx/h5/getInternetTraffic', data, 'POST', 'application/json;charset=UTF-8','https://h5api.his.cdwjyyh.com');
}
// 每十分钟获得积分
export function getIntegralByH5Video(data) {
	return request('/app/course/getIntegralByH5Video', data, 'POST', 'application/json;charset=UTF-8','https://h5api.his.cdwjyyh.com');
}

// 发送奖励
export function sendReward(data) {
	return request('/course_uniapp/app/course/wx/h5/sendReward', data, 'POST', 'application/json;charset=UTF-8','https://h5api.his.cdwjyyh.com');
}
// 获取真实链接
export function getRealLink(data) {
	return request('/app/course/getRealLink', data, 'GET','','https://h5api.his.cdwjyyh.com');
}
 //检查是否有头像以及昵称
 export function checkUserInfo(data) {
 	 return request('/course_uniapp/app/user/checkUserInfo',data,'GET','application/json;charset=UTF-8');
 }
 //更改用户头像以及昵称
 export function editUser(data) {
 	 return request('/course_uniapp/app/user/editUser',data,'POST','application/json;charset=UTF-8');
 }
 // 成为会员
 export function registerCourses(data) {
 	 return request('/course_uniapp/companyapp/app/fs/user/beMember',data,'POST','application/json;charset=UTF-8');
 }
 //获取头像以及昵称信息
 export function getusername(data) {
 	 return request('/companyapp/app/wx/h5/mp/userInfo',data,'POST','application/json;charset=UTF-8');
 }
 //h5授权登录
 export function handleFsUserWx(data) {
 	 return request('/course_uniapp/app/wx/h5/mp/handleFsUserWx',data,'POST','application/json;charset=UTF-8');
 }
 //h5授权登录
 export function H5logoinApp(data,type) {
	 if(type&&type==1) {
		return request('/app/wx/h5/mp/courseLoginByMp',data,'POST','application/json;charset=UTF-8'); 
	 } else {
		return request('/app/wx/h5/mp/loginByMp',data,'POST','application/json;charset=UTF-8'); 
	 }
 }
 //获取弹窗时间
 export function getRemainTime(data) {
 	 return request('/course_uniapp/app/course/wx/h5/getRemainTime',data,'POST','application/json;charset=UTF-8');
 }
 
 //查询评论
 export function getCommentList(data) {
 	 return request('/course_uniapp/app/course/comment/myList',data,'GET','application/json;charset=UTF-8');
 }
/** 取首个文件路径（兼容误传数组） */
function _firstPathArg(v) {
	if (v == null) return ''
	if (typeof v === 'string') return v.trim()
	if (Array.isArray(v) && v.length) {
		const x = v[0]
		return x != null && typeof x === 'string' ? x.trim() : ''
	}
	return ''
}

/**
 * 是否应使用 uni.uploadFile 上传的本地临时路径。
 * 注意：微信/uni 下相册临时路径常为 http(s)://tmp/...，若以「是否 http」判断会误判为网络图，导致不走上传、图片未传参。
 */
function _isLocalMediaFilePath(p) {
	if (p == null || p === '') return false
	if (typeof p !== 'string') return false
	const s = p.trim()
	if (!s) return false
	if (/^blob:/i.test(s)) return false
	if (/^https?:\/\/tmp\//i.test(s)) return true
	if (/^wxfile:\/\//i.test(s)) return true
	if (/^file:\/\//i.test(s)) return true
	if (/^https?:\/\//i.test(s)) return false
	return true
}

function _addCommentWithMediaUploadBaseUrl() {
	const base = uni.getStorageSync('requestPath') || 'https://userapp.klbycp.com'
	return String(base).replace(/\/$/, '') + '/app/course/comment/addCommentWithMedia'
}

/** courseId、type、content、toUserId 拼到请求路径（query），值均 encodeURIComponent */
function _buildAddCommentWithMediaQuery(d) {
	const courseId = encodeURIComponent(d.courseId != null ? String(d.courseId) : '')
	const videoId = encodeURIComponent(d.videoId != null ? String(d.videoId) : '')
	const type = encodeURIComponent(d.type != null ? String(d.type) : '1')
	const content = encodeURIComponent(d.content != null ? String(d.content) : '')
	const toUserId = encodeURIComponent(d.toUserId != null ? String(d.toUserId) : '')
	return `?courseId=${courseId}&videoId=${videoId}&type=${type}&content=${content}&toUserId=${toUserId}`
}

/**
 * 发布评论：业务参数均在 URL query；带本地图/视频时仅 multipart body 传 imageFiles 或 videoFiles
 */
export function addCommentWithMedia(data) {
	const d = data || {}
	const imageArg = _firstPathArg(d.imageFiles)
	const videoArg = _firstPathArg(d.videoFiles)
	const imagePath = _isLocalMediaFilePath(imageArg) ? imageArg : ''
	const videoPath = _isLocalMediaFilePath(videoArg) ? videoArg : ''
	if (imagePath || videoPath) {
		return new Promise((resolve, reject) => {
			const token =
				uni.getStorageSync('TOKEN_WEXIN') ||
				uni.getStorageSync('AppTokenmini_AutoCourse') ||
				''
			// 与 common/request.js 中 uni.request 一致；multipart 的 boundary 由客户端自动带，勿手写 Content-Type
			const header = {
				AppToken: token
			}
			try {
				if (typeof wx !== 'undefined' && wx.getAccountInfoSync) {
					header['appid'] = wx.getAccountInfoSync().miniProgram.appId
				}
			} catch (e) {}
			const filePath = imagePath || videoPath
			// 与后端 multipart 字段名一致：imageFiles / videoFiles（Content-Disposition: form-data; name="imageFiles"; filename="..."）
			const name = imagePath ? 'imageFiles' : 'videoFiles'
			const url = _addCommentWithMediaUploadBaseUrl() + _buildAddCommentWithMediaQuery(d)
			uni.uploadFile({
				url,
				filePath,
				name,
				header,
				success: (uploadFileRes) => {
					try {
						const raw = uploadFileRes.data
						const body = typeof raw === 'string' ? JSON.parse(raw) : raw
						resolve(body)
					} catch (e) {
						reject(e)
					}
				},
				fail: (err) => {
					reject(err || new Error('发布失败'))
				}
			})
		})
	}
	const router =
		'/course_uniapp/app/course/comment/addCommentWithMedia' + _buildAddCommentWithMediaQuery(d)
	return request(router, {}, 'POST')
}