package jnpf.attendance.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import jnpf.attendance.service.MachineStrategy;
import jnpf.base.UserInfo;
import jnpf.enums.attendance.MachineEnum;
import jnpf.permission.model.user.PartUserInfoVo;
import jnpf.util.attendance.MqttSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 语雀 - 考勤策略模式
 *
 * @author yanwenfu
 * @create 2024-04-09
 */
@Slf4j
@Component(value = "machineYuQueStrategy")
public class MachineYuQueStrategyImpl implements MachineStrategy {

    @Autowired
    private MqttSender mqttSender;

    @Value("${spring.mqtt.topics}")
    private String topic;

    @Value("${spring.mqtt.servicePath}")
    private String servicePath;

    @Override
    public MachineEnum getMachine() {
        return MachineEnum.YU_QUE;
    }

    @Override
    public void addUserToMachine(UserInfo userInfo, PartUserInfoVo user, String sn) {

        // sn为设备mac地址
        JSONObject json = new JSONObject();
        json.set("method", "sync_person");
        JSONObject dataJson = new JSONObject();
        dataJson.set("path", servicePath + "/device/sync_person");
        JSONObject pathParams = new JSONObject();
        pathParams.set("dev_sno", sn);
        pathParams.set("limit", 1);
        pathParams.set("offset", 0);
        pathParams.set("total", 1);
        JSONArray array = new JSONArray();
        array.add(userInfo.getTenantId() + "@" + user.getUserId());
        pathParams.set("person_list", array);
        pathParams.set("person_type", "4");
        dataJson.set("path_params", pathParams);
        json.set("data", dataJson);
        json.set("notify", servicePath + "/device/notify");
        JSONObject params = new JSONObject();
        params.set("tenantId", userInfo.getTenantId());
        json.set("params", params);
        mqttSender.send(sn, json.toString());
    }

    @Override
    public void deleteUserList(UserInfo userInfo, List<String> userIds, String sn) {

        if (userIds.isEmpty()) {
            log.error("userIds为空, 无可删除用户...");
            return;
        }
        JSONObject json = new JSONObject();
        json.set("method", "delete_person");
        json.set("notify", servicePath + "/device/notify");
        json.set("params", "");
        JSONObject dataJson = new JSONObject();
        JSONArray array = new JSONArray();
        userIds.forEach(userId -> array.add(userInfo.getTenantId() + "@" + userId));
        dataJson.set("person_list", array);
        dataJson.set("person_type", "4");
        json.set("data", dataJson);
        mqttSender.send(sn, json.toString());
    }

    @Override
    public void syncMachineMember(String sn) {

    }
}
