package com.gree.mall.manager.logic.brand;

import com.gree.mall.manager.exception.RemoteServiceException;
import org.apache.commons.lang3.StringUtils;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.Brand;
import com.gree.mall.manager.plus.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class BrandLogic {

    @Autowired
    CommonLogic commonLogic;
    @Autowired
    BrandService brandService;

    public List<Brand> list(){
        AdminUserCom adminUser = commonLogic.getAdminUser();
        return brandService.lambdaQuery()
                .orderByAsc(Brand::getSortNum)
                .eq(StringUtils.isNotBlank(adminUser.getCompanyWechatId()),Brand::getCompanyWechatId,adminUser.getCompanyWechatId())
                .list();
    }

    public void save(Brand brand, HttpServletRequest request){
        AdminUserCom adminUser = commonLogic.getAdminUser(request);
        if(StringUtils.isBlank(brand.getId())){
            brand.setCreateTime(new Date());
            brand.setCreateBy(adminUser.getNickName());
            brand.setUpdateBy(adminUser.getNickName());
            brand.setUpdateTime(new Date());
        }else{
            brand.setUpdateBy(adminUser.getNickName());
            brand.setUpdateTime(new Date());
        }
        brand.setCompanyWechatId(adminUser.getCompanyWechatId());
        brand.setCompanyWechatName(adminUser.getCompanyName());

        Integer count = brandService.lambdaQuery()
                .eq(Brand::getCompanyWechatId, brand.getCompanyWechatId())
                .eq(Brand::getBrandName, brand.getBrandName())
                .ne(StringUtils.isNotBlank(brand.getId()), Brand::getId, brand.getId())
                .count();

        if (count > 0) {
            throw new RemoteServiceException(brand.getBrandName() + "品牌名称已存在, 请检查");
        }

        brand.insertOrUpdate();
    }

    public Brand detail(String id){
        return brandService.getById(id);
    }

    public void delete(String id){
        brandService.removeById(id);
    }

}
