package com.skr.mdm.service.impl.app;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.skr.mdm.annotation.CmdHandler;
import com.skr.mdm.constant.CmdTypeConstants;
import com.skr.mdm.dao.AppStrategyUserDao;
import com.skr.mdm.dto.AppStrategyInfoDTO;
import com.skr.mdm.entity.AppStrategyUserDO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.service.CmdHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author nfq
 * @date 2020/8/3 15:07
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.APP_STRATEGY)
public class AppStrategyServiceImpl implements CmdHandlerService {

    @Autowired
    private AppStrategyUserDao appStrategyUserDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            // 应用策略回调
            JSONArray jsonArray = JSONUtil.parseArray(data);
            List<AppStrategyInfoDTO> appStrategyInfoDTOList = JSONUtil.toList(jsonArray, AppStrategyInfoDTO.class);
            List<Integer> cidList = new ArrayList<>(appStrategyInfoDTOList.size());
            appStrategyInfoDTOList.forEach(appStrategyInfoDTO -> {
                LambdaUpdateChainWrapper<AppStrategyUserDO> updateChainWrapper = new LambdaUpdateChainWrapper<>(appStrategyUserDao);
                updateChainWrapper
                        .set(AppStrategyUserDO::getState, appStrategyInfoDTO.getState())
                        .eq(AppStrategyUserDO::getStrategyId, appStrategyInfoDTO.getAppStrategyId())
                        .eq(AppStrategyUserDO::getEquipmentId, equipmentId)
                        .update();
                cidList.add(appStrategyInfoDTO.getCid());
            });
            return ResponseResult.success(JSONUtil.toJsonStr(cidList));
        } catch (Exception e) {
            log.error("应用策略回调异常: " + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}
