/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.znb.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.common.core.util.StringUtil;
import com.tofly.znb.config.ZnbConfig;
import com.tofly.znb.entity.YhCbkxx;
import com.tofly.znb.entity.ZnbCbLog;
import com.tofly.znb.entity.ZnbZlLog;
import com.tofly.znb.service.YhCbkxxService;
import com.tofly.znb.service.ZnbZlLogService;
import com.tofly.znb.utils.HttpRequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.tofly.znb.mapper.ZnbZlLogMapper;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 智能表指令明细
 *
 * @author admin
 * @date Fri Aug 01 00:00:00 CST 2025
 */
@Slf4j
@Service("znbZlLogService")
public class ZnbZlLogServiceImpl extends ServiceImpl<ZnbZlLogMapper, ZnbZlLog> implements ZnbZlLogService {

    @Autowired
    private ZnbConfig znbConfig;

    @Autowired
    private YhCbkxxService yhCbkxxService;

    public ZnbZlLog addZlLog(BigDecimal ye, ZnbCbLog znbcb) {
        ZnbZlLog znbZlLog = BeanUtil.copyProperties(znbcb, ZnbZlLog.class);
        znbZlLog.setZltype("1");
        if (ye.signum() < 0) {
            znbZlLog.setZlvalue("0");
        }
        znbZlLog.setClCljg("0");
        znbZlLog.setClClry("系统机器");
        znbZlLog.setClClsj(DateTime.now());
        save(znbZlLog);
        return znbZlLog;
    }


    @Override
    public void znbkgfTask() {
        ZnbOpenCloseCalve();
    }

    @Transactional
    @Async
    public void ZnbOpenCloseCalve() {
        //6声派尔
        List<ZnbZlLog> znbZlLogs = this.lambdaQuery()
                .eq(ZnbZlLog::getZltype, "1")
                .eq(ZnbZlLog::getClLock, "0")
                .eq(ZnbZlLog::getClCljg, "0")
                .lt(ZnbZlLog::getQqNum, 5)//请求次数小于五
                .in(ZnbZlLog::getSccj, "6")
                .orderByAsc(ZnbZlLog::getCzsj)
                .list();
        if (znbZlLogs.isEmpty()) {
            return;
        }
        try {
            //先锁定防止重复查询
            this.lambdaUpdate()
                    .set(ZnbZlLog::getClLock, "1")
                    .setSql("QQ_NUM=nvl(QQ_NUM,0)+1")
                    .in(ZnbZlLog::getId, znbZlLogs.stream().map(ZnbZlLog::getId).collect(Collectors.toList()))
                    .update();
            //查询出声派尔的阀控指令
            List<ZnbZlLog> znbZlLogs_qdjc = znbZlLogs.stream().filter(o -> "6".equals(o.getSccj())).collect(Collectors.toList());
            if (!znbZlLogs_qdjc.isEmpty()) {
                qdjckgf(znbZlLogs_qdjc);
            }
        } catch (Exception e) {
            log.error("执行开关阀命令失败");
        }
    }

    /**
     * 声派尔水表开关阀指令发送
     *
     * @param list
     */
    @Override
    public void qdjckgf(List<ZnbZlLog> list) {
        String token = HttpRequestUtil.GetToken(znbConfig);
        String baseUrl = znbConfig.getApiUrl() + "/authentication/interface/valveControl?token=" + token;
        for (ZnbZlLog item : list) {
            String getbaseUrl = baseUrl + "&sn=" + item.getBjbh() + "&flag=" + item.getZlvalue().equals("1");
            String result = HttpRequestUtil.GETRequest(getbaseUrl, "", "");
            log.info("开关阀请求结果：{}", result);
            if (StringUtil.isEmpty(result)) {
                this.lambdaUpdate()
                        .set(ZnbZlLog::getClLock, "0")
                        .set(ZnbZlLog::getClCljg, "0")
                        .set(ZnbZlLog::getClRemessage, "指令发送失败")
                        .set(ZnbZlLog::getClClsj, new Date())
                        .eq(ZnbZlLog::getId, item.getId())
                        .update();
            } else {
                JSONObject info = JSONObject.parseObject(result);
                if ("200".equals(info.getString("httpCode"))) {
                    this.lambdaUpdate()
                            .set(ZnbZlLog::getClLock, "0")
                            .set(ZnbZlLog::getClCljg, "1")
                            .set(ZnbZlLog::getClRemessage, info.getString("data"))
                            .set(ZnbZlLog::getClClsj, new Date())
                            .eq(ZnbZlLog::getId, item.getId())
                            .update();
                    yhCbkxxService.lambdaUpdate()
                            .set(YhCbkxx::getFmzt, item.getZlvalue().equals("1") ? "0" : "2")
                            .in(YhCbkxx::getCbkid, item.getCbkid())
                            .update();
                } else {
                    this.lambdaUpdate()
                            .set(ZnbZlLog::getClLock, "1")
                            .set(ZnbZlLog::getClCljg, "2")
                            .set(ZnbZlLog::getClRemessage, info.getString("msg"))
                            .set(ZnbZlLog::getClClsj, new Date())
                            .eq(ZnbZlLog::getId, item.getId())
                            .update();
                }
            }
        }
    }
}
