package com.platform.service.custom;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.entity.TmBrandAdmin;
import com.platform.enums.IdStarterEnum;
import com.platform.service.impl.TmBrandAdminServiceImpl;
import com.platform.utils.UUidGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author abnerhou
 * @date 2020/9/18 15:39
 * @desciption
 */
@Service
@Slf4j
public class TmBrandAdminService extends TmBrandAdminServiceImpl {

    public int addNew(TmBrandAdmin tmBrandAdmin){
        if(null == tmBrandAdmin){
            return -1;
        }
        tmBrandAdmin.setRelationId(UUidGenerator.generatorUuid(IdStarterEnum.DEFAULT_ID.getStarter()));
        tmBrandAdmin.setEnable(1);
        tmBrandAdmin.setCreateTime(LocalDateTime.now());
        tmBrandAdmin.setUpdateTime(LocalDateTime.now());
        return getBaseMapper().insert(tmBrandAdmin);
    }

    @Transactional(rollbackFor = Exception.class)
    public int updateRation(TmBrandAdmin tmBrandAdmin){
        if(null == tmBrandAdmin || StringUtils.isBlank(tmBrandAdmin.getRelationId())){
            return -1;
        }
        UpdateWrapper<TmBrandAdmin> update = new UpdateWrapper<>();
        update.eq("relation_id" , tmBrandAdmin.getRelationId());
        update.last("limit 1");
        tmBrandAdmin.setUpdateTime(LocalDateTime.now());
        return getBaseMapper().update(tmBrandAdmin , update);
    }

    public TmBrandAdmin getByAdminIdAndBrandId(int adminId , int brandId){

        QueryWrapper<TmBrandAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id" , adminId);
        queryWrapper.eq("brand_id" , brandId);
        queryWrapper.eq("enable" , 1);
        queryWrapper.last("limit 1");
        return getBaseMapper().selectOne(queryWrapper);
    }

    public long countUserRelation(int adminId){
        QueryWrapper<TmBrandAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id" , adminId);
        queryWrapper.eq("enable" , 1);
        IPage<TmBrandAdmin> page = new Page<>(1 , 10);
        IPage<TmBrandAdmin> resultPage = new Page<>();
        resultPage = getBaseMapper().selectPage(page , queryWrapper);
        if(null == resultPage){
            return 0;
        }
        return resultPage.getTotal();
    }
}
