/*
 * Copyright [2022] [https://www.xiaonuo.vip]
 *
 * Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：
 *
 * 1.请不要删除和修改根目录下的LICENSE文件。
 * 2.请不要删除和修改Snowy源码头部的版权声明。
 * 3.本项目代码可免费商业使用，商业使用请保留源码和相关描述文件的项目出处，作者声明等。
 * 4.分发源码时候，请注明软件出处 https://www.xiaonuo.vip
 * 5.不可二次分发开源参与同类竞品，如有想法可联系团队xiaonuobase@qq.com商议合作。
 * 6.若您的项目无法满足以上几点，需要更多功能代码，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.biz.modular.depotDevice.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.biz.api.cloud.param.CloudDeviceParam;
import vip.xiaonuo.biz.core.Const.BizStr;
import vip.xiaonuo.biz.core.exception.BizExceptionEnum;
import vip.xiaonuo.biz.modular.depotDevice.param.*;
import vip.xiaonuo.biz.modular.depotDeviceWarn.param.DepotDeviceWarnAddParam;
import vip.xiaonuo.biz.modular.depotDeviceWarn.service.DepotDeviceWarnService;
import vip.xiaonuo.biz.modular.depotGrain.service.DepotGrainService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.depotDevice.entity.DepotDevice;
import vip.xiaonuo.biz.modular.depotDevice.mapper.DepotDeviceMapper;

import javax.annotation.Resource;
import java.util.List;

/**
 * 设备列表Service接口实现类
 *
 * @author xiang
 * @date 2023/09/19 10:12
 **/
@Service
public class DepotDeviceService extends ServiceImpl<DepotDeviceMapper, DepotDevice> {
    @Resource
    DepotGrainService depotGrainService;
    @Resource
    DepotDeviceWarnService deviceWarnService;

    public Page<DepotDevice> page(DepotDevicePageParam param) {
        QueryWrapper<DepotDevice> queryWrapper = new QueryWrapper<>();
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        queryWrapper.lambda().in(CollUtil.isNotEmpty(depotIdLst), DepotDevice::getDepotId, depotIdLst);
        if (ObjectUtil.isNotEmpty(param.getDepotId())) {
            queryWrapper.lambda().eq(DepotDevice::getDepotId, param.getDepotId());
        }
        if (ObjectUtil.isNotEmpty(param.getWeighbridgeType())) {
            queryWrapper.lambda().like(DepotDevice::getWeighbridgeType, param.getWeighbridgeType());
        }
        if (ObjectUtil.isNotEmpty(param.getDeviceGroup())) {
            queryWrapper.lambda().like(DepotDevice::getDeviceGroup, param.getDeviceGroup());
        }
        if (ObjectUtil.isNotEmpty(param.getDeviceType())) {
            queryWrapper.lambda().like(DepotDevice::getDeviceType, param.getDeviceType());
        }
        if (ObjectUtil.isNotEmpty(param.getDeviceName())) {
            queryWrapper.lambda().like(DepotDevice::getDeviceName, param.getDeviceName());
        }
        if (ObjectUtil.isNotEmpty(param.getDeviceTax())) {
            queryWrapper.lambda().like(DepotDevice::getDeviceTax, param.getDeviceTax());
        }
        if (ObjectUtil.isNotEmpty(param.getMainBoardType())) {
            queryWrapper.lambda().like(DepotDevice::getMainBoardType, param.getMainBoardType());
        }
        if (ObjectUtil.isNotEmpty(param.getEntryLift())) {
            queryWrapper.lambda().like(DepotDevice::getEntryLift, param.getEntryLift());
        }
        if (ObjectUtil.isNotEmpty(param.getEntryFall())) {
            queryWrapper.lambda().like(DepotDevice::getEntryFall, param.getEntryFall());
        }
        if (ObjectUtil.isNotEmpty(param.getExitLift())) {
            queryWrapper.lambda().like(DepotDevice::getExitLift, param.getExitLift());
        }
        if (ObjectUtil.isNotEmpty(param.getExitFall())) {
            queryWrapper.lambda().like(DepotDevice::getExitFall, param.getExitFall());
        }
        if (ObjectUtil.isNotEmpty(param.getOnlineState())) {
            queryWrapper.lambda().eq(DepotDevice::getOnlineState, param.getOnlineState());
        }
        if (ObjectUtil.isNotEmpty(param.getMeterType())) {
            queryWrapper.lambda().like(DepotDevice::getMeterType, param.getMeterType());
        }
        if (ObjectUtil.isNotEmpty(param.getContent())) {
            queryWrapper.lambda().like(DepotDevice::getContent, param.getContent());
        }
        if (ObjectUtil.isAllNotEmpty(param.getSortField(), param.getSortOrder())) {
            CommonSortOrderEnum.validate(param.getSortOrder());
            queryWrapper.orderBy(true, param.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(param.getSortField()));
        } else {
            queryWrapper.lambda().orderByDesc(DepotDevice::getId);
        }
        Page page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        //匹配粮库名称
        depotGrainService.putDepotName(page.getRecords());
        return page;
    }

    public List<DepotDevice> lst(DepotDeviceListParam param) {
        LambdaQueryWrapper<DepotDevice> wrapper = new LambdaQueryWrapper<>(BeanUtil.toBean(param, DepotDevice.class));
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.in(CollUtil.isNotEmpty(depotIdLst), DepotDevice::getDepotId, depotIdLst);
        return list(wrapper);
    }

    public DepotDevice getOne(DepotDevice param) {
        LambdaQueryWrapper<DepotDevice> wrapper = new LambdaQueryWrapper<>(param).orderByDesc(DepotDevice::getId);
        List<String> depotIdLst = depotGrainService.lstOrgGrep();
        wrapper.in(CollUtil.isNotEmpty(depotIdLst), DepotDevice::getDepotId, depotIdLst);
        wrapper.last("limit 1");
        List<DepotDevice> list = list(wrapper);
        return list.isEmpty() ? null : list.get(0);
    }

    public void add(DepotDeviceAddParam depotDeviceAddParam) {
        DepotDevice depotDevice = BeanUtil.toBean(depotDeviceAddParam, DepotDevice.class);
        this.save(depotDevice);
    }

    public void edit(DepotDeviceEditParam param) {
        DepotDevice depotDevice = this.queryEntity(param.getId());
        //离线报警
        if (BizStr.DEVICE_ON_LINE.equals(depotDevice.getOnlineState()) && BizStr.DEVICE_OFF_LINE.equals(param.getOnlineState())) {
            deviceWarnService.add(new DepotDeviceWarnAddParam(depotDevice.getDepotId()
                    , depotDevice.getId()
                    , depotDevice.getDeviceName()
                    , depotDevice.getDeviceTax()
                    , depotDevice.getOnlineTime()
                    , StringUtils.join(depotDevice.getDeviceName(), "，上次在线时间：", depotDevice.getOnlineTime())));
        }
        //离线报警处理
        else if (BizStr.DEVICE_OFF_LINE.equals(depotDevice.getOnlineState()) && BizStr.DEVICE_ON_LINE.equals(param.getOnlineState())) {
            deviceWarnService.editStateOnLine(depotDevice.getDepotId(), depotDevice.getId());
        }
        BeanUtil.copyProperties(param, depotDevice);
        this.updateById(depotDevice);
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<DepotDeviceIdParam> depotDeviceIdParamList) {
        // 执行删除
        this.removeBatchByIds(CollStreamUtil.toList(depotDeviceIdParamList, DepotDeviceIdParam::getId));
    }

    public void addByPush(CloudDeviceParam param) {
        DepotDevice depotDevice = BeanUtil.toBean(param, DepotDevice.class);
        this.save(depotDevice);
    }

    public void editByPush(CloudDeviceParam param) {
        DepotDevice depotDevice = this.getOne(new DepotDevice(param.getId(), param.getDepotId()));
        //离线报警
        if (BizStr.DEVICE_ON_LINE.equals(depotDevice.getOnlineState()) && BizStr.DEVICE_OFF_LINE.equals(param.getOnlineState())) {
            deviceWarnService.add(new DepotDeviceWarnAddParam(depotDevice.getDepotId()
                    , depotDevice.getId()
                    , depotDevice.getDeviceName()
                    , depotDevice.getDeviceTax()
                    , depotDevice.getOnlineTime()
                    , StringUtils.join(depotDevice.getDeviceName(), "，上次在线时间：", depotDevice.getOnlineTime())));
        }
        //离线报警处理
        else if (BizStr.DEVICE_OFF_LINE.equals(depotDevice.getOnlineState()) && BizStr.DEVICE_ON_LINE.equals(param.getOnlineState())) {
            deviceWarnService.editStateOnLine(depotDevice.getDepotId(), depotDevice.getId());
        }
        BeanUtil.copyProperties(param, depotDevice);
        this.updateById(depotDevice);
    }

    @Transactional(rollbackFor = Exception.class)
    public void deleteByPush(CloudDeviceParam param) {
        if (ArrayUtil.hasEmpty(param.getId(), param.getDepotId()))
            throw new CommonException(BizExceptionEnum.ERROR00001.getMessage());
        //离线报警处理
        deviceWarnService.editStateOnLine(param.getDepotId(), param.getId());
        // 执行删除
        this.remove(new LambdaQueryWrapper<>(new DepotDevice(param.getId(), param.getDepotId())));
    }

    public DepotDevice detail(DepotDeviceIdParam depotDeviceIdParam) {
        return this.queryEntity(depotDeviceIdParam.getId());
    }

    public DepotDevice queryEntity(String id) {
        DepotDevice depotDevice = this.getById(id);
        if (ObjectUtil.isEmpty(depotDevice)) {
            throw new CommonException("设备列表不存在，id值为：{}", id);
        }
        return depotDevice;
    }

}
