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

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.DeviceEquipmentDao;
import com.skr.mdm.dto.EquipmentCardBindDTO;
import com.skr.mdm.entity.DeviceEquipmentDO;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.service.CmdHandlerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 机卡绑定
 * @author nfq
 * @date 2021/2/4 14:38
 */
@Slf4j
@CmdHandler(cmdType = CmdTypeConstants.CARD_BIND_UNBIND)
public class EquipmentCardBindServiceImpl implements CmdHandlerService {

    @Autowired
    private DeviceEquipmentDao equipmentDao;

    @Override
    public ResponseResult cmdHandler(Integer equipmentId, String data) {
        try {
            EquipmentCardBindDTO equipmentCardBindDTO = JSONUtil.toBean(data, EquipmentCardBindDTO.class);
            new LambdaUpdateChainWrapper<>(equipmentDao)
                    .set(DeviceEquipmentDO::getIsCardBinding, equipmentCardBindDTO.getBindState())
                    .set(equipmentCardBindDTO.getBindState() == 1, DeviceEquipmentDO::getCardUnbindPassword, equipmentCardBindDTO.getUnbindPassword())
                    .set(StringUtils.isNotBlank(equipmentCardBindDTO.getRandomCode()), DeviceEquipmentDO::getOfflineUnlockCode, equipmentCardBindDTO.getRandomCode())
                    .set(StringUtils.isNotBlank(equipmentCardBindDTO.getPhoneNumber()), DeviceEquipmentDO::getPhoneNumber, equipmentCardBindDTO.getPhoneNumber())
                    .set(StringUtils.isNotBlank(equipmentCardBindDTO.getIccid()), DeviceEquipmentDO::getIccid, equipmentCardBindDTO.getIccid())
                    .eq(DeviceEquipmentDO::getId, equipmentId)
                    .update();
            return ResponseResult.success(equipmentCardBindDTO.getCid());
        } catch (Exception e) {
            log.error("机卡绑定异常: " + equipmentId + data, e);
            return ResponseResult.failure();
        }
    }
}