package com.tofly.third.service;

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

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

@Slf4j
@Service
public class ZnbZlLogService extends ServiceImpl<ZnbZlLogMapper, ZnbZlLog> {
    @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");
        } else {
            //znbZlLog.setZlvalue("false");
        }

        znbZlLog.setClCljg("0");
        znbZlLog.setClClry("系统机器");
        znbZlLog.setClClsj(null);

        save(znbZlLog);
        return znbZlLog;
    }


    public void znbkgfTask() {
        ZnbOpenCloseCalve();
    }

    @Transactional
    @Async
    public void ZnbOpenCloseCalve() {
        //3青岛积成
        List<ZnbZlLog> znbZlLogs = this.lambdaQuery()
                .eq(ZnbZlLog::getZltype, "1")
                .eq(ZnbZlLog::getClLock, "0")
                .eq(ZnbZlLog::getClCljg, "0")
                .lt(ZnbZlLog::getQqNum, 5)//请求次数小于五
                .in(ZnbZlLog::getSccj, "2", "3", "4")
                .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_sdgx = znbZlLogs.stream().filter(o -> "2".equals(o.getSccj())).collect(Collectors.toList());
            if (!znbZlLogs_sdgx.isEmpty()) {
                sdgxkgf(znbZlLogs_sdgx);
            }
            //查询出山东晨晖的阀控指令
            List<ZnbZlLog> znbZlLogs_sdch = znbZlLogs.stream().filter(o -> "3".equals(o.getSccj())).collect(Collectors.toList());
            if (!znbZlLogs_sdch.isEmpty()) {

            }
            //查询出成都优艾特的阀控指令
            List<ZnbZlLog> znbZlLogs_cdyat = znbZlLogs.stream().filter(o -> "4".equals(o.getSccj())).collect(Collectors.toList());
            if (!znbZlLogs_cdyat.isEmpty()) {

            }

        } catch (Exception e) {
            log.error("执行开关阀命令失败");
        }
    }

    /**
     * 山东冠翔开关阀指令发送
     *
     * @param list
     */
    private void sdgxkgf(List<ZnbZlLog> list) {
        String baseUrl = znbconfig.getSdgxznbconfig().getBaseUrl();
        for (ZnbZlLog item : list) {
            Map map = new HashMap();
            map.put("bjbh", item.getBjbh());//水表钢印号，用于唯一标识水表
            map.put("zlID", item.getId());//指令ID
            map.put("zlvalue", item.getZlvalue());//阀门操作类型：1 = 开阀  0= 关阀
            String params = JSONObject.toJSONString(map);
            log.info("指令发送参数：" + params);
            String result = HttpRequestUtil.POSTRequest(baseUrl, params);
            log.info("指令发送结果：" + result);
            if (StringUtil.isEmpty(result)) {
                updateZllog(item.getId());
            } else {
                log.info("指令发送成功：" + result);
                //成功返回{"code":0,"message":"Success","timestamp":"2026-05-29 11:11:01","result":null}
                //失败返回{"code":1,"message":"操作失败","timestamp":"2026-05-29 11:13:19","result":null}
                JSONObject info = JSONObject.parseObject(result);
                if (info != null) {
                    List<ZnbZlLog> updates = new ArrayList<>();
                    ZnbZlLog updateLog = new ZnbZlLog();
                    updateLog.setId(item.getId()); // 必须 set ID
                    if ("0".equals(info.getString("code"))) {
                        updateLog.setClCljg("8");
                        updateLog.setClLock("0");
                        updateLog.setClRemessage("指令已发送等待回传");
                        updateLog.setClClsj(LocalDateTime.now());
                        updates.add(updateLog);
                        yhCbkxxService.lambdaUpdate()
                                .set(YhCbkxx::getFmzt, "1")
                                .in(YhCbkxx::getCbkid, item.getCbkid())
                                .update();
                    } else {
                        updateLog.setClCljg("0");
                        updateLog.setClLock("0");
                        updateLog.setClRemessage(info.getString("message"));
                        updateLog.setClClsj(LocalDateTime.now());
                        updates.add(updateLog);
                    }
                    this.updateBatchById(updates);
                } else {
                    updateZllog(item.getId());
                }
            }
        }
    }


    private void updateZllog(String id) {
        this.lambdaUpdate()
                .set(ZnbZlLog::getClLock, "0")
                .set(ZnbZlLog::getClCljg, "0")
                .set(ZnbZlLog::getClRemessage, "指令发送失败")
                .set(ZnbZlLog::getClClsj, new Date())
                .eq(ZnbZlLog::getId, id)
                .update();
    }
}
