package com.usky.iot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.bean.CommonPage;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.iot.domain.BaseFacilityDevice;
import com.usky.iot.domain.BaseGgpFacility;
import com.usky.iot.domain.BaseScreen;
import com.usky.iot.domain.DmpDeviceInfo;
import com.usky.iot.mapper.BaseScreenMapper;
import com.usky.iot.service.BaseScreenService;
import com.usky.common.mybatis.core.AbstractCrudService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author han
 * @since 2026-01-20
 */
@Service
public class BaseScreenServiceImpl extends AbstractCrudService<BaseScreenMapper, BaseScreen> implements BaseScreenService {
    @Override
    public boolean add(BaseScreen baseScreen) {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        baseScreen.setScreenCode(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(date));
        baseScreen.setCreatedBy(SecurityUtils.getUsername());
        baseScreen.setCreatedTime(LocalDateTime.now());
        baseScreen.setTenantId(SecurityUtils.getTenantId());
        this.checkRequiredData(baseScreen);
        return this.save(baseScreen);
    }

    @Override
    public void update(BaseScreen baseScreen) {
        baseScreen.setUpdatedTime(LocalDateTime.now());
        baseScreen.setUpdatedBy(SecurityUtils.getUsername());
        this.checkRequiredData(baseScreen);
        this.updateById(baseScreen);
    }

    @Override
    public List<BaseScreen> screenList(Integer screenGroup, Integer id) {
        LambdaQueryWrapper<BaseScreen> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(id != null, BaseScreen::getId, id)
                .eq(screenGroup != null, BaseScreen::getScreenGroup, screenGroup)
                .eq(BaseScreen::getTenantId, SecurityUtils.getTenantId());
        List<BaseScreen> list = this.list(lambdaQuery);
        return list;
    }

    /**
     * 必填数据校验
     */
    private void checkRequiredData(BaseScreen baseScreen) {

        if (StringUtils.isBlank(baseScreen.getScreenTitle())) {
            throw new BusinessException("大屏标题不能为空！");
        }

        if (StringUtils.isBlank(baseScreen.getScreenCode())) {
            throw new BusinessException("大屏编号不能为空！");
        }

        if (baseScreen.getScreenGroup() == null) {
            throw new BusinessException("分组不能为空！");
        }

        if (baseScreen.getIsDefault() == null) {
            throw new BusinessException("是否默认不能为空！");
        }
    }

}
