package org.jeecg.modules.api.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.jeecg.config.mqtt.MqttMessageSender;
import org.jeecg.modules.api.model.CabinetModel;
import org.jeecg.modules.api.model.CabinetStocks;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class CabinetConnectService {
    private static final String ZHONGHONG_MANUFACTURER = "zhonghong";
    private static final String RECEIVE_PREFIX = "receive";

    @Value("${cabinet.manufacturer}")
    private String cabinetManufacturer;

    @Autowired
    private MqttMessageSender mqttMessageSender;

    /**
     * 人员信息同步接口(每次新增成员的时候，所有人的数据都需要一次性下发)
     * @param cabinetModels 人员信息列表
     * @throws RuntimeException 如果发送消息失败
     */
    public void sendUsers(List<CabinetModel> cabinetModels) {
        JSONObject payload = createPayload("users", cabinetModels);
        sendDirectMessage("receiveUsers", payload);
    }

    /**
     * 向工具柜下发工单信息
     * @param cabinetModel 工单信息
     * @param applyType 申请类型
     * @throws RuntimeException 如果发送消息失败
     */
    public void sendWorkOrder(CabinetModel cabinetModel, int applyType) {
        JSONObject body = JSON.parseObject(JSON.toJSONString(cabinetModel));

        if (isZhonghongManufacturer()) {
            if (applyType == 0) {//物料
                sendDirectMessage("orderInfoMaterial", body);
            }else if (applyType == 1) {//工具
                sendDirectMessage("orderInfoTool", body);
            }
        } else {
            sendDirectMessage("receiveOrderInfo", body);
        }
    }

    /**
     * 撤销工单信息向工具柜下发
     * @param cabinetModel 工单信息
     * @throws RuntimeException 如果发送消息失败
     */
    public void sendCancelWorkOrder(CabinetModel cabinetModel) {
        if (isZhonghongManufacturer()) {
            JSONObject body = JSON.parseObject(JSON.toJSONString(cabinetModel));
            sendDirectMessage("cancelOrder", body);
        } else {
            JSONObject formData = new JSONObject();
            formData.put("orderId", cabinetModel.getOrderId());
            sendDirectMessage("receiveCancelOrder", formData);
        }
    }

    /**
     * 向工具柜同步工具信息
     * @param stocks 工具信息列表
     * @throws RuntimeException 如果发送消息失败
     */
    public void sendToolInfo(List<CabinetStocks> stocks) {
        JSONObject payload = createPayload("tools", stocks);
        sendDirectMessage("receiveToolInfo", payload);
    }

    private boolean isZhonghongManufacturer() {
        return ZHONGHONG_MANUFACTURER.equalsIgnoreCase(cabinetManufacturer);
    }

    private JSONObject createPayload(String key, List<?> data) {
        JSONObject payload = new JSONObject();
        payload.put(key, JSONArray.parseArray(JSON.toJSONString(data)));
        return payload;
    }

//    private void sendFormDataMessage(String topic, JSONObject payload, String customKey) {
//        JSONObject formData = new JSONObject();
//        String key = StringUtils.hasText(customKey) ? customKey : deriveDefaultKey(topic);
//        formData.put(key, payload);
//        sendDirectMessage(topic, formData);
//    }

    private void sendDirectMessage(String topic, JSONObject message) {
        mqttMessageSender.send(topic, message.toJSONString());
    }

//    private String deriveDefaultKey(String topic) {
//        if (topic.startsWith(RECEIVE_PREFIX)) {
//            return topic.substring(RECEIVE_PREFIX.length()).toLowerCase();
//        }
//        return topic.toLowerCase();
//    }
}
