package com.mortals.xhx.thread;


import cn.hutool.core.net.url.UrlBuilder;
import com.alibaba.fastjson.JSON;
import com.mortals.framework.ap.GlobalSysInfo;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.util.AbstractThread;
import com.mortals.xhx.base.system.message.MessageService;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.DeviceMethodEnum;
import com.mortals.xhx.common.pdu.DeviceReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

import static com.mortals.xhx.common.key.Constant.PARAM_SERVER_PHP_IN_HTTP_URL;
import static com.mortals.xhx.common.key.RedisKey.KEY_DEVICE_THIRDPARTY_QUEUE;


/**
 * 发送第三方服务线程
 *
 * @author zxfei
 */
@Slf4j
@Service
@Order(value = 2)
public class SendThirdPartyThread extends AbstractThread {

    @Autowired
    private ICacheService cacheService;
    @Autowired
    private MessageService messageService;

    @Value("${thirdPartyPath:/inter/device/deviceIn}")
    public String thirdPartyPath;

    @Override
    protected int getSleepTime() {
        return 1000;
    }

    @Override
    protected void process() {
        //  log.info("SendThirdPartyThread process");
        List<DeviceReq> deviceMsgReqs = new ArrayList<>();
        while (true) {
            DeviceReq deviceReq = cacheService.lpop(KEY_DEVICE_THIRDPARTY_QUEUE, DeviceReq.class);
            if (ObjectUtils.isEmpty(deviceReq)) {
                // log.info("deviceMsgReq:{}", deviceMsgReq == null);
                break;
            }
            deviceMsgReqs.add(deviceReq);
        }
        if (!ObjectUtils.isEmpty(deviceMsgReqs)) {
            for (DeviceReq deviceMsgReq : deviceMsgReqs) {
                String phpInUrl = GlobalSysInfo.getParamValue(PARAM_SERVER_PHP_IN_HTTP_URL, "http://127.0.0.1:11078/zwfw_api");
                ApiResp<String> resp = messageService.sendThirdParty(UrlBuilder.of(phpInUrl).addPath(thirdPartyPath).build(), deviceMsgReq);
                log.info("sendThirty req==>{} TYPE:{} \n resp ==>{}", JSON.toJSONString(deviceMsgReq), DeviceMethodEnum.getByValue(deviceMsgReq.getDeviceStatus()).getDesc(), JSON.toJSONString(resp));
            }
        }
    }


    @Override
    protected void threadClosed() {
        // TODO Auto-generated method stub
        super.close();
    }


}
