package com.iformall.schedule;

import com.alibaba.fastjson.JSONObject;
import com.iformall.domain.po.WxWiWideInfo;
import com.iformall.exception.MallinkException;
import com.iformall.mapper.WxWiwideInfoMapper;
import com.iformall.utils.WiwideUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;

/**
 * @author gongbiao
 */
@Component
public class WiwideTokenSchedule {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxWiwideInfoMapper wxWiwideInfoMapper;

    //@Scheduled(cron = "0 0 * * * ?")
    public void requestToken() {
        List<WxWiWideInfo> list = wxWiwideInfoMapper.findList(null);
        for (int i = 0, size = list.size(); i < size; i++) {
            WxWiWideInfo wxWiWideInfo = list.get(i);
            logger.info("WiwideTokenSchedule>>>>wiwideinfo:"+JSONObject.toJSONString(wxWiWideInfo));
            String data = WiwideUtil.queryToken(wxWiWideInfo);
            logger.info("WiwideTokenSchedule>>>>bid:"+wxWiWideInfo.getWiwideId()+",newdata:"+data);
            String token = (String) JSONObject.parseObject(data).get("data");
            if(token==null){
                logger.error("WiwideTokenSchedule>>>商场:"+wxWiWideInfo.getTenantId()+",token为空");
                continue;
            }
            updateToken(wxWiWideInfo, token);
        }

    }

    private void updateToken(WxWiWideInfo wxWiWideInfo, String token) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, 45);
        logger.info("WiwideTokenSchedule>>>数据表中的数据："+JSONObject.toJSONString(wxWiWideInfo));
        WxWiWideInfo record = new WxWiWideInfo();
        record.setId(wxWiWideInfo.getId());
        record.setToken(token);
        record.setExpiredTime(instance.getTime());
        try {
            logger.info("WiwideTokenSchedule>>>>要更新的数据before>>>>>>>>>>"+JSONObject.toJSONString(record));
            wxWiwideInfoMapper.updateToken(record);
            logger.info("要更新的数据after>>>>>>>>>>"+JSONObject.toJSONString(record));
        } catch (MallinkException e) {
            logger.error("WiwideTokenSchedule>>>>更新TOKEN失败：商场" + wxWiWideInfo.getTenantId());
        }
    }


}