package com.railway.business.push.task;

import com.gexin.fastjson.JSONObject;
import com.railway.business.push.domain.BusPushMsg;
import com.railway.business.push.enums.PushEnum;
import com.railway.business.push.service.IBusPushMsgService;
import com.railway.business.push.vo.GeTuiVo;
import com.railway.framework.config.ConfigurerSchedulingTask;
import com.railway.system.service.ISysConfigService;
import com.railway.system.service.ISysScheduledTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.List;

@Slf4j
@Configuration
public class AppMsgPushTask extends ConfigurerSchedulingTask {

    private final ISysConfigService configService;
    private final IBusPushMsgService busPushMsgService;
    private final ISysScheduledTaskService sysScheduledTaskService;

    public AppMsgPushTask(ISysConfigService configService, IBusPushMsgService busPushMsgService,
                          ISysScheduledTaskService sysScheduledTaskService) {
        this.configService = configService;
        this.busPushMsgService = busPushMsgService;
        this.sysScheduledTaskService = sysScheduledTaskService;
    }

    @Override
    public void taskService() {
        Integer open = this.getOpen();
        log.debug("getui task is open {}", open == 1);
        // 个推开关
        if (1 == open) {
            // 查询需要发送的消息（未推送/推送失败且小于6轮）
            List<BusPushMsg> msgPos = busPushMsgService.selectAppMsg();
            if (msgPos.size() == 0) {
                return;
            }
            Date curTime = new Date();
            for (BusPushMsg msgPo : msgPos) {
                msgPo.setPushLoop((msgPo.getPushLoop() + 1));
                msgPo.setPushTime(curTime);
                try {
                    String result = busPushMsgService.pushToSingle(msgPo);
                    //保存 解析 个推服务器的响应
                    msgPo.setPushResultDesc(result);
                    GeTuiVo geTuiVo = JSONObject.parseObject(result, GeTuiVo.class);
                    if (geTuiVo != null) {
                        if (PushEnum.GE_TUI_OK.getCode().equals(geTuiVo.getResult())) {
                            msgPo.setPushStatus(PushEnum.PUSH_STATUS_SUCCES.getCode());
                        } else {
                            msgPo.setPushStatus(PushEnum.PUSH_STATUS_ERROR_PUSH.getCode());
                        }
                    }
                } catch (Exception e) {
                    msgPo.setPushStatus(PushEnum.PUSH_STATUS_ERROR_SERVE.getCode());
                    msgPo.setPushResultDesc("个推服务器出错");
                    log.error("个推服务器出错", e);
                }
            }
            busPushMsgService.updateBatch(msgPos);
        }
    }

    @Override
    public String getCron() {
        return sysScheduledTaskService.getInfoByName("getui").getCron();
    }

    public Integer getOpen() {
        return sysScheduledTaskService.getInfoByName("getui").getOpen();
    }
}
