package com.ningdatech.carapi.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ningdatech.basic.exception.BaseUncheckedException;
import com.ningdatech.cache.repository.CachePlusOps;
import com.ningdatech.carapi.sys.entity.Operator;
import com.ningdatech.carapi.sys.entity.OperatorRegionHead;
import com.ningdatech.carapi.sys.entity.dto.OperatorSaveDTO;
import com.ningdatech.carapi.sys.entity.dto.OperatorUpdateDTO;
import com.ningdatech.carapi.sys.helper.OperatorsCacheHelper;
import com.ningdatech.carapi.sys.mapper.OperatorMapper;
import com.ningdatech.carapi.sys.service.OperatorRegionHeadService;
import com.ningdatech.carapi.sys.service.OperatorService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 业务实现类
 * 运营商
 * </p>
 *
 * @author PoffyZhang
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OperatorServiceImpl extends ServiceImpl<OperatorMapper, Operator> implements OperatorService {

    private final CachePlusOps cachePlusOps;
    private final OperatorMapper operatorMapper;
    private final OperatorRegionHeadService operatorRegionHeadService;

    private final OperatorsCacheHelper operatorsCacheHelper;

    /**
     *
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeByIdWithCache(List<Long> ids) {
        if (ids.isEmpty()) {
            return true;
        }
        // 运营商
        boolean removeFlag = removeByIds(ids);
        operatorsCacheHelper.refresh(ids);
        //删除区域负责人
        operatorRegionHeadService.remove(Wrappers.lambdaQuery(OperatorRegionHead.class)
                .in(OperatorRegionHead::getOperatorId, ids));
        return removeFlag;
    }


    /**
     * 保存用户
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(OperatorSaveDTO data, Long userId) {
        if(StrUtil.isNotBlank(data.getName())
                && check(data.getName())){
            throw new BaseUncheckedException(HttpStatus.HTTP_OK, "运营商{} 已经存在",
                    data.getName());
        }
        Operator operator = BeanUtil.toBean(data, Operator.class);
        //创建人 最后修改人
        operator.setCreateBy(userId);
        operator.setUpdateBy(userId);
        if(save(operator)){
            operatorsCacheHelper.refresh(operator.getId());
        }
        if(CollUtil.isNotEmpty(data.getOperatorRegionHeads())){
            //先删除 再批量添加
            operatorRegionHeadService.removeByRegionId(operator.getId());
            operatorRegionHeadService.saveBatch(data.getOperatorRegionHeads(),operator.getId(),userId);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(OperatorUpdateDTO data, Long userId) {
        Operator old = operatorMapper.selectById(data.getId());
        if(Objects.isNull(old)){
            throw new BaseUncheckedException(HttpStatus.HTTP_OK,String.format("修改运营商｛｝ 不存在",data.getId()));
        }

        if(StringUtils.isNotBlank(data.getName())){
            Assert.isFalse(check(data.getName(),old.getId()), "运营商名{} 已经存在",
                    data.getName());
        }

        Operator operator = BeanUtil.toBean(data, Operator.class);
        //最后修改人
        operator.setUpdateBy(userId);
        if(updateById(operator)){
            operatorsCacheHelper.refresh(operator.getId());
        }
        if(CollUtil.isNotEmpty(data.getOperatorRegionHeads())){
            //先删除 再批量添加
            operatorRegionHeadService.removeByRegionId(operator.getId());
            operatorRegionHeadService.saveBatch(data.getOperatorRegionHeads(),operator.getId(),userId);
        }
    }

    @Override
    public Boolean check(String name) {
        return super.count(Wrappers.lambdaQuery(Operator.class).eq(Operator::getName, name)) > 0;
    }

    @Override
    public Boolean check(String name,Long id) {
        return super.count(Wrappers.lambdaQuery(Operator.class).ne(Operator::getId,id)
                .eq(Operator::getName, name)) > 0;
    }
}
