package com.qiuguo.iot.third.service;

import cn.hutool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qiuguo.iot.data.entity.user.UserHandlingDeviceEntity;
import com.qiuguo.iot.data.service.user.UserHandlingDeviceService;
import com.qiuguo.iot.third.enums.TuyaCategoryEnum;
import com.qiuguo.iot.third.query.TuyaQuery;
import com.qiuguo.iot.third.resp.TuyaResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * XXX
 *
 * @author weiyachao
 * @since 2023/9/19 15:13
 */
@Service
@Slf4j
public class TuyaDeviceService {
    
    @Autowired
    private TuyaDeviceConnector tuyaDeviceConnector;
    
    @Autowired
    private UserHandlingDeviceService userHandlingDeviceService;
    
    // @Autowired
    // private
    
    /**
     * 查询设备详情
     */
    public Mono<JSONArray> getDeviceInfo(String deviceId) {
        return Mono.just(tuyaDeviceConnector.getByid(deviceId));
    }
    
    /**
     * 获取设备分类code
     */
    public Mono<String> getCateCode(String deviceId) {
        JSONArray byid = tuyaDeviceConnector.getByid(deviceId);
        if (ObjectUtils.isEmpty(byid)) {
            return Mono.empty();
        }
        return Mono.just(byid.getJSONObject(0).getString("category"));
    }
    
    /**
     * 获取设备状态
     */
    public Mono<JSONArray> getDeviceStatus(String deviceId) {
        return Mono.just(tuyaDeviceConnector.getDeviceStatus(deviceId));
    }
    
    // /**
    //  * 设备控制
    //  */
    // public Mono<TuyaResponse> controlDevice(List<TuyaQuery> list) {
    //     TuyaResponse tuyaResponse = new TuyaResponse();
    //     tuyaResponse.setCode(500);
    //     if (ObjectUtils.isEmpty(list)) {
    //         tuyaResponse.setMessage("参数为空");
    //         return Mono.just(tuyaResponse);
    //     }
    //     Map<Long, TuyaQuery> queryMap = list.stream()
    //             .collect(Collectors.toMap(TuyaQuery::getUserHandlingDeviceId, Function.identity()));
    //     Flux<UserHandlingDeviceEntity> selectByIds = userHandlingDeviceService.selectByIds(
    //             list.stream().map(TuyaQuery::getUserHandlingDeviceId).collect(Collectors.toList()));
    //
    //     return selectByIds.flatMapSequential(entity -> {
    //         try {
    //             TuyaQuery query = queryMap.get(entity.getId());
    //             JSONArray jsonArray = tuyaDeviceConnector.getByid(query.getDeviceId());
    //             if (ObjectUtils.isEmpty(jsonArray)) {
    //                 tuyaResponse.setMessage("查询不到设备");
    //                 return Mono.just(tuyaResponse);
    //             }
    //             JSONObject deviceInfo = jsonArray.getJSONObject(0);
    //             if (Objects.equals(deviceInfo.getBoolean(TuyaCategoryEnum.getColumn(entity.getCategoryCode())), false)
    //                     && !Objects.equals(entity.getMatchingFields(), "开")) {
    //                 tuyaResponse.setMessage("设备未开机");
    //                 return Mono.just(tuyaResponse);
    //             }
    //             JSONObject commands = new JSONObject();
    //             List<JSONObject> queryList = new ArrayList<>();
    //             JSONObject jsonObject = new JSONObject();
    //             String type = entity.getType();
    //             jsonObject.put("code", entity.getCode());
    //             if (type.equalsIgnoreCase("boolean")) {
    //                 jsonObject.put("value", Boolean.parseBoolean(entity.getValue()));
    //             } else if (type.equalsIgnoreCase("Integer")) {
    //                 int value = Integer.parseInt(entity.getValue());
    //                 jsonObject.put("value", value <= entity.getMin() ? entity.getMin()
    //                         : value >= entity.getMax() ? entity.getMax() : value);
    //             } else if (type.equalsIgnoreCase("Enum")) {
    //                 jsonObject.put("value", entity.getValue());
    //             } else {
    //                 jsonObject.put("value", entity.getValue());
    //             }
    //             queryList.add(jsonObject);
    //             commands.put("commands", queryList);
    //             return Mono.just(true);
    //         } catch (Exception ex) {
    //             tuyaResponse.setMessage("网络异常");
    //             return Mono.just(tuyaResponse);
    //         }
    //     }).onErrorResume(throwable -> {
    //         // 处理异常情况，返回 Mono.just(false)
    //         return Mono.just(false);
    //     });
    //
    //
    //
    // }
    //
    public static void main(String[] args) {
        int aa = 1000;
        double a = 10 / (double) 1000;
        System.out.println(a);
    }
    
    /**
     * 控制设备
     */
    public Mono<TuyaResponse> controlDevice(TuyaQuery query) {
        Mono<UserHandlingDeviceEntity> userHandlingDeviceEntityMono = userHandlingDeviceService.selectUserHandlingDeviceById(
                query.getUserHandlingDeviceId());
        TuyaResponse tuyaResponse = new TuyaResponse();
        tuyaResponse.setCode(500);
        return userHandlingDeviceEntityMono.flatMap(data -> {
            JSONArray jsonArray = tuyaDeviceConnector.getByid(query.getDeviceId());
            if (ObjectUtils.isEmpty(jsonArray)) {
                tuyaResponse.setMessage("查询不到设备");
                return Mono.just(tuyaResponse);
            }
            JSONObject deviceInfo = jsonArray.getJSONObject(0);
            if (Objects.equals(deviceInfo.getBoolean(TuyaCategoryEnum.getColumn(data.getCategoryCode())), false)
                    && !Objects.equals(data.getMatchingFields(), "开")) {
                tuyaResponse.setMessage("设备未开机");
                return Mono.just(tuyaResponse);
            }
            JSONArray deviceStatus = tuyaDeviceConnector.getDeviceStatus(query.getDeviceId());
            if (ObjectUtils.isEmpty(deviceStatus)) {
                tuyaResponse.setMessage("设备信息异常");
                return Mono.just(tuyaResponse);
            }
            List<JSONObject> javaList = deviceStatus.toJavaList(JSONObject.class);
            JSONObject commands = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            String type = data.getType();
            jsonObject.put("code", data.getCode());
            if (type.equalsIgnoreCase("boolean")) {
                jsonObject.put("value", Boolean.parseBoolean(data.getValue()));
            } else if (type.equalsIgnoreCase("Integer")) {
                jsonObject.put("value", Integer.parseInt(query.getValue()));
            } else if (type.equalsIgnoreCase("Enum")) {
                jsonObject.put("value", data.getValue());
            } else if (type.equalsIgnoreCase("auto_add_integer")) {
                JSONObject code = javaList.stream()
                        .filter(statu -> data.getCode().equalsIgnoreCase(statu.getString("code"))).findFirst()
                        .orElse(new JSONObject());
                double codeValue = code.getInteger("value");
                int max = data.getMax();
                double cut = max * 0.2;
                double value = codeValue + cut;
                int intValue = (int) value;
                jsonObject.put("value", intValue >= max ? max - 1 : intValue);
            } else if (type.equalsIgnoreCase("auto_reduce_integer")) {
                JSONObject code = javaList.stream()
                        .filter(statu -> data.getCode().equalsIgnoreCase(statu.getString("code"))).findFirst()
                        .orElse(new JSONObject());
                double codeValue = code.getInteger("value");
                int min = data.getMin();
                double cut = data.getMax() * 0.2;
                double value = codeValue - cut;
                int intValue = (int) value;
                jsonObject.put("value", intValue <= min ? min + 1 : intValue);
            }
            if (javaList.contains(jsonObject)) {
                tuyaResponse.setMessage("已在当前状态");
                tuyaResponse.setCode(200);
                return Mono.just(tuyaResponse);
            }
            javaList.add(jsonObject);
            List<JSONObject> collect = javaList.stream().filter(jl -> !ObjectUtils.isEmpty(jl.get("value")))
                    .filter(jl -> !jl.getString("value").startsWith("{"))
                    .filter(jl -> !jl.getString("value").startsWith("[")).collect(Collectors.toList());
            commands.put("commands", collect);
            Boolean result = tuyaDeviceConnector.controlDevice(query.getDeviceId(), commands);
            if (result) {
                tuyaResponse.setMessage("ok");
                tuyaResponse.setCode(200);
            } else {
                tuyaResponse.setMessage("请求失败");
            }
            return Mono.just(tuyaResponse);
        }).onErrorResume(ex -> {
            log.error("TuyaDeviceService is error:{}",ex);
            tuyaResponse.setMessage("设备不支持此操作");
            return Mono.just(tuyaResponse);
        });
    }
}
