package com.yihu.jw.base.service.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yihu.jw.base.dao.wx.*;
import com.yihu.jw.base.useragent.UserAgent;
import com.yihu.jw.entity.base.wx.*;
import com.yihu.jw.restmodel.base.wx.*;
import com.yihu.jw.restmodel.web.Envelop;
import com.yihu.jw.restmodel.web.MixEnvelop;
import com.yihu.jw.rm.base.BaseRequestMapping;
import com.yihu.jw.util.wechat.WeiXinMessageUtils;
import com.yihu.jw.utils.hibernate.HibenateUtils;
import com.yihu.jw.wechat.dao.WechatDao;
import com.yihu.jw.wechat.dao.WxTemplateConfigDao;
import com.yihu.jw.wechat.dao.WxTemplateDao;
import com.yihu.jw.wechat.service.WxAccessTokenService;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by trick on 2017/5/20
 */
@Service
@Transactional
public class WechatService {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private WechatDao wechatDao;
    @Autowired
    private WxWechatSaasDao wxWechatSaasDao;
    @Autowired
    private WxGraphicSceneDao wxGraphicSceneDao;
    @Autowired
    private WxGraphicSceneGroupDao wxGraphicSceneGroupDao;
    @Autowired
    private WxGraphicMessageDao wxGraphicMessageDao;
    @Autowired
    private WxReplySceneDao wxReplySceneDao;
    @Autowired
    private WxTemplateDao wxTemplateDao;
    @Autowired
    private WxTemplateConfigDao wxTemplateConfigDao;
    @Autowired
    private WxAccessTokenService wxAccessTokenService;
    @Autowired
    private UserAgent userAgent;
    @Autowired
    private HibenateUtils hibenateUtils;

    @Value("${wechat.flag}")
    private boolean flag;

    //====================微信与租户管理=======================

    public MixEnvelop getWxWechatList(String name,String saasName,Integer status,Integer publicType,Integer page,Integer size,String wechatId){

        String sql = "SELECT " +
                " w.id AS \"id\", " +
                " w.name as \"name\", " +
                " w.status AS \"status\", " +
                " w.type as \"type\", " +
                " w.public_type AS \"publicType\"," +
                " w.token AS \"token\"," +
                " w.enc_type AS \"encType\"," +
//                " w.type as \"type\"," +
                " w.app_id AS \"appId\"," +
                " w.app_secret AS \"appSecret\"," +
                " w.app_origin_id AS \"appOriginId\"," +
                " w.base_url AS \"baseUrl\"," +
                " w.user_name AS \"userName\"," +
                " w.password AS \"password\"," +
                " w.remark AS \"remark\"," +
                " w.create_time AS \"createTime\"," +
                " w.create_user AS \"createUser\"," +
                " w.create_user_name AS \"createUserName\"," +
                " w.update_time AS \"updateTime\"," +
                " w.update_user AS \"updateUser\"," +
                " w.update_user_name AS \"updateUserName\"" +
                " FROM " +
                " wx_wechat w ";
        if (StringUtils.isNotBlank(saasName)) {
            sql += " JOIN wx_wechat_saas s ON w.id = s.wechat_id" +
                    " JOIN base_saas bs ON s.saas_id = bs.id ";
        }
        sql += " WHERE 1=1 ";

        if (StringUtils.isNotBlank(name)) {
            sql += " AND w.`name` LIKE '%" + name + "%' ";
        }
        if (publicType!=null) {
            sql += " AND w.public_type = " + publicType + " " ;
        }
        if (status!=null) {
            sql += " AND w.`status` = " + status + " ";
        }
        if (StringUtils.isNotBlank(saasName)) {
            sql += " AND bs.`name` like '%" + saasName + "%'";
        }



        List<WxWechatVO> list =null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){

            if (flag){
                sql += " LIMIT " + (page - 1) * size + "," + size + "";
                Logger.getAnonymousLogger().info("sql="+sql);
                list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxWechatVO.class));
            }else {
                String oracleSql="SELECT\n" +
                        "\t*\n" +
                        "FROM\n" +
                        "\t(\n" +
                        "\t\tSELECT\n" +
                        "\t\t\tA .*\n" +
                        "\t\tFROM\n" +
                        "\t\t\t(";

                oracleSql+=sql;

                oracleSql+="\t\t\t) A\n" +
                        "\t\tWHERE\n" +
                        "  ROWNUM <="+page*size +
                        "\t) \n" +
                        "WHERE\n" +
                        "\tROWNUM >= "+(page-1)*size;
                Logger.getAnonymousLogger().info("oracleSql="+oracleSql);
                list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper(WxWechatVO.class));
            }

        }else {
            sql += " LIMIT " + (page - 1) * size + "," + size + "";
            Logger.getAnonymousLogger().info("sql="+sql);
            list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxWechatVO.class));
        }

        if(list!=null&&list.size()>0){
            for(WxWechatVO wx :list){
                wx.setSaas(getWxSaasVOs(wx.getId()));
            }
        }

        String countSql = "SELECT count(1) AS total"+
                " FROM " +
                " wx_wechat w ";;
        if (StringUtils.isNotBlank(saasName)) {
            countSql += " JOIN wx_wechat_saas s ON w.id = s.wechat_id" +
                    " JOIN base_saas bs ON s.saas_id = bs.id ";
        }
        countSql += " WHERE 1=1 ";
        if (StringUtils.isNotBlank(name)) {
            sql += " AND w.`name` LIKE '%" + name + "%' ";
        }
        if (publicType!=null) {
            sql += " AND w.public_type = " + publicType + " " ;
        }
        if (status!=null) {
            sql += " AND w.`status` = " + status + "";
        }
        if (StringUtils.isNotBlank(saasName)) {
            countSql += " AND bs.`name` like '%" + saasName + "%'";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(countSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString()) ;
        }

        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }

    public List<WxSaasVO> getWxSaasVOs(String id){
        String sql ="SELECT " +
                " bs.name AS \"saasName\", " +
                " bs.id AS \"saasid\"" +
                " FROM " +
                " wx_wechat_saas s " +
                " JOIN base_saas bs ON bs.id = s.saas_id " +
                " WHERE " +
                " s.wechat_id = '"+id+"'";
        List<WxSaasVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxSaasVO.class));
        return list;
    }

    public Envelop saveWxAndSaas(WxWechatDO wxWechatDO, List<WxWechatSaasDO> wxWechatSaasDOs){

        wxWechatDO.setCreateUser(userAgent.getUID());
        wxWechatDO.setCreateUserName(userAgent.getUNAME());
        wxWechatDO.setUpdateUser(userAgent.getUID());
        wxWechatDO.setUpdateUserName(userAgent.getUNAME());
        WxWechatDO wechat = wechatDao.save(wxWechatDO);

        if(wxWechatSaasDOs!=null&&wxWechatSaasDOs.size()>0){
            for(WxWechatSaasDO wxs:wxWechatSaasDOs){
                //删除该SaaS之前所以微信的关联关系
                List<WxWechatSaasDO> allsaas = wxWechatSaasDao.findBySaasId(wxs.getSaasId());
                if(allsaas!=null&&allsaas.size()>0){
                    wxWechatSaasDao.delete(allsaas);
                }

                wxs.setWechatId(wechat.getId());
            }
            wxWechatSaasDao.save(wxWechatSaasDOs);
        }
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public Envelop updateWxAndSaas(WxWechatDO wxWechatDO, List<WxWechatSaasDO> wxWechatSaasDOs) {
        //设置更新人
        wxWechatDO.setUpdateUser(userAgent.getUID());
        wxWechatDO.setUpdateUserName(userAgent.getUNAME());
        wechatDao.save(wxWechatDO);

        //删除该微信所以SaaS关联关系
        List<WxWechatSaasDO> ws = wxWechatSaasDao.findByWechatId(wxWechatDO.getId());
        wxWechatSaasDao.delete(ws);

        if(wxWechatSaasDOs!=null&&wxWechatSaasDOs.size()>0){

            for(WxWechatSaasDO wxs:wxWechatSaasDOs){

                //删除该SaaS之前所以微信的关联关系
                List<WxWechatSaasDO> allsaas = wxWechatSaasDao.findBySaasId(wxs.getSaasId());
                if(allsaas!=null&&allsaas.size()>0){
                    wxWechatSaasDao.delete(allsaas);
                }

                wxs.setWechatId(wxWechatDO.getId());
            }
            //保存现有SaaS关系
            wxWechatSaasDao.save(wxWechatSaasDOs);
        }
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public WxWechatDO findWxWechatSingle(String wechatId){
        WxWechatDO wxWechatDO = wechatDao.findOne(wechatId);
        return wxWechatDO;
    }

    public Boolean findWxWechatExist(String name){
        List<WxWechatDO> list = wechatDao.findByName(name);
        if(list!=null&&list.size()>0){
            return true;
        }
        return false;
    }


    //====================微信与租户管理end=======================

    //====================图文素材管理============================

    public MixEnvelop findWechatCombo(String saasId){
        String sql ="SELECT t.id AS \"id\",t.name as \"name\"," +
                "t.app_origin_id AS \"appOriginId\"," +
                "t.public_type AS \"publicType\" " +
                "from wx_wechat t";
        if(StringUtils.isNotBlank(saasId)){
            sql += " JOIN wx_wechat_saas s ON s.wechat_id = t.id " +
                   " WHERE s.saas_id = '"+saasId+"'";
        }
        List<WxComboVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxComboVO.class));
        return MixEnvelop.getSuccessList(BaseRequestMapping.WeChat.api_success,list);
    }


    public MixEnvelop findWechatImgGroup(String wechatId,String scene,Integer page,Integer size){

        String totalSql ="SELECT COUNT(1) AS total from wx_graphic_scene g WHERE g.wechat_id ='"+wechatId+"'";

        if(StringUtils.isNotBlank(scene)){
            totalSql+=" AND g.scene like'%"+scene+"%' ";
        }

        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }

        String sql = "SELECT " +
                " g.id as \"id\",g.wechat_id AS \"wechatId\",g.scene AS \"scene\" " +
                " FROM " +
                " wx_graphic_scene g " +
                " WHERE " +
                " g.wechat_id = '"+wechatId+"' ";

        if(StringUtils.isNotBlank(scene)){
            sql+= " AND g.scene like'%"+scene+"%'" ;
        }


        List<WxGraphicSceneVO> list=null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            String oracleSql="SELECT\n" +
                    "\t*\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\t\tSELECT\n" +
                    "\t\t\tA .*\n" +
                    "\t\tFROM\n" +
                    "\t\t\t(";

            oracleSql+=sql;

            oracleSql+="\t\t\t) A\n" +
                    "\t\tWHERE\n" +
                    "  ROWNUM <="+page*size +
                    "\t) \n" +
                    "WHERE\n" +
                    "\tROWNUM >= "+(page-1)*size;
            list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper(WxGraphicSceneVO.class));
        }else {
            sql+= " LIMIT  " + (page - 1) * size + "," + size + "";
            list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxGraphicSceneVO.class));
        }



        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }

    public Envelop createImgGroup(WxGraphicSceneDO wxGraphicSceneDO){
        wxGraphicSceneDao.save(wxGraphicSceneDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public Boolean findImgGroupExist(String wechatId,String scene){
        List<WxGraphicSceneDO> list = wxGraphicSceneDao.findByWechatIdAndScene(wechatId,scene);
        if(list!=null&&list.size()>0){
            return true;
        }
        return false;
    }

    public Envelop updateImgGroup(String id,String scene){
        WxGraphicSceneDO wxGraphicSceneDO = wxGraphicSceneDao.findOne(id);
        List<WxGraphicSceneGroupDO> list = wxGraphicSceneGroupDao.findByWechatIdAndScene(wxGraphicSceneDO.getWechatId(),wxGraphicSceneDO.getScene());

        if(list!=null&&list.size()>0){
            for(WxGraphicSceneGroupDO group:list){
                group.setScene(scene);
            }
            wxGraphicSceneGroupDao.save(list);
        }
        wxGraphicSceneDO.setScene(scene);
        wxGraphicSceneDao.save(wxGraphicSceneDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public Envelop deleteImgGroup(String id){
        WxGraphicSceneDO wxGraphicSceneDO = wxGraphicSceneDao.findOne(id);
        List<WxGraphicSceneGroupDO> list = wxGraphicSceneGroupDao.findByWechatIdAndScene(wxGraphicSceneDO.getWechatId(),wxGraphicSceneDO.getScene());
        if(list!=null&&list.size()>0){
            wxGraphicSceneGroupDao.delete(list);
        }
        wxGraphicSceneDao.delete(wxGraphicSceneDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public Envelop saveImg(WxGraphicMessageDO wxGraphicMessageDO){

        if(wxGraphicMessageDO.getId()!=null){
            wxGraphicMessageDO.setUpdateUser(userAgent.getUID());
            wxGraphicMessageDO.setUpdateUserName(userAgent.getUNAME());
        }else{
            wxGraphicMessageDO.setCreateUser(userAgent.getUID());
            wxGraphicMessageDO.setCreateUser(userAgent.getUNAME());
            wxGraphicMessageDO.setUpdateUser(userAgent.getUID());
            wxGraphicMessageDO.setUpdateUserName(userAgent.getUNAME());
        }
        wxGraphicMessageDao.save(wxGraphicMessageDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public MixEnvelop findImg(String wechatId,String title,String scene,Integer page,Integer size){

        String sqlTotal = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " wx_graphic_message m ";
                if(StringUtils.isNotBlank(scene)){
                    sqlTotal+= " JOIN wx_graphic_scene_group g ON g.graphic_id = m.id ";
                }
        sqlTotal+= " WHERE " +
                " m.wechat_id = '"+wechatId+"' " +
                " AND m.status =1" ;
                if(StringUtils.isNotBlank(title)){
                    sqlTotal += " AND m.title LIKE '%"+title+"%' " ;
                }
                if(StringUtils.isNotBlank(scene)){
                    sqlTotal+= " AND g.scene = '"+scene+"'";
                }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(sqlTotal);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString()) ;
        }

        String sql = "SELECT " +
                " m.id as \"id\", " +
                " m.wechat_id AS \"wechatId\", " +
                " m.title as \"title\", " +
                " m.description \"description\", " +
                " m.url as \"url\", " +
                " m.pic_url AS \"picUrl\", " +
                " m.status AS \"status\" " +
                " FROM " +
                " wx_graphic_message m ";
        if(StringUtils.isNotBlank(scene)){
            sql+= " JOIN wx_graphic_scene_group g ON g.graphic_id = m.id ";
        }
        sql+=" WHERE m.wechat_id = '"+wechatId+"' " +
                " AND m.status =1" ;
        if(StringUtils.isNotBlank(title)){
            sql += " AND m.title LIKE '%"+title+"%' " ;
        }
        if(StringUtils.isNotBlank(scene)){
            sql+= " AND g.scene = '"+scene+"' ORDER BY g.scene ASC ";
        }


        List<WxReplySceneVO> list=null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            String oracleSql="SELECT\n" +
                    "\t*\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\t\tSELECT\n" +
                    "\t\t\tA .*\n" +
                    "\t\tFROM\n" +
                    "\t\t\t(";

            oracleSql+=sql;

            oracleSql+="\t\t\t) A\n" +
                    "\t\tWHERE\n" +
                    "  ROWNUM <="+page*size +
                    "\t) \n" +
                    "WHERE\n" +
                    "\tROWNUM >= "+(page-1)*size;
            list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper(WxReplySceneVO.class));
        }else {
            sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
            list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxGraphicMessageVO.class));
        }

        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }

    public WxGraphicMessageDO findGraphicMessageSingle(String id){
        return wxGraphicMessageDao.findOne(id);
    }

    public Envelop saveImgGroup(List<WxGraphicSceneGroupDO> groups){
        List<WxGraphicSceneGroupDO> gs = wxGraphicSceneGroupDao.findByWechatIdAndScene(groups.get(0).getWechatId(),groups.get(0).getScene());
        if(gs!=null&&gs.size()>0){
            wxGraphicSceneGroupDao.delete(gs);
        }
        wxGraphicSceneGroupDao.save(groups);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public Envelop deleteImgGroupRelation(String wechatId,String scene,String imgId){
        WxGraphicSceneGroupDO wxGraphicSceneGroupDO = wxGraphicSceneGroupDao.findByWechatIdAndSceneAndGraphicId(wechatId,scene,imgId);
        wxGraphicSceneGroupDao.delete(wxGraphicSceneGroupDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public Envelop saveWxReplyScene(WxReplySceneDO wxReplySceneDO){

        if(StringUtils.isNotBlank(wxReplySceneDO.getDefaultReply())){
           List<WxReplySceneDO> list = wxReplySceneDao.findByWechatIdAndDefaultReply(wxReplySceneDO.getWechatId(),wxReplySceneDO.getDefaultReply());
            if(list!=null&&list.size()>0){
                wxReplySceneDao.delete(list);
            }
        }

        wxReplySceneDO.setCreateUser(userAgent.getUID());
        wxReplySceneDO.setCreateUserName(userAgent.getUNAME());
        wxReplySceneDO.setCreateTime(new Date());
        wxReplySceneDO.setUpdateUser(userAgent.getUID());
        wxReplySceneDO.setUpdateUserName(userAgent.getUNAME());
        wxReplySceneDO.setUpdateTime(new Date());

        wxReplySceneDao.save(wxReplySceneDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public WxReplySceneDO findDefaultReply(String wechatId){
        List<WxReplySceneDO> list = wxReplySceneDao.findByWechatIdAndDefaultReply(wechatId, WeiXinMessageUtils.RESP_MESSAGE_DEFAULT);
        if(list!=null&&list.size()>0){
            return list.get(0);
        }
       return null;
    }

    public Map<String,Object> findWxReplySceneExist(String wechatId,String msgType,String event,String content,String scene){
        Map<String,Object> map = new HashedMap();

        if("text".equals(msgType)){
            List<WxReplySceneDO> wxReplySceneDOs =wxReplySceneDao.findByWechatIdAndMsgTypeAndContentAndStatus(wechatId,msgType,content,1);
            if(wxReplySceneDOs!=null&&wxReplySceneDOs.size()>0){
                map.put("status",-1);
                map.put("mes","文本回复已经存在！");
            }else{
                map.put("status",1);
                map.put("mes","事件验证成功！");
            }
        }else{
            //关注事件类型只能有一条事件配置
            if("subscribe".equals(event)){
                List<WxReplySceneDO> wxReplySceneDOs =wxReplySceneDao.findByWechatIdAndMsgTypeAndEventAndStatus(wechatId,msgType,event,1);
                if(wxReplySceneDOs!=null&&wxReplySceneDOs.size()>0){
                    map.put("status",-2);
                    map.put("mes","关注事件已经配置！");
                }else{
                    map.put("status",1);
                    map.put("mes","事件验证成功！");
                }
            }else{
                //点击事件，扫码事件
                List<WxReplySceneDO> wxReplySceneDOs =wxReplySceneDao.findByWechatIdAndMsgTypeAndEventAndSceneAndStatus(wechatId,msgType,event,scene,1);
                if(wxReplySceneDOs!=null&&wxReplySceneDOs.size()>0){
                    map.put("status",-3);
                    map.put("mes","事件图文分组已经配置！");
                }else{
                    map.put("status",1);
                    map.put("mes","事件验证成功！");
                }
            }
        }

        return map;
    }

    public MixEnvelop findWxReplyScene(String wechatId,String msgType,String event,String content,Integer status,Integer page,Integer size){
        String totalSql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " wx_reply_scene s " +
                " WHERE " +
                " s.wechat_id = '"+wechatId+"' " +
                " AND s.default_Reply is null ";
        if(StringUtils.isNotBlank(msgType)){
            totalSql += " AND s.msg_type ='"+msgType+"'";
        }
        if(StringUtils.isNotBlank(event)){
            totalSql += " AND s.event ='"+event+"'";
        }
        if(StringUtils.isNotBlank(content)){
            totalSql += " AND s.content like '%"+content+"%'";
        }
        if(status!=null){
            totalSql += " AND s.status = "+status;
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count =Long.parseLong(rstotal.get(0).get("total").toString()) ;
        }

        String sql = "SELECT " +
                " s.id AS \"id\"," +
                " s.wechat_id AS \"wechatId\"," +
                " s.scene AS \"scene\", " +
                " s.status as \"status\", " +
//                " s.id as \"id\", " +
                " s.content as \"content\", " +
                " s.app_origin_id AS \"appOriginId\", " +
                " s.event as \"event\", " +
                " s.msg_type AS \"msgType\"" +
                " FROM " +
                " wx_reply_scene s " +
                " WHERE " +
                " s.wechat_id = '"+wechatId+"'" +
                " AND s.default_Reply is null ";
        if(StringUtils.isNotBlank(msgType)){
            sql += " AND s.msg_type ='"+msgType+"'";
        }
        if(StringUtils.isNotBlank(event)){
            sql += " AND s.event ='"+event+"'";
        }
        if(StringUtils.isNotBlank(content)){
            sql += " AND s.content like '%"+content+"%'";
        }
        if(status!=null){
            sql += " AND s.status = "+status;
        }

        List<WxReplySceneVO> list=null;
        if ("xm_ykyy_wx".equalsIgnoreCase(wechatId)){
            String oracleSql="SELECT\n" +
                    "\t*\n" +
                    "FROM\n" +
                    "\t(\n" +
                    "\t\tSELECT\n" +
                    "\t\t\tA .*\n" +
                    "\t\tFROM\n" +
                    "\t\t\t(";

            oracleSql+=sql;

            oracleSql+="\t\t\t) A\n" +
                    "\t\tWHERE\n" +
                    "  ROWNUM <="+page*size +
                    "\t) \n" +
                    "WHERE\n" +
                    "\tROWNUM >= "+(page-1)*size;
            list = jdbcTemplate.query(oracleSql, new BeanPropertyRowMapper(WxReplySceneVO.class));
        }else {
            sql+=" ORDER BY s.create_time DESC LIMIT  " + (page - 1) * size + "," + size + "";
            list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxReplySceneVO.class));
        }

        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }


    //===================图文素材管理end====================================

    //===================模板消息==========================================

    public Envelop saveWxTemp(WxTemplateDO wxTemplateDO){

        if(wxTemplateDO.getId()!=null){
            wxTemplateDO.setUpdateUser(userAgent.getUID());
            wxTemplateDO.setUpdateUserName(userAgent.getUNAME());
        }else{
            wxTemplateDO.setCreateUser(userAgent.getUID());
            wxTemplateDO.setCreateUserName(userAgent.getUNAME());
            wxTemplateDO.setUpdateUser(userAgent.getUID());
            wxTemplateDO.setUpdateUserName(userAgent.getUNAME());
        }

        wxTemplateDao.save(wxTemplateDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public Boolean findWxTempExist(String wechatId,String templateId,String templateName){
        List<WxTemplateDO> list = wxTemplateDao.findByTemplateIdAndWechatIdAndStatus(templateId,wechatId,1);
        if(list!=null&&list.size()>0){
            return true;
        }
        List<WxTemplateDO> list2 = wxTemplateDao.findByTemplateNameAndWechatIdAndStatus(templateName,wechatId,1);
        if(list2!=null&&list2.size()>0){
            return true;
        }
        return false;
    }

    public Boolean findWxTempNameExist(String wechatId,String templateName){
        List<WxTemplateDO> list2 = wxTemplateDao.findByTemplateNameAndWechatIdAndStatus(templateName,wechatId,1);
        if(list2!=null&&list2.size()>0){
            return true;
        }
        return false;
    }

    public MixEnvelop findWxtemp(String wechatId,Integer status,String name,String key,Integer page,Integer size){
        String totalSql = "SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " wx_template t" +
                " WHERE t.wechat_id= '"+wechatId+"' ";
        if(status!=null){
            totalSql+= " AND t.status = "+ status;
        }
        if(StringUtils.isNotBlank(name)){
            totalSql+= " AND t.template_name ='"+name+"'";
        }
        if(StringUtils.isNotBlank(key)){
            totalSql+= " AND (t.template_id ='"+key+"' OR t.title like'%"+key+"%')";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString()) ;
        }

        String sql = "SELECT " +
                " t.id as \"id\", " +
                " t.title AS \"title\", " +
                " t.wechat_id AS \"wechatId\", " +
                " t.template_id AS \"templateId\", " +
                " t.template_name AS \"templateName\", " +
                " t.content as \"content\", " +
                " t.status as \"status\" " +
                " FROM " +
                " wx_template t" +
                " WHERE t.wechat_id= '"+wechatId+"' ";
        if(status!=null){
            sql+= " AND t.status = "+ status;
        }
        if(StringUtils.isNotBlank(name)){
            sql+= " AND t.template_name ='"+name+"'";
        }
        if(StringUtils.isNotBlank(key)){
            sql+= " AND (t.template_id ='"+key+"' OR t.title like'%"+key+"%')";
        }
        sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
        List<WxTemplateVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxTemplateVO.class));
        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }

    public Envelop saveWxTempConfig(WxTemplateConfigDO wxTemplateConfigDO){

        if(wxTemplateConfigDO.getId()!=null){
            wxTemplateConfigDO.setUpdateUser(userAgent.getUID());
            wxTemplateConfigDO.setUpdateUserName(userAgent.getUNAME());
        }else{
            wxTemplateConfigDO.setCreateUser(userAgent.getUID());
            wxTemplateConfigDO.setUpdateUserName(userAgent.getUNAME());
            wxTemplateConfigDO.setUpdateUser(userAgent.getUID());
            wxTemplateConfigDO.setUpdateUserName(userAgent.getUNAME());
        }
        wxTemplateConfigDao.save(wxTemplateConfigDO);
        return Envelop.getSuccess(BaseRequestMapping.WeChat.api_success);
    }

    public MixEnvelop findWxTempConfigList(String wechatId,String templateId,String scene,Integer page,Integer size){
        String totalSql ="SELECT " +
                " COUNT(1) AS \"total\" " +
                " FROM " +
                " wx_template_config g " +
                " WHERE " +
                " g.wechat_id ='"+wechatId+"'";
        if(StringUtils.isNotBlank(scene)){
            totalSql += " AND g.scene = '"+scene+"'";
        }
        if(StringUtils.isNotBlank(templateId)){
            totalSql += " AND g.template_id = '"+templateId+"'";
        }
        List<Map<String, Object>> rstotal = jdbcTemplate.queryForList(totalSql);
        Long count = 0L;
        if (rstotal != null && rstotal.size() > 0) {
            count = Long.parseLong(rstotal.get(0).get("total").toString());
        }

        String sql ="SELECT " +
                " g.id as \"id\", " +
                " g.wechat_id AS \"wechatId\", " +
                " g.template_id AS \"templateId\", " +
                " g.template_name AS \"template_name\", " +
                " g.scene AS \"scene\", " +
                " g.scene_description AS \"sceneDescription\", " +
                " g.first AS \"first\", " +
                " g.url AS \"url\", " +
                " g.remark AS \"remark\", " +
                " g.keyword1 AS \"keyword1\", " +
                " g.keyword2 AS \"keyword2\", " +
                " g.keyword3 AS \"keyword3\", " +
                " g.keyword4 AS \"keyword4\", " +
                " g.keyword5 AS \"keyword5\", " +
                " g.keyword6 AS \"keyword6\", " +
                " g.keyword7 AS \"keyword7\", " +
                " g.create_time AS \"createTime\", " +
                " g.create_user AS \"createUser\", " +
                " g.create_user_name AS \"createUserName\", " +
                " g.update_time AS \"updateTime\", " +
                " g.update_user AS \"updateUser\", " +
                " g.update_user_name AS \"updateUserName\", " +
                " g.status AS \"status\"" +
                " FROM " +
                " wx_template_config g " +
                " WHERE " +
                " g.wechat_id ='"+wechatId+"'";
        if(StringUtils.isNotBlank(scene)){
            sql += " AND g.scene = '"+scene+"'";
        }
        if(StringUtils.isNotBlank(templateId)){
            sql += " AND g.template_id = '"+templateId+"'";
        }
        sql+=" LIMIT  " + (page - 1) * size + "," + size + "";
        List<WxTemplateConfigVO> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper(WxTemplateConfigVO.class));
        return MixEnvelop.getSuccessListWithPage(BaseRequestMapping.WeChat.api_success, list, page, size, count);
    }

    public WxTemplateConfigDO findWxTemplateConfig(String wechatId,String name,String scene){
        WxTemplateConfigDO wxTemplateConfigDO =  wxTemplateConfigDao.findByWechatIdAndTemplateNameAndScene(wechatId,name,scene);
        return wxTemplateConfigDO;
    }

    public Boolean findWxTemplateConfigExist(String wechatId,String scene){
        List<WxTemplateConfigDO> list =  wxTemplateConfigDao.findByWechatIdAndScene(wechatId,scene);
        if(list!=null&&list.size()>0){
            return true;
        }
        return false;
    }

    //===================模板消息end=======================================

    //===================微信统计==========================================


    public StatisticsTitleVO getFansTitle(String wechatId,String date){

        StatisticsTitleVO statisticsTitleVO = new StatisticsTitleVO();
        //获取统计增量
        String url ="https://api.weixin.qq.com/datacube/getusersummary?access_token="+wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken();
        String param = "{ \n" +
                "    \"begin_date\": \""+date+"\", \n" +
                "    \"end_date\": \""+date+"\"\n" +
                "}";

        String result = com.yihu.jw.util.wechat.wxhttp.HttpUtil.sendPost(url, param);

        JSONObject rs = JSON.parseObject(result);
        JSONArray list = rs.getJSONArray("list");

        if(list!=null&&list.size()>0&&!list.isEmpty()){
            JSONObject info = (JSONObject)list.get(0);
            Integer new_user = info.getInteger("new_user");
            Integer cancel_user = info.getInteger("cancel_user");
            Integer add_user = new_user-cancel_user;
            statisticsTitleVO.setNew_user(new_user);
            statisticsTitleVO.setCancel_user(cancel_user);
            statisticsTitleVO.setAdd_user(add_user);
        }
        //获取统计总量
        String url2 ="https://api.weixin.qq.com/datacube/getusercumulate?access_token="+wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken();
        String param2 = "{ \n" +
                "    \"begin_date\": \""+date+"\", \n" +
                "    \"end_date\": \""+date+"\"\n" +
                "}";
        String result2 = com.yihu.jw.util.wechat.wxhttp.HttpUtil.sendPost(url2, param2);

        JSONObject rs2 = JSON.parseObject(result2);
        JSONArray list2 = rs2.getJSONArray("list");
        if(list2!=null&&list2.size()>0&&!list2.isEmpty()){
            JSONObject info = (JSONObject)list2.get(0);
            Integer cumulate_user = info.getInteger("cumulate_user");
            statisticsTitleVO.setCumulate_user(cumulate_user);
        }

        return statisticsTitleVO;
    }

    public JSONObject getusersummary(String wechatId,String beginDate,String endDate){

        String url ="https://api.weixin.qq.com/datacube/getusersummary?access_token="+wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken();
        //          "https://api.weixin.qq.com/datacube/getusersummary?access_token=ACCESS_TOKEN"

        JSONObject paramJson = new JSONObject();

        paramJson.put("begin_date",beginDate);
        paramJson.put("end_date",endDate);


        String result = com.yihu.jw.util.wechat.wxhttp.HttpUtil.sendPost(url, paramJson.toJSONString());
        JSONObject rs = JSON.parseObject(result);
        return rs;
    }

    public JSONObject getusercumulate(String wechatId,String beginDate,String endDate){

        String url ="https://api.weixin.qq.com/datacube/getusercumulate?access_token="+wxAccessTokenService.getWxAccessTokenById(wechatId).getAccessToken();
        JSONObject paramJson = new JSONObject();

        paramJson.put("begin_date",beginDate);
        paramJson.put("end_date",endDate);

        String result = com.yihu.jw.util.wechat.wxhttp.HttpUtil.sendPost(url, paramJson.toJSONString());
        JSONObject rs = JSON.parseObject(result);
        return rs;
    }

    //===================微信统计end=======================================

}
