package com.zhongshu.card.server.core.service.devices.permiss;

import cn.hutool.json.JSONUtil;
import com.github.microservice.models.device.DevicePermissSendResponseParam;
import com.github.microservice.models.device.DevicePermissSendResponseResult;
import com.github.microservice.net.ResultContent;
import com.zhongshu.card.client.type.permiss.PermissSendState;
import com.zhongshu.card.server.core.dao.devices.DevicePermissSendLogDao;
import com.zhongshu.card.server.core.domain.devices.permiss.DevicePermissSendLog;
import com.zhongshu.card.server.core.service.base.CommonService;
import com.zhongshu.card.server.core.service.base.SuperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author TRX
 * @date 2024/10/31
 */
@Slf4j
@Service
public class DevicePermissSendLogService extends SuperService {

    @Autowired
    private DevicePermissSendLogDao devicePermissSendLogDao;

    @Autowired
    private CommonService commonService;

    /**
     * 下发权限数据的响应
     *
     * @param param
     * @return
     */
    public ResultContent markSendResponse(DevicePermissSendResponseParam param) {
        DevicePermissSendResponseResult result = new DevicePermissSendResponseResult();
        result.setSuccess();

        return ResultContent.buildSuccess(JSONUtil.toJsonStr(result));
    }

    /**
     * 得到下发 结果
     *
     * @param groupId
     * @return
     */
    public ResultContent isAllResponseSuccess(String groupId) {

        return ResultContent.buildSuccess();
    }

    /**
     * 批次下发的权限是否都已响应
     *
     * @param groupId
     * @return
     */
    public Boolean isAllResponse(String groupId) {
        long all = devicePermissSendLogDao.countByGroupId(groupId);
        long responseEd = devicePermissSendLogDao.countByGroupIdAndIsResponse(groupId, Boolean.TRUE);
        if (all == responseEd) {
            return true;
        }
        return false;
    }

    /**
     * 编辑
     *
     * @param groupId
     * @param isSuccess
     */
    public void markPermissSend(String groupId, Boolean isSuccess, String message) {
        if (StringUtils.isNotEmpty(groupId)) {
            Map<String, Object> where = new HashMap<>();
            where.put("groupId", groupId);

            Map<String, Object> standardData = new HashMap<>();
            if (isSuccess != null && isSuccess) {
                standardData.put("sendState", PermissSendState.SendSuccess);
            } else {
                standardData.put("sendState", PermissSendState.SendFailed);
            }
            standardData.put("sendMsg", message);
            commonService.updateData(where, standardData, DevicePermissSendLog.class.getSimpleName());
        }
    }

}
