package cn.hmsoft.weixin.control;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.hmsoft.application.web.Ajax;
import cn.hmsoft.frame.control.FrameControl;
import cn.hmsoft.frame.exception.BusinessException;
import cn.hmsoft.frame.util.FrameAssertUtil;
import cn.hmsoft.weixin.constants.WxMaterialType;
import cn.hmsoft.weixin.data.dao.WxUserLogDao;
import cn.hmsoft.weixin.data.model.WxMaterial;
import cn.hmsoft.weixin.entity.request.custom.CustomRequestJson;
import cn.hmsoft.weixin.entity.request.custom.ImageCustomRequestJson;
import cn.hmsoft.weixin.entity.request.custom.TextCustomRequestJson;
import cn.hmsoft.weixin.entity.request.custom.VideoCustomRequestJson;
import cn.hmsoft.weixin.entity.request.custom.VoiceCustomRequestJson;
import cn.hmsoft.weixin.entity.request.custom.entity.Video;
import cn.hmsoft.weixin.request.MessageCustomSendRequest;
import cn.hmsoft.weixin.service.WxUserService;

@RestController
public class WxCustomSendControl extends FrameControl {
	@Autowired
	private WxUserLogDao daoLog;
	
	@Autowired
	private WxUserService sUSer;

	@RequestMapping("weixin/custom/send/text")
	public Ajax text(int wx_id, String open_id, String content) {
		FrameAssertUtil.isNotEmpty(content, "文本消息不允许为空");
		TextCustomRequestJson json = new TextCustomRequestJson(content);
		json.setTouser(open_id);
		MessageCustomSendRequest rq = new MessageCustomSendRequest(json);
		rq.setWxDefine(wx_id);
		rq.request();
		daoLog.logMessage(wx_id, json);
		this.sUSer.logMessage(this.getFrameOptr(), open_id, content);
		return new Ajax();

	}

	@RequestMapping("weixin/custom/send/media")
	public Ajax media(int wx_id, String open_id, WxMaterial media) {
		CustomRequestJson json = null;
		if (media.getMaterial_type().equalsIgnoreCase(WxMaterialType.Image)) {
			json = new ImageCustomRequestJson(media.getMedia_id());
		} else if (media.getMaterial_type().equalsIgnoreCase(WxMaterialType.Video)) {
			Video video = new Video();
			// video.setDescription(media.get);
			video.setTitle(media.getName());
			json = new VideoCustomRequestJson(video);
		} else if (media.getMaterial_type().equalsIgnoreCase(WxMaterialType.Voice)) {
			json = new VoiceCustomRequestJson(media.getMedia_id());
		} else {
			throw new BusinessException("不支持该格式的媒体文件");
		}
		json.setTouser(open_id);
		MessageCustomSendRequest rq = new MessageCustomSendRequest(json);
		rq.request();
		rq.setWxDefine(wx_id);
		daoLog.logMessage(wx_id,json);
		return new Ajax();

	}
}
