package com.kxs.product.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.mq.handlers.IMQSender;
import com.kxs.product.api.model.KxsGdReport;
import com.kxs.product.api.req.gd.GdQueryCardOrderReq;
import com.kxs.product.api.res.gd.GdCommRes;
import com.kxs.product.api.res.gd.GdQueryOrderRes;
import com.kxs.product.api.amqp.rabbit.RabbitGdActQueueMQ;
import com.kxs.product.biz.config.RsaProperties;
import com.kxs.product.biz.constant.enums.GdReportEnum;
import com.kxs.product.biz.mapper.KxsGdReportMapper;
import com.kxs.product.biz.service.KxsGdService;
import com.kxs.product.biz.util.GdRsaUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * KXS 广电 服务实现
 *
 * @author 没秃顶的码农
 * @date 2024-04-23
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class KxsGdServiceImpl implements KxsGdService {

    private final RsaProperties rsaProperties;

    private final KxsGdReportMapper kxsGdReportMapper;

    private final IMQSender mqSender;

    @Async("getAsyncExecutor")
    @Override
    public void checkGdAsyncData(String startTime, String endTime) {
        int pageNo = 1;
        int pageSize = 50;

        do {
            List<GdQueryOrderRes.GdQueryOrder> list = this.queryCardOrders(startTime, endTime, pageNo, pageSize);
            if (list.isEmpty()) {
                pageNo = -1;
            } else {
                for (GdQueryOrderRes.GdQueryOrder gdQueryOrder : list) {
                    if ("已激活".equals(gdQueryOrder.getActivationStatusName())) {
                        KxsGdReport kxsGdReport = kxsGdReportMapper.selectOne(Wrappers.<KxsGdReport>lambdaQuery()
                                .eq(KxsGdReport::getIsCheck, GdReportEnum.CHECK_NO.getType())
                                .eq(KxsGdReport::getGdSn, gdQueryOrder.getIccId())
                                .eq(KxsGdReport::getGdMobile, gdQueryOrder.getPhoneNo()));
                        if (kxsGdReport != null) {
                            //发送广电激活MQ消息
                            RabbitGdActQueueMQ.MsgEntity msgEntity = new RabbitGdActQueueMQ.MsgEntity();
                            BeanUtil.copyProperties(gdQueryOrder, msgEntity);
                            mqSender.send(RabbitGdActQueueMQ.build(msgEntity));

                            kxsGdReportMapper.update(null, Wrappers.<KxsGdReport>lambdaUpdate().eq(KxsGdReport::getId, kxsGdReport.getId())
                                    .set(KxsGdReport::getIsCheck, GdReportEnum.CHECK_SUC.getType())
                                    .set(KxsGdReport::getGdMobile, gdQueryOrder.getPhoneNo()));
                            log.info("发送广电激活数据{}", kxsGdReport.getGdSn()
                                    + "," + kxsGdReport.getGdMobile());
                        }
                    }
                }
                pageNo++;
            }
        } while (pageNo != -1);

    }

    public List<GdQueryOrderRes.GdQueryOrder> queryCardOrders(String startTime, String endTime, int pageNo, int pageSize) {

        try {
            String url = "https://" + rsaProperties.getGd().getUrl() + "/ycsim-business/openapi/query_card_order_info";

            long timestamp = System.currentTimeMillis() / 1000;

            GdQueryCardOrderReq req = GdQueryCardOrderReq.builder()
                    .queryBeginTime(startTime)
                    .queryEndTime(endTime)
                    .brhNo(rsaProperties.getGd().getBrhNo())
                    .pageNo(String.valueOf(pageNo))
                    .pageSize(String.valueOf(pageSize))
                    .timestamp(String.valueOf(timestamp)).build();
            String sign = GdRsaUtils.rsa256Sign(BeanUtil.beanToMap(req), rsaProperties.getGd().getPrivateKey());
            req.setSign(sign);
            String body = JSONUtil.toJsonStr(req);
            String response = HttpRequest.post(url)
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(body)
                    .timeout(50000)//超时，毫秒
                    .execute().body();
            Optional.ofNullable(response).orElseThrow(() -> new GlobalCustomerException("调用接口失败"));
            GdCommRes<GdQueryOrderRes> commRes = JSONUtil.toBean(response, new TypeReference<GdCommRes<GdQueryOrderRes>>() {
            }, true);
            if (commRes.getResultCode() == 1) {
                return commRes.getData().getRecords();
            } else {
                throw new GlobalCustomerException(commRes.getErrorDesc());
            }

        } catch (Exception e) {
            log.error("请求广电接口报错:{}", e.getLocalizedMessage());
            throw new GlobalCustomerException(e.getLocalizedMessage());
        }
    }

}
