package com.miaxis.test;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.miaxis.JsjpApplication;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.redis.RedisCache;
import com.miaxis.common.utils.DateDeserializer;
import com.miaxis.feign.dto.WxGzhMini;
import com.miaxis.feign.dto.WxGzhSend;
import com.miaxis.feign.service.IWxSendService;
import com.miaxis.jsgzh.domain.JsgzhUser;
import com.miaxis.jsgzh.mapper.JsgzhUserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@SpringBootTest(classes = JsjpApplication.class)
@RunWith(SpringRunner.class)
public class WxGzhTest {

    @Autowired
    private JsgzhUserMapper jsgzhUserMapper;

    @Autowired
    private IWxSendService wxSendService;

    @Autowired
    private RedisCache redisCache;

    private String token;

    @Value("${gzh.appid}")
    private String appid;
    @Value("${gzh.secret}")
    private String secret;


    public String getGzhTokenService(){
        Object cacheObject = redisCache.getCacheObject(Constants.GZH_MESSAGE_TOKEN);
        //如果过期，重新获取并保存到redis
        if (cacheObject == null){
            String result = wxSendService.getAccessToken("client_credential",appid,secret);
            JSONObject json = JSONObject.parseObject(result);
            String token = json.getString("access_token");
            int expiresIn = json.getIntValue("expires_in")-1800;
            redisCache.setCacheObject(Constants.GZH_MESSAGE_TOKEN,token,expiresIn, TimeUnit.SECONDS);
            return token;
        }else {
            return String.valueOf(cacheObject);
        }
    }




    @Test
    public void getWxGzhService(){
        WxGzhSend gzhSend = new WxGzhSend();
        gzhSend.setTouser("oYiEFwrmR6tquoFPXL2KlwT8WfWU");
        gzhSend.setTemplate_id("3TKF3q46VuxrM2lsCOhs0S4-uH6UeND2FN-rJ4DUFYg");
        gzhSend.setUrl("https://mp.weixin.qq.com/s?__biz=Mzg2MTU0MzczMQ==&tempkey=MTExOF9XU0RNeHpBd2RybEh5dWlIZ0hKWXJ6QlVwRUp2RktPQ09Dekl6M0dCTE1mSFFYNmJPSm13YTdJaGl0dk5valF2VGxoYUFJY1pDaFdrQVNUNTBqRTdiR0hSN3J1cldhVUVpSi1ydm5Gd2l6Qm9sUjRqbExZdnBhVV9lWVZvdWViTmpSQlBjWTJ3RXVQYThCYkZXR2hrWDMwVW1rck5KSkw0M3JwOTZnfn4%3D&chksm=4e14c836796341201c518c5f2617004b8739b3263c5a212329115a9a74a67ad2d947f556dc08#rd");
        WxGzhMini wxGzhMini = new WxGzhMini();
//        wxGzhMini.setAppid("wx8f43db501343feab");
//        wxGzhMini.setPagepath("/pages/webview/webview?src=https://jsjp.zzxcx.net/123.jpg");
        gzhSend.setMiniprogram(wxGzhMini);

        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        JSONObject jsonObject3 = new JSONObject();
        JSONObject jsonObject4 = new JSONObject();
        jsonObject1.put("value","恭喜你购买成功！");
        jsonObject1.put("color","#173177");
        jsonObject2.put("value","巧克力");
        jsonObject3.put("value","39.8元");
        jsonObject4.put("value","这东西不错");
        jsonObject.put("first",jsonObject1);
        jsonObject.put("keyword1",jsonObject2);
        jsonObject.put("keyword2",jsonObject3);
        jsonObject.put("remark",jsonObject4);
        gzhSend.setData(jsonObject);
        token = this.getGzhTokenService();
        String result = wxSendService.sendGzhMessage(token,gzhSend);
        System.out.println(result);
    }


    @Test
    public void getWxGzhUserService() {
        token = this.getGzhTokenService();
        System.out.println(token);
        String result = wxSendService.getUser(token,"oYiEFwr-6ZMxcejakYd3lnxHQyUs");
        System.out.println(result);
        JSONObject json = JSONObject.parseObject(result);
        int count = json.getIntValue("count");
        String data = json.getString("data");
        JSONObject dataObject = JSONObject.parseObject(data);
        System.out.println(data);
        String openids = dataObject.getString("openid");
        JSONArray jsonArray = (JSONArray) JSONArray.parse(openids);
        for (int i = 0; i < count; i++) {
            String openid = jsonArray.get(i).toString();
                JsgzhUser jsgzhUser = new JsgzhUser();
                System.out.println(openid);
                jsgzhUser.setOpenid(openid);
                jsgzhUser.setIs_get(0l);
                jsgzhUserMapper.insert(jsgzhUser);
        }
    }

    @Test
    public void getUserInfo() throws IOException {
        token = this.getGzhTokenService();
        JsgzhUser jsgzhUser = new JsgzhUser();
        List<JsgzhUser> list = jsgzhUserMapper.selectJsgzhUserListNullName(jsgzhUser);
        System.out.println(list.size());
        for (JsgzhUser user: list) {
            String result = wxSendService.getUserInfo(token,user.getOpenid(),"zh_CN");
            System.out.println(result);
            ObjectMapper om = new ObjectMapper();
            JavaTimeModule javaTimeModule = new JavaTimeModule();
            // 反序列化日期格式
            javaTimeModule.addDeserializer(Date.class,new DateDeserializer());
            om.registerModule(javaTimeModule);
            om.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
            om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
            JsgzhUser jsgzhUser2 = om.readValue(result, JsgzhUser.class);
            System.out.println(jsgzhUser2);
            jsgzhUser2.setIs_get(1l);
            System.out.println(jsgzhUserMapper.updateJsgzhUserByOpenId(jsgzhUser2));
        }


    }





}

