package com.cyksj.web.controller.mini;

import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.util.IoKit;
import com.cyksj.common.util.StringUtil;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.model.entity.User;
import com.cyksj.model.request.MiniArticleReq;
import com.cyksj.model.request.MiniProgramLoginPost;
import com.cyksj.model.request.MiniSchemaReq;
import com.cyksj.model.views.ArticleDetailView;
import com.cyksj.model.views.ArticleFrontView;
import com.cyksj.model.views.ArticleSelfFrontView;
import com.cyksj.service.mini.MiniService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;

/*
 *项目名: netflix
 *文件名: MiniController
 *创建者: JavaZou
 *创建时间:2023/5/11 18:03
 */
@RestController
@RequestMapping("/applets/mini")
@RequiredArgsConstructor
@Slf4j
public class MiniController {
	private final MiniService miniService;

	private final BeanSearcher beanSearcher;

	private final HttpServletRequest request;

	/**
	 * 生成小程序跳转链接二维码
	 */
	@RequestMapping(value = "/linkUrl", method = RequestMethod.GET)
	public Result<String> getMiniLinkURL(String path, String query) throws Exception {
		String linkUrl = miniService.getMiniURLLink(path, query);
		return GatewayResponse.SUCCESS.newBuilder().toResult(linkUrl);
	}

	/**
	 * 生成小程序schema
	 */
	@GetMapping("/generate/schema")
	public Result<String> generateSchema(String dsCode) throws Exception {
		MiniSchemaReq req = new MiniSchemaReq();
		req.setDsCode(dsCode);
		String url = miniService.generateSchema(req);
		return GatewayResponse.SUCCESS.newBuilder().toResult(url);
	}

	/**
	 * 生成小程序code
	 */
	@GetMapping("/generate/code")
	public void generateCode(String dsCode, HttpServletResponse response) throws Exception {
		MiniSchemaReq req = new MiniSchemaReq();
		req.setDsCode(dsCode);
		byte [] s = miniService.generateCode(req);
		response.reset();
		// 若直接在浏览器预览 需要注释下面的response header
		//response.addHeader("Content-Disposition", "attachment;filename=share.jpeg");
		response.setContentType("image/jpeg");
		// 处理文件 返回流
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			IoKit.write(s, out);
		} catch (Throwable e) {
			throw BusinessRuntimeException.getInstance(StringUtil.getErrorMsg(e));
		} finally {
			IoKit.close(out);
		}
	}

	/**
	 * 银河小程序 静默授权登录
	 */
	@PostMapping("/user/login")
	public Result<String> userLogin(@RequestBody MiniProgramLoginPost miniDataParams) throws Exception {
		String methodName = "银河小程序静默授权";
		log.info("{}[start] params:{}", methodName, miniDataParams);

		if (StringUtils.isBlank(miniDataParams.getCode())) {
			throw BusinessRuntimeException.getInstance("需要登录凭证code.");
		}
		User user = miniService.wxlogin(miniDataParams.getCode(), miniDataParams.getAppId());
		StpUserUtil.login(user.getId());

		log.info("{}[end] uuid:{}", methodName, user.getId());

		return GatewayResponse.SUCCESS.newBuilder().toResult(StpUserUtil.getTokenValue());
	}

	/**
	 * 生成GPT小程序schema
	 */
	@PostMapping("/generate/gpt/schema")
	public Result<String> generateGptMiniSchema(@RequestBody MiniSchemaReq req) throws Exception {
		String url = miniService.generateGptMiniSchema(req);
		return GatewayResponse.SUCCESS.newBuilder().toResult(url);
	}


	/**
	 * 文章列表
	 */
	@GetMapping("/get/article")
	public Result<SearchResult<ArticleFrontView>> getArticleFrontView(@RequestParam(defaultValue = "0") Boolean login) {
		Long userId = null;
		if (login) {
			userId = StpUserUtil.getLoginIdAsLong();
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		if (userId != null) builder.put("user_id", String.format("and aum2.user_id = %s", userId));
		SearchResult<ArticleFrontView> search = beanSearcher.search(ArticleFrontView.class, builder
				.orderBy(ArticleFrontView::getReleaseTime).desc()
				.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 文章标记
	 */
	@PostMapping("/mark/article")
	public Result<String> markArticle(@RequestBody @Validated MiniArticleReq miniArticleReq) {
		Integer type = miniArticleReq.getType();
		long userId = StpUserUtil.getLoginIdAsLong();
		if (type < 0 || type > 2) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		miniArticleReq.setUserId(userId);
		return miniService.markArticle(miniArticleReq);
	}

	/**
	 * 文章筛选自身标记列表
	 */
	@GetMapping("/get/mark/article")
	public Result<SearchResult<ArticleSelfFrontView>> getArticleByType(@RequestParam(defaultValue = "1") Integer type) {
		long userId = StpUserUtil.getLoginIdAsLong();
		if (type < 0 || type > 2) {
			return GatewayResponse.SUCCESS.newBuilder().toResult();
		}
		MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap());
		String conditionSql = String.format(" where user_id = %s", userId);
		if (type == 1) {
			conditionSql += " and is_dz is true";
		}
		if (type == 2) {
			conditionSql += " and is_col is true";
		}
		builder.put("condition", conditionSql);
		SearchResult<ArticleSelfFrontView> search = beanSearcher.search(ArticleSelfFrontView.class, builder.build());
		return GatewayResponse.SUCCESS.newBuilder().toResult(search);
	}

	/**
	 * 文章详情
	 */
	@GetMapping("/get/article/detail/{articleId}")
	public Result<ArticleDetailView> getArticleDetailView(@PathVariable Long articleId, @RequestParam(defaultValue = "0") Boolean login) {
		Long userId = null;
		if (login) {
			userId = StpUserUtil.getLoginIdAsLong();
		}
		ArticleDetailView view = miniService.getArticleDetailView(articleId, userId);
		return GatewayResponse.SUCCESS.newBuilder().toResult(view);
	}
}
