package cn.hmsoft.weixin.request;

import java.util.Calendar;
import java.util.Date;

import cn.hmsoft.application.SpringHelper;
import cn.hmsoft.frame.constants.FrameStatus;
import cn.hmsoft.helper.DateHelper;
import cn.hmsoft.log.LogHelper;
import cn.hmsoft.weixin.constants.WxMaterialType;
import cn.hmsoft.weixin.data.model.WxMaterial;
import cn.hmsoft.weixin.entity.request.MaterialBatchGetRequestJson;
import cn.hmsoft.weixin.entity.response.MaterialNewsResponseJson;

/****************************************
 * 
 * @note 批量获取多媒体（图文）
 * @author revisit@126.com
 * @Company: www.hmsoft.cn
 * @create 2017-05-09 00:18:42
 * @version 4.0.0
 */
public class MaterialBatchgetNewsRequest extends AbstractRequest<MaterialNewsResponseJson, MaterialNewsResponseJson, MaterialBatchGetRequestJson> {

	private final static String url = "https://api.weixin.qq.com/cgi-bin/tags/members/batchtagging?";

	public MaterialBatchgetNewsRequest(String type, int count, int offset) {
		this.requestEntity = new MaterialBatchGetRequestJson();
		this.requestEntity.setCount(count);
		this.requestEntity.setOffset(offset);
		this.requestEntity.setType(type);
	}

	@Override
	protected String makeUrl() {
		this.method = "POST";
		return url + "access_token=" + this.wxDefine.getApp_accesstoken();
	}

	@Override
	public void processBusiness() {
		this.returnEntity = this.jsonEntity;
		for (MaterialNewsResponseJson.Item item : this.jsonEntity.getItem()) {
			WxMaterial wm = SpringHelper.AppGobalDao.find(WxMaterial.class, item.getMedia_id());
			if (wm == null) {
				wm = new WxMaterial();
				wm.setUpdate_time(new Date(item.getUpdate_time() * 1000));
				wm.setInvalid_time(DateHelper.addValues(Calendar.YEAR, 10));
				wm.setStatus(FrameStatus.Active.toString());
				wm.setMaterial_type(WxMaterialType.News);
				try {
					SpringHelper.AppGobalDao.insert(wm);
				} catch (Exception e) {
					LogHelper.error(e);
				}
			}
		}
	}
}
