/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.feesapi.wxgl.wechatbasicmgt.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.feesapi.common.wechat.UserListJsonResult;
import com.tofly.feesapi.common.wechat.WxPayConfig;
import com.tofly.feesapi.common.wechat.Wxapi;
import com.tofly.feesapi.wxgl.wechatbasicmgt.entity.WxMessage;
import com.tofly.feesapi.wxgl.wechatbasicmgt.entity.WxToken;
import com.tofly.feesapi.wxgl.wechatbasicmgt.entity.WxTstz;
import com.tofly.feesapi.wxgl.wechatbasicmgt.mapper.WxTstzMapper;
import com.tofly.feesapi.wxgl.wechatbasicmgt.service.WxTokenService;
import com.tofly.feesapi.wxgl.wechatbasicmgt.service.WxTstzService;
import com.tofly.feesapi.wxgl.wechatbasicmgt.service.WxUserLsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 微信推送停水通知
 *
 * @author sxb
 * @date Mon Jun 05 00:00:00 CST 2023
 */
@Service("wxTstzService")
public class WxTstzServiceImpl extends ServiceImpl<WxTstzMapper, WxTstz> implements WxTstzService {

    @Autowired
    private WxTokenService wxTokenService;

    @Override
    public List<String> wx_send(WxTstz wxTsTz) {
        WxPayConfig wxPayConfig = new WxPayConfig();

        //region 获取accessToken和expiresdate，openid
        WxToken wxToken = wxTokenService.getById(wxPayConfig.getAPPID());
        String accessToken = wxToken.getAccessToken();
        Date expiresDate = wxToken.getExpiresdate();

        int resultcount = 10000;
        String nextopenid = "";
        List<String> listpenid = new ArrayList<>();
        //int j = 2;
        while (resultcount >= 10000) {
            Date date = new Date();
            // 判断access_token是否在有效期内,无效重新获取
            if (date.compareTo(expiresDate) >= 0 || accessToken == "") {

                Map<String, String> map = Wxapi.GetAccessToken();
                accessToken = map.get("accessToken");
                if (accessToken != "") {
                    long currentTime = System.currentTimeMillis();
                    currentTime += 120 * 60 * 1000;
                    expiresDate = new Date(currentTime);
                    wxToken.setAccessToken(accessToken);
                    wxToken.setExpiresdate(expiresDate);
                    wxTokenService.updateById(wxToken);
                } else {
                    break;
                }

            }
            UserListJsonResult userlist = Wxapi.GetUserList(accessToken, nextopenid);
            if (userlist != null && userlist.data != null) {
                listpenid.addAll(userlist.data.openid);
                resultcount = userlist.count;
                nextopenid = userlist.next_openid;

            } else {
                break;
            }

        }
        return listpenid;
    }
}
