package tech.glinfo.enbao.modules.sh.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import tech.glinfo.enbao.common.utils.DateUtils;
import tech.glinfo.enbao.common.utils.R;
import tech.glinfo.enbao.common.utils.StringUtils;
import tech.glinfo.enbao.modules.sh.dao.OtherShDevicePowerDao;
import tech.glinfo.enbao.modules.sh.entity.ShDevicePowerEntity;
import tech.glinfo.enbao.modules.sh.service.OtherShDevicePowerService;

import java.util.Date;
import java.util.Map;


@Service("otherShDevicePowerService")
public class OtherShDevicePowerServiceImpl extends ServiceImpl<OtherShDevicePowerDao, ShDevicePowerEntity> implements OtherShDevicePowerService {

    @Override
    public R powerQuery(Map<String, Object> params) {
        String startTime = (String) params.get("startTime");
        String entTime = (String) params.get("entTime");
        String deviceId = (String) params.get("deviceId");
        if (StringUtils.isBlank(startTime, entTime, deviceId)) {
            return R.error("缺少参数");
        }

        ShDevicePowerEntity entity1 = this.baseMapper.startPower(Integer.parseInt(deviceId), startTime, entTime);

        ShDevicePowerEntity entity2 = this.baseMapper.entPower(Integer.parseInt(deviceId), startTime, entTime);
        if (entity1 != null && entity2 != null) {
            return R.ok().put("totalPower", entity2.getTotalPower() - entity1.getTotalPower());
        }else if (entity1 == null && entity2 == null) {
            return R.ok().put("totalPower", 0);
        }else if (entity1 != null){
            return R.ok().put("totalPower", entity1.getTotalPower());
        }else {
            return R.ok().put("totalPower", entity2.getTotalPower());
        }
    }

    @Override
    public R saveOrUpdateByTime(Integer deviceId, Integer totalDuration, Integer totalPower) {

        ShDevicePowerEntity entity = this.baseMapper.getPowerByTime(deviceId, DateUtils.format(new Date()));
        if (entity == null) {
            ShDevicePowerEntity entity1 = new ShDevicePowerEntity();
            entity1.setDeviceId(deviceId);
            entity1.setTotalDuration(totalDuration);
            entity1.setTotalPower(totalPower);
            return this.save(entity1) ? R.ok() : R.error();
        }else {
            entity.setTotalDuration(totalDuration);
            entity.setTotalPower(totalPower);
            return this.updateById(entity) ? R.ok() : R.error();
        }
    }

}