package com.qs.mp.web.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.qs.mp.channel.domain.Channel;
import com.qs.mp.common.core.domain.AjaxResult;
import com.qs.mp.common.core.domain.AjaxResult.Type;
import com.qs.mp.common.enums.ErrorCodeEnum;
import com.qs.mp.framework.service.IAppTokenService;
import com.qs.mp.framework.service.IWxUrlLinkService;
import com.qs.mp.utils.SecurityUtils;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @auther zhongcp
 * @create 2022-02-28 16:17:48
 * @describe 渠道邀请前端控制器
 */
@Api("微信服务端调用API")
@RestController
@RequestMapping("/api/v1/mp/wx/*")
@Component
public class WxServerController extends BaseApiController {

	@Autowired
	private IWxUrlLinkService wxUrlLinkService;

	@Autowired
	private IAppTokenService appTokenService;

	@Value("${wx-user.appId}")
	private String userAppId;

	/**
	 * 用户扫描盲票二维码，生成schemaUrl，每天限量50w个
	 *
	 * @return
	 */
	@PostMapping("urlschema/generate")
	public AjaxResult generateUrlSchema(@RequestBody  JSONObject jsonObject) {
		String query = jsonObject.getString("query");
		String path = jsonObject.getString("path"); // "/pages/deposit/index"
		String rst = wxUrlLinkService.generateUrlSchema(path, query, userAppId);
		return new AjaxResult(Type.SUCCESS, "", rst);
	}

	/**
	 * 生成盲票购买小程序码
	 *
	 * @return
	 */
	@PostMapping("code/generate")
	public AjaxResult generateInviteCode(@RequestBody  JSONObject jsonObject) {
		String id = jsonObject.getString("id");
		String rst = wxUrlLinkService.generateCode("pages/lucky/index", "id=" + id, userAppId);
		return new AjaxResult(Type.SUCCESS, "", rst);
	}

	/**
	 * 获取小程序access_token
	 *
	 * @return
	 */
	@PostMapping("getAccessToken")
	public AjaxResult getAccessToken(@RequestBody  JSONObject jsonObject) {
		String appId = jsonObject.getString("appId");
		if (StringUtils.isBlank(appId)) {
			return AjaxResult.error(ErrorCodeEnum.ERROR_CODE_1001);
		}
		String rst = appTokenService.getAccessToken(appId);
		return new AjaxResult(Type.SUCCESS, "", rst);
	}
}
