package com.tofly.third.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.tofly.common.core.util.StringUtil;
import com.tofly.third.common.exception.BusinessException;
import com.tofly.third.common.req.Cbxx;
import com.tofly.third.common.util.AESUtil;
import com.tofly.third.common.util.HttpRequestUtil;
import com.tofly.third.common.util.ServerUtil;
import com.tofly.third.config.Znbconfig;
import com.tofly.third.entity.YatCbssxx;
import com.tofly.third.entity.YhCbkxx;
import com.tofly.third.entity.YhKhjbxx;
import com.tofly.third.entity.ZnbCbLog;
import com.tofly.third.mapper.ZnbCbLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ZnbCbLogService extends ServiceImpl<ZnbCbLogMapper, ZnbCbLog> {

    @Autowired
    private SysGdcsbService gdcsbService;
    @Autowired
    private YhCbkxxService yhCbkxxService;

    @Autowired
    private YccbService yccbService;

    @Autowired
    private Znbconfig znbconfig;

    public ZnbCbLog znbcb(YhKhjbxx yhKhjbxx, YhCbkxx cbkxx, Cbxx cbxx) {
        ZnbCbLog znbCbLog = new ZnbCbLog();
        znbCbLog.setYhbh(yhKhjbxx.getYhbh())
                .setCbkh(cbkxx.getCbkh())
                .setCbkid(cbkxx.getCbkid())
                .setBjbh(cbkxx.getSbbh())
                .setSccj(cbkxx.getSbsccj())
                .setSsgs("1")
                .setPch(ServerUtil.getZnbPCH())
                .setCzry("4")
                .setCzsj(LocalDateTime.now())
                .setClLock("0")
                .setClCljg("0")
                .setClClry("系统机器");

        znbCbLog.setSscbpq(yhKhjbxx.getSscbpq())
                .setSscbb(yhKhjbxx.getSscbb());

        String cwrq = gdcsbService.selectCwrq();
        znbCbLog.setCwrq(BigDecimal.valueOf(Long.parseLong(cwrq)));

        ZnbCbLog scyccbLog = getZxCbLogByCbkId(cbkxx.getCbkid());
        if (ObjectUtil.isNull(scyccbLog)) {
            znbCbLog.setSccbrq(null).setScds(BigDecimal.valueOf(cbkxx.getSbqs()));
        } else {
            if (ObjectUtil.isNotNull(scyccbLog.getCbrq())) {
                znbCbLog.setSccbrq(scyccbLog.getCbrq());
            }
            znbCbLog.setScds(scyccbLog.getBcds());
        }

        // TODO: 2025/9/2 水表读数 暂定向下取整，不保留小数位
        BigDecimal cbzs = new BigDecimal(cbxx.getCbzs());
        BigDecimal result = cbzs.setScale(0, RoundingMode.FLOOR);

        BigDecimal cbsl = result.subtract(znbCbLog.getScds());

        znbCbLog.setCbZs(result)
                .setCbSl(cbsl)
                .setBcds(result)
                .setCbrybm("4")
                .setCbryxm("物联网抄表");

        String cbsj = cbxx.getCbsj();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN);
        LocalDateTime cbrq = LocalDateTime.parse(cbsj, formatter);
        znbCbLog.setCbrq(cbrq)
                .setLrrybm("3")
                .setLrryxm("系统机器")
                .setLrrq(new Date())
                .setCbpl(6);

        znbCbLog.setClClsj(LocalDateTime.now())
                .setClCljg("1");

        if ("1".equals(cbxx.getBjbhpp())) {
            znbCbLog.setCbbz("水表厂家推送的表具编号与水表档案的不匹配！");
        }
        save(znbCbLog);
        return znbCbLog;
    }

    public ZnbCbLog getZxCbLogByCbkId(String cbkId) {
        if (StrUtil.isEmpty(cbkId)) {
            throw new BusinessException("未找到抄表卡信息");
        }

        return baseMapper.getZxCbLogByCbkId(cbkId);
    }


    public void YatZnbcbTask() {
        List<YhCbkxx> cbkxxList = yhCbkxxService.list(
                new LambdaQueryWrapper<YhCbkxx>()
                        .select(YhCbkxx::getYhbh, YhCbkxx::getCbkid, YhCbkxx::getSbbh)
                        .eq(YhCbkxx::getSbsccj, "4")
                        .eq(YhCbkxx::getSbbh, "1125122118")
        );
        if (!cbkxxList.isEmpty()) {
            List<List<YhCbkxx>> cbkxxList50 = Lists.partition(cbkxxList, 50);
            String baseUrl = znbconfig.getYatznbconfig().getBaseUrl() + "queryDataHistoryBatch";
            for (List<YhCbkxx> item : cbkxxList50) {
                String data = item.stream().map(YhCbkxx::getSbbh).collect(Collectors.joining("1,"));
                String params = YatRequestObject(data, "string");
                String result = HttpRequestUtil.POSTRequest(baseUrl, params);
                log.info("优艾特返回结果：" + result);
                if (StringUtil.isNotEmpty(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String jsondata = jsonObject.getString("data");
                    String timeStamp = jsonObject.getString("timeStamp");
                    timeStamp = AESUtil.decrypt(timeStamp, znbconfig.getYatznbconfig().getAppName());
                    jsondata = AESUtil.decrypt(jsondata, timeStamp);
                    if (jsonObject.getBoolean("requestCode")) {
                        JSONArray jsonArray = JSONArray.parseArray(jsondata);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            YatCbssxx yatCbssxx = jsonArray.getObject(i, YatCbssxx.class);
                            if (yatCbssxx.getRequestCode()) {
                                Cbxx cbxx = new Cbxx();
                                cbxx.setBjbh(yatCbssxx.getMeterNumber());
                                cbxx.setCbzs(String.valueOf(yatCbssxx.getMount()));
                                cbxx.setCbsj(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                cbxx.setImei(yatCbssxx.getImei());
                                cbxx.setPid(yatCbssxx.getUsim());
                                cbxx.setDsId(yatCbssxx.getDeviceId());
                                //设备信息
                                cbxx.setNbdy(String.valueOf(yatCbssxx.getVoltage()));//电池电量
                                cbxx.setNbxhqd(String.valueOf(yatCbssxx.getSignal()));
                                yccbService.cbtb(cbxx);
                            } else {
                                log.error("优艾特返回结果异常：" + yatCbssxx.getErrorMsg());
                            }
                        }

                    } else {
                        log.error("优艾特返回结果异常：" + jsondata);
                    }
                } else {
                    log.error("优艾特返回结果异常：" + result);
                }
            }
        }
    }

    /**
     * 封装请求参数
     *
     * @param data     实际参数
     * @param dataName 参数类型string或者jsonobject
     * @return
     */
    public String YatRequestObject(String data, String dataName) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMddHHmm");
        String timeStamp = now.format(formatter);
        Map map = new HashMap();
        //对接识别名称
        map.put("appName", znbconfig.getYatznbconfig().getAppName());
        //格 式MMddHHmm以appName为KEY加密
        map.put("timeStamp", AESUtil.encrypt(timeStamp, znbconfig.getYatznbconfig().getAppName()));
        //返回结果有效 true 成功
        map.put("requestCode", true);
        //Data 的格式名称string或者jsonobject
        map.put("dataName", dataName);
        //以加密前的timeStamp 为key 加密
        map.put("data", AESUtil.encrypt(data, timeStamp));
        String params = JSONObject.toJSONString(map);
        log.info("指令发送参数：" + params);
        return params;
    }
}
