package thyyxxk.webserver.scheduled;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import thyyxxk.webserver.entity.WeComTokens;
import thyyxxk.webserver.service.externalhttp.CorpWxSrvc;
import thyyxxk.webserver.utils.Md5Util;
import thyyxxk.webserver.utils.TokenUtil;


@Slf4j
@Component
public class FetchAccessTokenTask {
    private final CorpWxSrvc srvc;

    private static final String USERINFO_SECRET = "wpHuNePfiDyotmpXjy5hUYGF0w8Ks5OPHSQp22z8oBk";
    private static final String CLOCKIN_SECRET = "_DodO23wewvESf-Lt-K46O2OsZ_nwrNhCbGaj0gbFjQ";
    private static final String HRG_SECRET = "xYHIiJldL1cn5-RbsyV2VIq505_22_3JY-U_gYpQ4hE";


    private final static String LIS_DOCK_APP_ID = "jkzd5e26bf01c5a0d79";
    private final static String LIS_DOCK_SECRET = "957a642f1dae09fd226a3517a465";

    private static volatile boolean TOKEN_SYNCED = false;

    @Autowired
    public FetchAccessTokenTask(CorpWxSrvc srvc) {
        this.srvc = srvc;
    }

    @Scheduled(fixedRate = 6900 * 1000)
    public void getAccessToken() {
        JSONObject json = srvc.fetchAccessToken(USERINFO_SECRET);
        String weComAddressBookToken = json.getString("access_token");
        log.info("获取企业微信通讯录ACCESS_TOKEN: {}", weComAddressBookToken);
        TokenUtil.setWeComAddressBookToken(weComAddressBookToken);

        json = srvc.fetchAccessToken(CLOCKIN_SECRET);
        String weComClockInToken = json.getString("access_token");
        log.info("获取企业微信打卡数据ACCESS_TOKEN: {}", weComClockInToken);
        TokenUtil.setWeComClockInToken(weComClockInToken);

        json = srvc.fetchAccessToken(HRG_SECRET);
        String weComSendMsgToken = json.getString("access_token");
        log.info("获取企业微信紧急消息推送ACCESS_TOKEN: {}", weComSendMsgToken);
        TokenUtil.setWeComSendMsgToken(weComSendMsgToken);

        if (!TOKEN_SYNCED) {
            WeComTokens tokens = new WeComTokens(weComAddressBookToken, weComClockInToken, weComSendMsgToken);
            String updateTokensResult = srvc.syncTokens(tokens);
            log.info("同步线上环境企业微信tokens: {}", updateTokensResult);
            TOKEN_SYNCED = true;
        }
    }

    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void doSign() {
        String[] sign = new String[2];
        sign[0] = String.valueOf(System.currentTimeMillis());
        String ori = LIS_DOCK_APP_ID + sign[0] + LIS_DOCK_SECRET;
        sign[1] = Md5Util.encrypt(Md5Util.encrypt(ori));
        TokenUtil.setLisDockSign(sign);
        log.info("获取健康证对接签名：【{},{}】", sign[0], sign[1]);
    }
}
