/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package com.huimv.modular.collectorregister.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
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.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huimv.core.consts.CommonConstant;
import com.huimv.core.context.login.LoginContextHolder;
import com.huimv.core.enums.CommonStatusEnum;
import com.huimv.core.exception.ServiceException;
import com.huimv.core.factory.PageFactory;
import com.huimv.core.pojo.login.SysLoginUser;
import com.huimv.core.pojo.page.PageResult;
import com.huimv.core.pojo.response.ResponseData;
import com.huimv.core.pojo.response.SuccessResponseData;
import com.huimv.core.util.PoiUtil;
import com.huimv.modular.collectorregister.entity.CollectorRegister;
import com.huimv.modular.collectorregister.enums.CollectorRegisterExceptionEnum;
import com.huimv.modular.collectorregister.mapper.CollectorRegisterMapper;
import com.huimv.modular.collectorregister.param.CollectorRegisterParam;
import com.huimv.modular.collectorregister.service.CollectorRegisterService;
import com.huimv.sys.modular.org.entity.SysOrg;
import com.huimv.sys.modular.org.mapper.SysOrgMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 设备管理service接口实现类
 *
 * @author yinhao
 * @date 2021-08-19 09:43:52
 */
@Service
public class CollectorRegisterServiceImpl extends ServiceImpl<CollectorRegisterMapper, CollectorRegister> implements CollectorRegisterService {

    @Override
    public PageResult<CollectorRegister> page(CollectorRegisterParam collectorRegisterParam) {
        QueryWrapper<CollectorRegister> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(collectorRegisterParam)) {
            Long orgId = LoginContextHolder.me().getSysLoginUserOrgId();
            // 根据组织id 查询
                queryWrapper.lambda().eq(CollectorRegister::getOrgId, orgId);
            if (ObjectUtil.isNotEmpty(collectorRegisterParam.getRegisterTime())) {
                Date registerTime = collectorRegisterParam.getRegisterTime();
                DateTime startTime = DateUtil.beginOfDay(registerTime);
                DateTime endTime = DateUtil.endOfDay(registerTime);
                queryWrapper.lambda().ge(CollectorRegister::getRegisterTime,startTime);
                queryWrapper.lambda().le(CollectorRegister::getRegisterTime,endTime);
            }

            // 根据设备编码查询
            if (ObjectUtil.isNotEmpty(collectorRegisterParam.getPigpenId())) {
                queryWrapper.lambda().like(CollectorRegister::getPigpenId, collectorRegisterParam.getPigpenId());
            }

            // 根据设备编码查询
            if (ObjectUtil.isNotEmpty(collectorRegisterParam.getDeviceCode())) {
                queryWrapper.lambda().like(CollectorRegister::getDeviceCode, collectorRegisterParam.getDeviceCode());
            }
            // 根据状态
            if (ObjectUtil.isNotEmpty(collectorRegisterParam.getCanStatus())) {
                queryWrapper.lambda().like(CollectorRegister::getCanStatus, collectorRegisterParam.getCanStatus());
            }
            //按照最后上传时间倒序
            queryWrapper.lambda().orderByDesc(CollectorRegister::getLastTime);
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    
    @Override
    public List<CollectorRegister> list(CollectorRegisterParam collectorRegisterParam) {
        return this.list();
    }

    @Resource
    private SysOrgMapper sysOrgMapper;

    @Override
    public void add(CollectorRegisterParam collectorRegisterParam) {
        CollectorRegister collectorRegister = new CollectorRegister();
        //之前是拿组织ID  之后添加---现在应该改变这里
        BeanUtil.copyProperties(collectorRegisterParam, collectorRegister);
        Long sysLoginUserOrgId = LoginContextHolder.me().getSysLoginUserOrgId();
        SysOrg sysOrg = sysOrgMapper.selectById(sysLoginUserOrgId);

        collectorRegister.setOrgId(sysLoginUserOrgId);//非省平台不需要这个
        collectorRegister.setOrgName(sysOrg.getName());//非省平台不需要这个
        this.save(collectorRegister);
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<Integer> ids) {
        ids.forEach(this::removeById);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(CollectorRegisterParam collectorRegisterParam) {
        CollectorRegister collectorRegister = this.queryCollectorRegister(collectorRegisterParam);
        BeanUtil.copyProperties(collectorRegisterParam, collectorRegister);
        this.updateById(collectorRegister);
    }

    @Override
    public CollectorRegister detail(CollectorRegisterParam collectorRegisterParam) {
        return this.queryCollectorRegister(collectorRegisterParam);
    }

    /**
     * 获取设备管理
     *
     * @author yinhao
     * @date 2021-08-19 09:43:52
     */
    private CollectorRegister queryCollectorRegister(CollectorRegisterParam collectorRegisterParam) {
        CollectorRegister collectorRegister = this.getById(collectorRegisterParam.getId());
        if (ObjectUtil.isNull(collectorRegister)) {
            throw new ServiceException(CollectorRegisterExceptionEnum.NOT_EXIST);
        }
        return collectorRegister;
    }

    @Override
    public ResponseData selectPcEveryStatusCollectors(Long orgId) {
        if (ObjectUtil.isEmpty(orgId)){
             orgId = LoginContextHolder.me().getSysLoginUserOrgId();
        }


        LambdaQueryWrapper<CollectorRegister> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(CollectorRegister::getOrgId, orgId);

        Map<String, Integer> map = new LinkedHashMap<>();
        map.put("total", count(lambdaQuery));

        lambdaQuery.eq(CollectorRegister::getCanStatus, 0);
        map.put("normal", count(lambdaQuery));

        lambdaQuery.clear();
        lambdaQuery.eq(CollectorRegister::getOrgId, orgId);
        lambdaQuery.ne(CollectorRegister::getCanStatus, 0);
        map.put("abnormal", count(lambdaQuery));

        lambdaQuery.clear();
        lambdaQuery.eq(CollectorRegister::getOrgId, orgId);
        lambdaQuery.eq(CollectorRegister::getCanStatus, 3);
        map.put("logout", count(lambdaQuery));

        return  new SuccessResponseData(map);
    }
}
