package com.xy.service.factory.cmd.impl;

import cn.hutool.json.JSONObject;
import com.xy.annotate.Factory;
import com.xy.dto.DeviceQualityDto;
import com.xy.dto.MqttCmdDto;
import com.xy.dto.PaterDto;
import com.xy.entity.DeviceQuality;
import com.xy.error.CommRuntimeException;
import com.xy.service.DeviceQualityServiceImpl;
import com.xy.service.factory.cmd.CmdService;
import com.xy.utils.Emptys;
import com.xy.utils.LambdaUtils;
import com.xy.utils.R;
import lombok.AllArgsConstructor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 质检指令 接口实现
 */
@Factory(type = "quality")
@AllArgsConstructor
public class QualityCmdServiceImpl implements CmdService {

    private DeviceQualityServiceImpl deviceQualityService;

    @Override
    public R senCommand(List<MqttCmdDto> mqttDtos) {
        Map<Integer, List<MqttCmdDto>> map = new HashMap<>();
        mqttDtos.forEach(mqttDto -> {
            PaterDto pater = mqttDto.getPater();
            JSONObject data = pater.getData();
            Integer qualityId = Integer.valueOf(data.getStr(LambdaUtils.getProperty(DeviceQuality::getQualityId)));
            if (!map.containsKey(qualityId)) {
                map.put(qualityId, new ArrayList<>());
            }
            map.get(qualityId).add(mqttDto);
        });
        map.forEach((k, v) -> {
            List<String> types = new ArrayList<>(v.size());
            v.forEach(mqttDto -> {
                PaterDto pater = mqttDto.getPater();
                JSONObject data = pater.getData();
                String type = data.getStr("type");
                types.add(type);
            });
            R r = deviceQualityService.rest(new DeviceQualityDto.Rest().setQualityId(k).setTypes(types));
            if (r.getCode() != R.Enum.SUCCESS.getCode()) {
                throw new CommRuntimeException(r.getMsg());
            }
        });
        return R.ok();
    }

    @Override
    public R resultBack(MqttCmdDto.ResultBack resultBack) {
        DeviceQualityDto.QualityResultBack qualityResultBack = resultBack.getQualityResultBack();
        if (!Emptys.check(qualityResultBack)) {
            return R.fail(LambdaUtils.getProperty(MqttCmdDto.ResultBack::getQualityResultBack) + "不能为空");
        }
        return deviceQualityService.qualityResultBack(qualityResultBack);
    }
}
