package cn.hmsoft.weixin.request;

import java.io.File;
import java.io.FileOutputStream;

import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.helper.StringHelper;
import cn.hmsoft.weixin.constants.WxMaterialType;
import cn.hmsoft.weixin.entity.response.MaterialResponseJson;

public class MediaGetRequest extends AbstractRequest<MaterialResponseJson, MaterialResponseJson, MaterialResponseJson> {

	private final static String url = "https://api.weixin.qq.com/cgi-bin/media/get?";
	private final static String url2 = "http://api.weixin.qq.com/cgi-bin/media/get?";

	private String type;
	private String localPath;

	public MediaGetRequest(String media_id, String type) {
		this.requestEntity = new MaterialResponseJson();
		this.requestEntity.setMedia_id(media_id);
		this.type = type;

	}

	public MediaGetRequest(String media_id, String type, String path) {
		this.requestEntity = new MaterialResponseJson();
		this.requestEntity.setMedia_id(media_id);
		this.type = type;
		this.localPath = path;

	}

	@Override
	protected String makeUrl() {
		this.method = "POST";
		if (WxMaterialType.Video.equalsIgnoreCase(this.type))
			return url2 + "access_token=" + this.wxDefine.getApp_accesstoken() + "&media_id="
					+ this.requestEntity.getMedia_id();
		return url + "access_token=" + this.wxDefine.getApp_accesstoken() + "&media_id="
				+ this.requestEntity.getMedia_id();
	}
	@Override
	protected String receiveMessage() {
		String file_name = this.getDownloadFileName();
		if (StringHelper.isEmpty(file_name)) {
			return super.receiveMessage();
		}
		File file = null;
		try {
//			if (StringHelper.isEmpty(this.localPath))
//				file = new File(FrameParamUtil.getFrameUploadFilePath() + this.getDownloadFileName());
//			else
				file = new File(this.localPath + File.separator + this.getDownloadFileName());
		} catch (Exception e) {
			throw new BusinessException("无法将素材保存到本地目录，请联系系统管理员");

		}
		file.getParentFile().mkdirs();
		int size = 0;
		try {
			size = this.receiveAsFile(new FileOutputStream(file));
		} catch (Exception e) {

		}
		if (size == 0)
			throw new BusinessException("未能从微信服务器获取到文件，请重试");
//		 FrameFile frameFile = FrameFileService.addFrameFile(file, size);
//		 SpringHelper.GobalDao.delete(WxMaterial.class, "media_id",
//		 this.requestEntity.getMedia_id());
//		 SpringHelper.GobalDao.insert(frameFile);
//		 WxMaterial media = new WxMaterial();
//		 media.setInvalid_time(DateHelper.addValues(Calendar.DATE, 3));
//		 media.setLocal_file_id(frameFile.getFile_id());
//		 media.setMedia_id(this.requestEntity.getMedia_id());
//		 media.setMaterial_type(this.type);
//		 media.setName(file.getName());
//		 media.setStatus(FrameStatus.InActive);
//		 // media.set
//		 SpringHelper.GobalDao.insert(media);
		 this.jsonEntity = new MaterialResponseJson();
		 this.jsonEntity.setFile_name(file.getName());
		 this.returnEntity = new MaterialResponseJson();
		 this.returnEntity.setFile_name(file.getName());
		return null;
	}
}
