/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.mp.comment.platform.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Json;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.config.WxConfig;
import com.yami.shop.mp.comment.model.WeixinMaterial;
import com.yami.shop.mp.comment.platform.service.WeixinMaterialService;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult.WxMaterialFileBatchGetNewsItem;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNews;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialNewsBatchGetResult;
import me.chanjar.weixin.mp.bean.material.WxMpNewsArticle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author lgh on 2019/05/14.
 */
@RestController
@RequestMapping("/weixin/material")
public class WeixinMaterialController {
	@Autowired
	private WeixinMaterialService weixinMaterialService;

	@Autowired
	private WxConfig wxConfig;

	/**
	 * 分页获取
	 */
	@GetMapping("/page")
	@PreAuthorize("@pms.hasPermission('weixin:material:page')")
	public ResponseEntity<IPage<WeixinMaterial>> page(PageParam<WeixinMaterial> page,WeixinMaterial weixinMaterial){
		IPage<WeixinMaterial> list = weixinMaterialService.page(page, new LambdaQueryWrapper<WeixinMaterial>()
				.eq(StrUtil.isNotBlank(weixinMaterial.getMediaType()), WeixinMaterial::getMediaType, weixinMaterial.getMediaType())
				.like(StrUtil.isNotBlank(weixinMaterial.getMediaName()), WeixinMaterial::getMediaName, weixinMaterial.getMediaName()));
		return ResponseEntity.ok(list);
	}

	/**
	 *  同步素材
	 * @throws WxErrorException
	 */
	@PostMapping("/sync/{type}")
	@PreAuthorize("@pms.hasPermission('weixin:material:sync')")
	public ResponseEntity<Void> sync(@PathVariable String type) throws WxErrorException{
		if (StrUtil.isBlank(type)) {
			throw new GlobalException("请选择素材类型");
		}
		List<WeixinMaterial> allMaterial = new ArrayList<>();
		// 每页大小
		int pageSize = 20;
		// 一共有多少页
		int pageCount = 1;
		// 一共有多少条记录
		int totalCount = 0;
		for (int i = 0; i < pageCount; i++) {
			// 图文素材
			if (WxConsts.MaterialType.NEWS.equals(type)) {
				WxMpMaterialNewsBatchGetResult wxMpMaterialNewsBatchGetResult = wxConfig.getWxMpService().getMaterialService().materialNewsBatchGet(i * pageSize, pageSize);
				totalCount = wxMpMaterialNewsBatchGetResult.getTotalCount();
				List<WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem> items = wxMpMaterialNewsBatchGetResult.getItems();
				for (WxMpMaterialNewsBatchGetResult.WxMaterialNewsBatchGetNewsItem newsItem : items) {
					WeixinMaterial weixinMaterial = new WeixinMaterial();
					weixinMaterial.setCreateTime(newsItem.getUpdateTime());
					weixinMaterial.setMediaId(newsItem.getMediaId());
					WxMpMaterialNews content = newsItem.getContent();
					List<WxMpNewsArticle> articles = content.getArticles();

					// 多余的文章没有实际作用，微信返回的消息只能返回一条
					WxMpNewsArticle wxMpMaterialNewsArticle = articles.get(0);
					// 内容保存起来没有实际用处，清除内容
					wxMpMaterialNewsArticle.setContent(null);

					weixinMaterial.setContent(Json.toJsonString(wxMpMaterialNewsArticle));
					weixinMaterial.setMediaName(wxMpMaterialNewsArticle.getTitle());
					weixinMaterial.setCreateTime(content.getCreateTime());
					weixinMaterial.setUpdateTime(content.getUpdateTime());
					weixinMaterial.setMediaType(type);
					allMaterial.add(weixinMaterial);
				}
			}
			// 其他素材：视频，语音，图片
			else {
				WxMpMaterialFileBatchGetResult wxMpMaterialFileBatchGetResult = wxConfig.getWxMpService().getMaterialService().materialFileBatchGet(type,i*pageSize, pageSize);
				totalCount = wxMpMaterialFileBatchGetResult.getTotalCount();
				List<WxMaterialFileBatchGetNewsItem> items = wxMpMaterialFileBatchGetResult.getItems();
				for (WxMaterialFileBatchGetNewsItem materialItem : items) {
					WeixinMaterial weixinMaterial = new WeixinMaterial();
					weixinMaterial.setCreateTime(materialItem.getUpdateTime());
					weixinMaterial.setMediaId(materialItem.getMediaId());
					weixinMaterial.setMediaName(materialItem.getName());
					weixinMaterial.setUpdateTime(materialItem.getUpdateTime());
					weixinMaterial.setMediaType(type);
					weixinMaterial.setContent(materialItem.getUrl());
					allMaterial.add(weixinMaterial);
				}
			}

			// 初始化
			if (i == 0) {
				pageCount = totalCount / pageSize;
				if (totalCount % pageSize > 0) {
					pageCount +=1 ;
				}
			}
		}
		weixinMaterialService.insertBatch(allMaterial,type);
		return ResponseEntity.ok().build();
	}

	/**
	 * 删除
	 */
	@DeleteMapping("/{mediaId}")
	@PreAuthorize("@pms.hasPermission('weixin:material:delete')")
	public ResponseEntity<Void> delete(@PathVariable String mediaId){
		weixinMaterialService.delete(mediaId);
		return ResponseEntity.ok().build();
	}

	/**
	 * 分页获取
	 */
	@GetMapping("/list")
	@PreAuthorize("@pms.hasPermission('weixin:material:info')")
	public ResponseEntity<List<WeixinMaterial>> list(){
		return ResponseEntity.ok(weixinMaterialService.list());
	}
}
