package com.mortals.xhx.base.system.message.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.impl.AbstractCRUDCacheServiceImpl;
import com.mortals.framework.util.DateUtils;
import com.mortals.framework.util.HttpUtil;
import com.mortals.framework.util.ThreadPool;
import com.mortals.xhx.base.system.message.MessageService;
import com.mortals.xhx.busiz.req.ApiReq;
import com.mortals.xhx.busiz.req.ApiThirdPartyReq;
import com.mortals.xhx.busiz.req.DeviceReq;
import com.mortals.xhx.busiz.rsp.ApiResp;
import com.mortals.xhx.common.code.ApiRespCodeEnum;
import com.mortals.xhx.common.code.DeviceMethodEnum;
import com.mortals.xhx.common.code.MessageTypeEnum;
import com.mortals.xhx.common.code.YesNoEnum;
import com.mortals.xhx.common.key.Constant;
import com.mortals.xhx.common.model.DefaultTbQueueMsgHeaders;
import com.mortals.xhx.common.model.MessageHeader;
import com.mortals.xhx.common.utils.SendTask;
import com.mortals.xhx.common.utils.SendTaskThreadPool;
import com.mortals.xhx.module.device.dao.DeviceDao;
import com.mortals.xhx.module.device.model.DeviceEntity;
import com.mortals.xhx.module.device.service.DeviceService;
import com.mortals.xhx.queue.*;
import com.mortals.xhx.queue.provider.TbCoreQueueProducerProvider;
import lombok.extern.apachecommons.CommonsLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.mortals.framework.util.HttpUtil.HEADER_CONTENT_TYPE;
import static com.mortals.xhx.common.key.Constant.PATH_LOGIN;
import static com.mortals.xhx.common.key.Constant.PATH_SITETREE;

/**
 * DeviceService
 * 设备 service实现
 *
 * @author zxfei
 * @date 2022-03-09
 */
@Service("messageService")
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Value("${baseplatform.httpUrl:''}")
    private String httpUrl;
    @Value("${baseplatform.loginName:''}")
    private String loginName;
    @Value("${baseplatform.password:''}")
    private String password;
    @Autowired
    private ICacheService cacheService;
    @Autowired
    private SendTaskThreadPool sendTaskThreadPool;


    @Autowired
    private TbCoreQueueProducerProvider producerProvider;

    @Override
    public void send(TopicPartitionInfo info, TbQueueMsgHeaders header, String message, TbQueueCallback callback) {
        TbQueueProducer<TbQueueMsg> producer = producerProvider.getTbCoreMsgProducer();
        TbQueueMsg queueMsg = new DefaultTbQueueMsg(IdUtil.fastSimpleUUID(), message == null ? "" : message, header);
        producer.send(info, queueMsg, callback);

    }

    @Override
    public void queueDeclare(TopicPartitionInfo info, TbQueueCallback callback) {
        TbQueueProducer<TbQueueMsg> producer = producerProvider.getTbCoreMsgProducer();
        producer.queueDeclare(info, callback);
    }

    @Override
    public void delQueue(String queue, TbQueueCallback callback) {
        TbQueueProducer<TbQueueMsg> producer = producerProvider.getTbCoreMsgProducer();
        producer.queueDel(queue, callback);
    }

    @Override
    public String getBasePlatformToken() {
        String token = cacheService.get(Constant.BASEPLATFORM_AUTHTOKEN);
        if (ObjectUtils.isEmpty(token)) {
            JSONObject obj = new JSONObject();
            obj.put("loginName", loginName);
            obj.put("password", password);
            obj.put("securityCode", "8888");
            String resp = null;
            try {
                Map<String, String> header = new HashMap<>();
                header.put(HEADER_CONTENT_TYPE, "application/json");
                resp = HttpUtil.doPost(httpUrl + PATH_LOGIN, header, JSON.toJSONString(obj));
                JSONObject jsonObject = JSON.parseObject(resp);

                Integer code = jsonObject.getInteger("code");
                if (code == YesNoEnum.YES.getValue()) {
                    JSONObject dataObj = jsonObject.getJSONObject("data");
                    String authtoken = dataObj.getString("token");
                    cacheService.setnx(Constant.BASEPLATFORM_AUTHTOKEN, authtoken, 7 * 24 * 60);
                    return authtoken;
                } else {
                    throw new AppException("异常");
                }

            } catch (Exception e) {
                log.error("异常:", e);
            }
            log.info("resp:{}", resp);
        }

        return token;
    }

    @Override
    public String siteTree() {
        String authToken = this.getBasePlatformToken();
        String resp = null;
        try {
            Map<String, String> header = new HashMap<>();
            header.put(HEADER_CONTENT_TYPE, "application/json");
            header.put("Authorization", Constant.TOKEN_PREFIX + authToken);
            resp = HttpUtil.doGet(httpUrl + PATH_SITETREE, header, new HashMap<>());
            JSONObject jsonObject = JSON.parseObject(resp);

            Integer code = jsonObject.getInteger("code");
            if (code == YesNoEnum.YES.getValue()) {
                JSONObject dataObj = jsonObject.getJSONObject("data");

                return resp;
            } else {
                throw new AppException("异常");
            }

        } catch (Exception e) {
            log.error("异常:", e);
        }
        log.info("resp:{}", resp);

        return resp;
    }

    @Override
    public ApiResp<String> sendThirdParty(String sendUrl, DeviceReq deviceReq) {
        ApiThirdPartyReq<DeviceReq> deviceReqApiReq = new ApiThirdPartyReq<>();
        deviceReqApiReq.setCode(YesNoEnum.YES.getValue());
        deviceReqApiReq.setType(MessageTypeEnum.CRUD.getValue());
        deviceReqApiReq.setData(deviceReq);
        String resp = null;
        try {
            Map<String, String> header = new HashMap<>();
            header.put(HEADER_CONTENT_TYPE, "application/json");
            log.info("\n thirdPartyUrl=>{} \n reqbody=>{} \n type=>{}",sendUrl,JSON.toJSONString(deviceReqApiReq), DeviceMethodEnum.getByValue(deviceReq.getDeviceStatus()).getDesc());
            resp = HttpUtil.doPost(sendUrl, header, JSON.toJSONString(deviceReqApiReq));
            return JSON.parseObject(resp, ApiResp.class);
        } catch (Exception e) {
            log.error("异常:", e);
        }
        return null;
    }

    @Override
    public void sendThirdParty(String sendUrl, String content) {
        SendTask sendTask = new SendTask(sendUrl, content);
        sendTaskThreadPool.execute(sendTask);
    }

}