package com.njcn.energy.service.impl;


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.njcn.common.pojo.enums.common.DataStateEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.db.constant.DbConstant;
import com.njcn.energy.mapper.NetDevMapper;
import com.njcn.energy.pojo.constant.ModelState;
import com.njcn.energy.pojo.enums.EnergyResponseEnum;
import com.njcn.energy.pojo.param.NetDevParam;
import com.njcn.energy.pojo.po.NetDev;
import com.njcn.energy.pojo.vo.NetDevInfoVO;
import com.njcn.energy.service.INetDevService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njcn.web.factory.PageFactory;
import com.njcn.web.utils.RequestUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cdf
 * @since 2022-02-22
 */
@Service
public class NetDevServiceImpl extends ServiceImpl<NetDevMapper, NetDev> implements INetDevService {


    @Override
    public Page<NetDev> listNetDev(NetDevParam.NetDevQueryParam queryParam) {
        QueryWrapper<NetDev> queryWrapper = new QueryWrapper<>();
        if(Objects.nonNull(queryParam)){
            //查询参数不为空，进行条件填充
            if(StrUtil.isNotBlank(queryParam.getSearchValue())){
                //字典类型表，仅提供名称、编码模糊查询
                queryWrapper
                        .and(param -> param.like("ele_net_dev.name",queryParam.getSearchValue())
                        .or().like("ele_net_dev.ndid",queryParam.getSearchValue()));
            }

            //排序
            if (ObjectUtil.isAllNotEmpty(queryParam.getSortBy(), queryParam.getOrderBy())) {
                queryWrapper.orderBy(true, queryParam.getOrderBy().equals(DbConstant.ASC), StrUtil.toUnderlineCase(queryParam.getSortBy()));
            }else{
                //没有排序参数，默认根据sort字段排序，没有排序字段的，根据updateTime更新时间排序
                queryWrapper.orderBy(true, true, "ele_net_dev.sort");
            }

        }
        queryWrapper.eq("ele_net_dev.state", DataStateEnum.ENABLE.getCode());
        return this.baseMapper.selectPage(new Page<>(PageFactory.getPageNum(queryParam),PageFactory.getPageSize(queryParam)),queryWrapper);
    }

    @Override
    public boolean addNetDev(NetDevParam netDevParam) {
        checkDicTypeName(netDevParam,false);
        NetDev netDev = new NetDev();
        BeanUtils.copyProperties(netDevParam, netDev);
        netDev.setState(DataStateEnum.ENABLE.getCode());
        netDev.setCreateBy(RequestUtil.getUserIndex());
        return this.save(netDev);
    }

    @Override
    public boolean updateNetDev(NetDevParam.NetDevUpdateParam updateParam) {
        checkDicTypeName(updateParam,true);
        NetDev netDev = new NetDev();
        BeanUtils.copyProperties(updateParam, netDev);
        netDev.setUpdateBy(RequestUtil.getUserIndex());
        return this.updateById(netDev);
    }

    @Override
    public boolean deleteNetDev(List<String> ids) {
        return this.lambdaUpdate()
                .set(NetDev::getState, DataStateEnum.DELETED.getCode())
                .in(NetDev::getId,ids)
                .update();
    }



    @Override
    public NetDev findByNdid(String ndid) {
        return this.lambdaQuery().eq(NetDev::getNdid,ndid).one();
    }

    @Override
    public NetDevInfoVO getNetDevInfo(String id){
       return this.baseMapper.getNetDevDetail(id);
    }

    @Override
    public void offlineNetDev(String netDev) {
        this.lambdaUpdate()
                .set(NetDev::getComFlag, ModelState.UNREGISTER)
                .eq(NetDev::getId,netDev)
                .update();
    }

    @Override
    public void onlineNetDev(String netDev) {
        this.lambdaUpdate()
                .set(NetDev::getComFlag, DataStateEnum.ENABLE.getCode())
                .eq(NetDev::getId,netDev)
                .update();
    }

    @Override
    public List<NetDev> getAllNetDev() {
        return this.lambdaQuery().eq(NetDev::getState,DataStateEnum.ENABLE.getCode()).list();
    }

    /**
     * 校验参数，检查是否存在相同名称的字典类型
     */
    private void checkDicTypeName(NetDevParam netDevParam, boolean isExcludeSelf) {
        LambdaQueryWrapper<NetDev> netDevLambdaQueryWrapper = new LambdaQueryWrapper<>();
        netDevLambdaQueryWrapper
                .eq(NetDev::getName,netDevParam.getName())
                .eq(NetDev::getState,DataStateEnum.ENABLE.getCode());
        //更新的时候，需排除当前记录
        if(isExcludeSelf){
            if(netDevParam instanceof NetDevParam.NetDevUpdateParam){
                netDevLambdaQueryWrapper.ne(NetDev::getId,((NetDevParam.NetDevUpdateParam) netDevParam).getId());
            }
        }
        int countByAccount = this.count(netDevLambdaQueryWrapper);
        //大于等于1个则表示重复
        if (countByAccount >= 1) {
            throw new BusinessException(EnergyResponseEnum.NET_DEV_NAME_REPEAT);
        }
    }
}
