package cn.hmsoft.weixin.request;

import java.util.Date;

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

/***************************
 * @note 批量获取多媒体文件
 * @author revisit@126.com
 * @Company: www.hmsoft.cn
 * @create 2017-05-09 00:24:21
 * @version 4.0.0
 */
public class MaterialBatchgetRequest
		extends AbstractRequest<MaterialResponseJson, MaterialResponseJson, MaterialBatchGetRequestJson> {

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

	/************************
	 * @param type
	 *            多媒体类型
	 * @param offset
	 *            从offset开始获取
	 * @param count
	 *            一共获取的数量
	 */
	public MaterialBatchgetRequest(String type, int offset, int count) {
		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;
		if (this.jsonEntity.getItem_count() == 0)
			return;
		for (MaterialResponseJson.MaterialItem 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.setMedia_id(item.getMedia_id());
				wm.setName(item.getName());
				wm.setUrl(item.getUrl());
				wm.setMaterial_type(this.requestEntity.getType());
				try {
					SpringHelper.AppGobalDao.insert(wm);
				} catch (Exception e) {
					LogHelper.error(e);
				}
			}
		}
	}
}
