package com.ssm.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ssm.manage.dto.SendData;
import com.ssm.manage.dto.StoreWechatDto;
import com.ssm.manage.dto.WxPushMessage;
import com.ssm.manage.entity.BaseStores;
import com.ssm.manage.entity.StoreWechat;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.service.SsmBaseStoreService;
import com.ssm.manage.service.StoreWechatService;
import com.ssm.manage.utils.AjaxResult;
import com.ssm.manage.utils.WxHelper;
import com.ssm.manage.utils.XmlUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author 杨敬一
 * @date 2020-01-07
 */
@RestController
@RequestMapping("/sys")
public class WxController {

    private static final Logger log = LoggerFactory.getLogger(WxController.class);

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private StoreWechatService storeWechatService;



    @GetMapping("/send")
    @ResponseBody
    public Map<String, Object> send(HttpSession session){

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("touser","oBxBQ6Jd5pJL3LoqGGteYoDSDoTE");
        hashMap.put("template_id","05DNtwB1aVSvCKvftU00XnzVX8daAbGwBWSLqbN_4-w");
        //hashMap.put("url","");  //非必填
        //hashMap.put("miniprogram",null); //非必填
        //现在封装data-> SendData
        //创建data的对象map
        Map<String, Object> data = new HashMap<>();
        SendData firstData = new SendData();
        firstData.setValue("隔壁老王");
        data.put("first",firstData);
        SendData keyword1 = new SendData();
        keyword1.setValue("艹");
        data.put("keyword1",keyword1);
        hashMap.put("data",data);
        String o =  JSONObject.toJSONString(hashMap);
        log.info("hashMap:==================== ,{}",hashMap);
        log.info("String:====================,{}",o);
        WxHelper.send(hashMap,session);
        return hashMap;
    }

    /**
     * 生成需要关注的二维码
     */
    @GetMapping("/makeQr")
    @ResponseBody
    //@Scheduled(cron = "1 * * * * ? *")//每周日凌晨一点执行一次
    public AjaxResult makeQr(@RequestParam("storeId") Long storeId, HttpSession session){
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        List<BaseStores> collect = pagesorganizations.stream().filter(baseStores -> null == baseStores.getParentId()).collect(Collectors.toList());
        StoreWechatDto storeWechatDto = new StoreWechatDto();
        storeWechatDto.setStoreId(collect.get(0).getId());
        storeWechatDto.setPageNum(1);
        storeWechatDto.setPageSize(10);

        PageInfo<StoreWechat> storeWechatPageInfo = storeWechatService.queryByPage(storeWechatDto);
        List<StoreWechat> list = storeWechatPageInfo.getList();
        StoreWechat storeWechat = null;
        if (list.isEmpty()){
            storeWechat= list.get(0);
        }

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("13113357477");
        if (null!=storeWechat){
            stringBuilder.append(storeWechat.getIphone());
        }


        String qRcodeUrl = WxHelper.makeQRcodeByPhone(String.valueOf(stringBuilder),session);
        return AjaxResult.success(qRcodeUrl);
    }

    @Scheduled(cron = "0 0 04 ? * MON")//每周日凌晨一点执行一次
    public void makeQrs(){
        String qRcodeUrl = WxHelper.makeQRcodeByPhone(null,null);
//        return AjaxResult.success(qRcodeUrl);
    }

    /**
     * 微信服务器 对 微信公众号管理平台的 服务器地址(URL) 进行校验
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/wx")
    @ResponseBody
    public String firstWxVerify(@RequestParam(value="signature",required=false) String signature,
                                @RequestParam(value="timestamp",required=false) String timestamp,
                                @RequestParam(value="nonce",required=false) String nonce,
                                @RequestParam(value="echostr",required=false) String echostr){
        System.out.println(" 微信服务端返回的数据 用于校验 微信配置中心的网址是否正确: >>>" + signature + "\t" + timestamp + "\t" + nonce + "\t" + echostr);
        log.info("开始签名验证："+" PARAM VAL: >>>" + signature + "\t" + timestamp + "\t" + nonce + "\t" + echostr);
        if (StringUtils.isNotEmpty(signature) && StringUtils.isNotEmpty(timestamp)
                &&StringUtils.isNotEmpty(nonce) && StringUtils.isNotEmpty(echostr)) {
            String sTempStr = "";
            if (StringUtils.isNotEmpty(signature) ) {
                log.info("验证成功：-----------："+sTempStr);
                return echostr;
            } else {
                log.info("验证失败：-----------：00000");
                return "-1";
            }
        } else {
            log.info("验证失败：-----------：11111");
            return "-1";
        }
    }


    /**
     * //微信方回调
     * @param body 微信回调传送的参数
     * @return String  返回一个空串告诉微信服务器 接受到了响应
     */
    @PostMapping("/wx")
    @ResponseBody
    public String wxCallBack(@RequestBody String body){
        //接受到微信的数据后解析为javabean
        WxPushMessage wxPushMessage = (WxPushMessage) XmlUtil.fromXML(body,WxPushMessage.class);
        System.out.println("=========wxPushMessage==========="+wxPushMessage);
        if(null != wxPushMessage){
            //开发者微信号
            String toUserName = wxPushMessage.getToUserName();
            //FromUserName
            String fromUserName = wxPushMessage.getFromUserName();
            //消息创建时间 （整型）
            Long createTime = wxPushMessage.getCreateTime();
            //消息类型，event
            String msgType = wxPushMessage.getMsgType();
            // 事件类型，subscribe->订阅  unsubscribe取消
            String event = wxPushMessage.getEvent();
            // 事件KEY值，qrscene_为前缀，后面为二维码的参数值
            String eventKey = wxPushMessage.getEventKey();
            //表示消息推送类型是订阅 SCAN消息推送类型是  之前关注过
            if(null != event && ("subscribe".equals(event) || "SCAN".equals(event))){
                // eventKey  之前传递的值  phone
                //TODO  关于重试的消息排重，推荐使用FromUserName + CreateTime 排重。
               // 更新数据库 将openid 和 phone绑定

                return "";
            }else if(null != event && "unsubscribe".equals(event)){//消息推送类型是 取消订阅
                // 更新数据库 将openid 和 phone解除绑定

                return "";
            }else {
                return "";
            }
        }else {
            return "";
        }
    }
}
