import request from "./request";
import {
	getComponentDetailUrl,
	updateUserInfoUrl,
	checkLoginUrl,
	getPageInfoUrl,
	getServiceDynamicListUrl,
	messageSubscribeNotifyUrl,
	mktApplyNotifyUrl,
	gwAppId,
} from "./constants";
import { ywtAuth } from "./ywtService";
import { getSilentAuthCode, getAppId } from "./jsapi";
import { setStorage } from ".";

// 扫码通行api
export const getCourtlistInfoUrl = "api/v1/proxy/intelli_court/courtList";

const openCardCaseUrl = "/api/v1/card/openCardCase";

export const reportCourtInfoUrl = "api/v1/data/template/report";
// eslint-disable-next-line import/prefer-default-export

export async function getComponentDetail(payload) {
	try {
		const [error, response] = await request({
			data: payload,
			url: getComponentDetailUrl,
		});
		if (error) throw error;
		return [undefined, response];
	} catch (error) {
		return [error, undefined];
	}
}

export async function updateUserInfo(payload) {
	try {
		const [authErr, res = {}] = await getSilentAuthCode();
		if (authErr) {
			// 授权失败
			throw authErr;
		}
		const data = { ...payload, authCode: res.authCode };
		const [error, response] = await request({ data, url: updateUserInfoUrl });
		console.log(
			"=====getComponentList====",
			"error",
			error,
			"response",
			response
		);
		if (error) throw error;
		return [undefined, response];
	} catch (error) {
		return [error, undefined];
	}
}

// 检查登陆态加获取ticket
export async function checkUserInfo() {
	// eslint-disable-next-line no-undef
	const app = getApp();
	const { appId } = app.globalData;
	if (!appId) {
		app.globalData.appId = getAppId();
	}
	const [authCodeErr, authCodeRes] = await getSilentAuthCode();
	if (authCodeErr) return [authCodeErr, null];
	const [err, res] = await request({
		url: checkLoginUrl,
		data: { authCode: authCodeRes.authCode },
		noNeedTicket: true,
	});
	if (err) return [err, null];
	if (!res) return [null, null];
	const { ticket, expiresTime, userInfo } = res;
	app.globalData.ticketData.ticket = ticket;
	app.globalData.ticketData.expiresTime = expiresTime;
	if (userInfo) {
		const [ywtErr, ywtResult] = await ywtAuth({ ticket, gwAppId });
		if (!ywtErr && ywtResult && ywtResult.token) {
			app.globalData.ywtToken = "Bearer " + ywtResult.token;
			app.globalData.ywtUserId = ywtResult.userId;
		}
	}
	return [null, res];
}

// 获取页面配置信息
export async function getPageInfo(data) {
	const [err, res] = await request({
		url: getPageInfoUrl,
		data,
		noNeedTicket: true,
	});
	if (err || !res) return [err, null];
	return [null, res];
}

// 动态数据源
export async function getServiceDynamicList(data) {
	try {
		const [err, res] = await request({
			url: getServiceDynamicListUrl,
			method: "get",
			data: {
				componentUuid: data.componentUuid,
				current: data.current || 1,
				pageSize: data.pageSize || 10,
			},
		});
		if (err) return [err, undefined];
		//   return [undefined, res];
		// } catch (error) {
		//   return [error, undefined];
		// }
		return {
			...res,
			index: data.index,
		};
	} catch (error) {
		return {
			index: data.index,
			list: [],
		};
	}
}

// C端订阅成功后，通知后端存储数据
export async function messageSubscribeNotify({ userResult, templateIds }) {
	if (!userResult || !userResult.success) return;

	const messageTemplateList = templateIds.map((id) => {
		const ids = id.split(";");
		const templateId = ids[0];
		const alipayTemplateId = ids[1];
		const status =
			userResult[alipayTemplateId] === "accept" ? "success" : "fail";
		const message = userResult.errorMessage;
		return { templateId, alipayTemplateId, status, message };
	});

	const [err, res] = await request({
		url: messageSubscribeNotifyUrl,
		method: "post",
		data: {
			subscribeList: JSON.stringify(messageTemplateList),
		},
	});
	console.log(err, res);
}

export async function getCourtlistInfo(data) {
	const [err, res] = await request({
		url: getCourtlistInfoUrl,
		method: "get",
		data,
	});
	if (err || !res) return [err, null];
	return [null, res];
}
// 小区数据上报
export async function reportCourtInfo(data) {
	const [err, res] = await request({
		url: reportCourtInfoUrl,
		headers: {
			"content-type": "application/json",
		},
		data,
	});
	if (err || !res) return [err, null];
	return [null, res];
}
export async function openCardCase(data) {
	const [err, res] = await request({
		url: openCardCaseUrl,
		headers: {
			"content-type": "application/json",
		},
		data,
	});
	if (err || !res) return [err, null];
	return [null, res];
}

export async function notifyMktApply(data) {
	const [err, res] = await request({
		url: mktApplyNotifyUrl,
		method: "post",
		data,
	});
	if (err || !res) return [err, null];
	return [null, res];
}
