package cn.hmsoft.weixin.control;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.helper.StringHelper;
import cn.hmsoft.jdbc.entity.Pager;
import cn.hmsoft.jdbc.entity.QueryOrder;
import cn.hmsoft.weixin.constants.WxParamName;
import cn.hmsoft.weixin.constants.WxResId;
import cn.hmsoft.weixin.data.dao.WxTemplateDao;
import cn.hmsoft.weixin.data.model.WxTemplate;
import cn.hmsoft.weixin.service.WxTemplateService;
import cn.hmsoft.weixin.util.WeiXinParamUtil;
import cn.hmsoft.weixin.util.WeiXinTemplateUtil;
import cn.hmsoft.weixin.util.WeiXinUtil;

@RestController
public class WxTemplateControl extends FrameControl {
	@Autowired
	private WxTemplateDao daoTemplate;
	@Autowired
	private WxTemplateService sTemplate;

	@RequestMapping("weixin/template/page")
	public Ajax page(Integer wx_id, int start, int limit, String query, String order, String type) {
		if (wx_id == null)
			return new Ajax(new Pager(new ArrayList<String>()));
		this.authOptrRole(WxResId.Template_Page);
		return new Ajax(this.daoTemplate.pageTemplate(wx_id, start, limit, query, getQueryOrder(order, type)));
	}

	@RequestMapping("weixin/template/edit")
	public Ajax edit(int wx_id, WxTemplate template) {
		this.authOptrRole(WxResId.Template_Manage);
		if (template.getTemplate_id() != null)
			this.sTemplate.editTemplate(wx_id, template, this.getFrameOptr());
		else
			this.sTemplate.addTemplate(wx_id, template, this.getFrameOptr());
		return new Ajax();
	}

	@RequestMapping("weixin/template/all")
	public Ajax all(int wx_id) {
		return new Ajax(this.daoTemplate.all());
	}

	@RequestMapping("weixin/template/find")
	public Ajax find(int template_id) {
		return new Ajax(this.daoTemplate.find(template_id));
	}

	@RequestMapping("weixin/template/delete/all")
	public Ajax deleteAll(int wx_id) {
		this.authOptrRole(WxResId.Template_Manage);
		this.sTemplate.delAllTemplate(wx_id, this.getFrameOptr());
		return new Ajax();
	}

	@RequestMapping("weixin/template/reload")
	public Ajax reload(int wx_id) {
		try {
			WeiXinParamUtil.WeiXinModuleConfig.restart();
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}
		return new Ajax();
	}

	@RequestMapping("weixin/template/delete")
	public Ajax delete(int wx_id, int template_id) {
		this.authOptrRole(WxResId.Template_Manage);
		this.sTemplate.delTemplate(wx_id, template_id, this.getFrameOptr());
		return new Ajax();
	}

	@RequestMapping("weixin/template/sync")
	public Ajax sync(int wx_id) {
		this.authOptrRole(WxResId.Template_Manage);
		this.sTemplate.syncTemplate(wx_id);
		return new Ajax();
	}

	@RequestMapping("weixin/template/user/list")
	public Ajax listUser(String sql) {
		try {
			sql = URLDecoder.decode(sql, "UTF-8");
		} catch (Exception e) {
			throw new BusinessException("解码失败，输入的SQL有误，请检查！");
		}
		String v = sql.toLowerCase();
		if (v.indexOf("update ") > -1 || v.indexOf("drop ") > -1 || v.indexOf("create ") > -1
				|| v.indexOf("insert ") > -1 || v.indexOf("truncate ") > -1 || v.indexOf("delete ") > -1)
			throw new BusinessException("检查到SQL注入，禁止此操作！");
		// 统计人数
		String vSql = "select count(1) from (" + sql + ") t";
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			map.put("UserTotal", this.daoTemplate.findObject(Integer.class, vSql));
			map.put("UserArray", this.daoTemplate.listMapBySql(new QueryOrder(""), 0, 10, sql));
		} catch (Exception e) {
			throw new BusinessException(e.getMessage());
		}

		return new Ajax(map);
	}

	@RequestMapping("weixin/template/send/test")
	public Ajax testSend(int wx_id, WxTemplate template) {
		// 获取测试号

		Map<String, String> paramMap = WeiXinUtil.getWxDefine(wx_id).getParamMap();
		if (paramMap == null || !paramMap.containsKey(WxParamName.AdminWexinId))
			throw new BusinessException("未设置管理员微信号");
		if (StringHelper.isEmpty(paramMap.get(WxParamName.AdminWexinId)))
			throw new BusinessException("未设置管理员微信号！");
		for (String s : paramMap.get(WxParamName.AdminWexinId).split(",")) {
			WeiXinTemplateUtil.sendWeiXinTemplate(WeiXinUtil.getWxDefine(wx_id).getApp_id(), template, s, false);
		}

		return new Ajax();
	}

	@RequestMapping("weixin/template/send")
	public Ajax send(int wx_id, String sql, WxTemplate template) {
		this.authAdminRole();
		try {
			sql = URLDecoder.decode(sql, "UTF-8");
		} catch (Exception e) {
			throw new BusinessException("解码失败，输入的SQL有误，请检查！");
		}
		String v = sql.toLowerCase();
		if (v.indexOf("update ") > -1 || v.indexOf("drop ") > -1 || v.indexOf("create ") > -1
				|| v.indexOf("insert ") > -1 || v.indexOf("truncate ") > -1 || v.indexOf("delete ") > -1)
			throw new BusinessException("检查到SQL注入，禁止此操作！");
		List<Map<String, Object>> userArray = this.daoTemplate.listMapBySql(sql);
		new Thread(new Runnable() {
			public void run() {
				String appId = WeiXinUtil.getWxDefine(wx_id).getApp_id();
				for (Map<String, Object> map : userArray) {
					if (!map.containsKey("open_id"))
						continue;
					String open_id = map.get("open_id").toString();
					if (StringHelper.isEmpty(open_id))
						continue;
					WxTemplate sendTemplate = new WxTemplate();
					// 逐一发送
					sendTemplate.setTemplate_code(template.getTemplate_code());
					// 替换url
					sendTemplate.setTemplate_url(WeiXinTemplateUtil.replaceValues(map, template.getTemplate_url()));
					// 替换first
					sendTemplate.setContent_value(WeiXinTemplateUtil.replaceValues(map, template.getContent_value()));

					// 替换keyword1
					sendTemplate.setKeyword1_value(WeiXinTemplateUtil.replaceValues(map, template.getKeyword1_value()));

					// 替换keyword2
					sendTemplate.setKeyword2_value(WeiXinTemplateUtil.replaceValues(map, template.getKeyword2_value()));

					// 替换keyword3
					sendTemplate.setKeyword3_value(WeiXinTemplateUtil.replaceValues(map, template.getKeyword3_value()));

					// 替换keyword4
					sendTemplate.setKeyword4_value(WeiXinTemplateUtil.replaceValues(map, template.getKeyword4_value()));

					// 替换keyword5
					sendTemplate.setKeyword5_value(WeiXinTemplateUtil.replaceValues(map, template.getKeyword5_value()));
					// 替换remark
					sendTemplate.setRemark_value(WeiXinTemplateUtil.replaceValues(map, template.getRemark_value()));

					WeiXinTemplateUtil.sendWeiXinTemplate(appId, sendTemplate, open_id, false);
					//System.out.println((i++) + ":" + map.get("std_id"));
					try {
						Thread.sleep(50);
						
					}catch(Exception e) {
						
					}
				}
			}
		}).start();
		return new Ajax();
	}
}
