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.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
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.EleDictMapper;
import com.njcn.energy.pojo.enums.EnergyResponseEnum;
import com.njcn.energy.pojo.param.DictParam;
import com.njcn.energy.pojo.po.EleDict;
import com.njcn.energy.service.IEleDictService;
import com.njcn.web.factory.PageFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * 类的介绍：
 *
 * @author xuyang
 * @version 1.0.0
 * @createTime 2022/3/24 10:59
 */
@Service
public class EleDictServiceImpl extends ServiceImpl<EleDictMapper, EleDict> implements IEleDictService {

    @Override
    public EleDict findDictByName(String name) {
        return this.lambdaQuery().eq(EleDict::getName,name).eq(EleDict::getState, DataStateEnum.ENABLE.getCode()).one();
    }

    @Override
    public EleDict findTableName(String name) {
        EleDict tableDict = new EleDict();
        EleDict dict = this.lambdaQuery().eq(EleDict::getName,name).eq(EleDict::getState, DataStateEnum.ENABLE.getCode()).one();
        if (Objects.isNull(dict)){
            throw new BusinessException(EnergyResponseEnum.NO_DICT);
        } else {
            tableDict = this.lambdaQuery().eq(EleDict::getId,dict.getPid()).eq(EleDict::getPid,0).one();
        }
        if (Objects.isNull(tableDict)){
            throw new BusinessException(EnergyResponseEnum.NO_TABLE);
        }
        return  tableDict;
    }

    @Override
    public boolean delete(String id) {
        LambdaQueryWrapper<EleDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EleDict::getPid,id).eq(EleDict::getState,DataStateEnum.ENABLE.getCode());
        int resCount = this.count(lambdaQueryWrapper);
        if(resCount>0){
            throw new BusinessException(EnergyResponseEnum.CHILDREN_EXIT);
        }

        UpdateWrapper<EleDict> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().eq(EleDict::getState,DataStateEnum.ENABLE.getCode()).set(EleDict::getState,DataStateEnum.DELETED.getCode()).eq(EleDict::getId,id);
        return this.update(updateWrapper);
    }

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

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

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

    }



    @Override
    public EleDict getById(String id) {
        return this.getById(id);
    }


    @Override
    public boolean add(DictParam dictParam) {
        checkName(dictParam,true);
        EleDict eleDict = new EleDict();
        BeanUtils.copyProperties(dictParam,eleDict);
        eleDict.setState(DataStateEnum.ENABLE.getCode());
        return this.save(eleDict);
    }

    @Override
    public boolean update(DictParam.DictUpdateParam dictUpdateParam) {
        checkName(dictUpdateParam,false);
        EleDict eleDict = new EleDict();
        BeanUtils.copyProperties(dictUpdateParam,eleDict);
        return this.updateById(eleDict);

    }




    /**
     * 名称重复校验
     * @author cdf
     * @date 2022/3/23
     */
    private void checkName(DictParam dictParam,boolean flag){
        LambdaQueryWrapper<EleDict> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EleDict::getName,dictParam.getName())
                .eq(EleDict::getState,DataStateEnum.ENABLE.getCode());
        //修改
        if(!flag){
            if(dictParam instanceof DictParam.DictUpdateParam ){
                lambdaQueryWrapper.ne(EleDict::getId,((DictParam.DictUpdateParam)dictParam).getId());
            }
        }
        int res = this.count(lambdaQueryWrapper);
        //大于等于1个则表示重复
        if (res >= 1) {
            throw new BusinessException(EnergyResponseEnum.DIC_NAME_REPEAT);
        }

    }
}
