package com.github.wxiaoqi.security.admin.biz;


import com.github.wxiaoqi.security.admin.entity.BranchCompany;
import com.github.wxiaoqi.security.admin.entity.BranchCompanyGive;
import com.github.wxiaoqi.security.admin.mapper.BranchCompanyGiveMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import java.util.List;


@Service
@Slf4j
public class BranchCompanyGiveBiz extends BaseBiz<BranchCompanyGiveMapper, BranchCompanyGive>{


    @Autowired
    BranchCompanyBiz  branchCompanyBiz;


    public void addOrUpdGive(BranchCompanyGive branchCompanyGive){
        Integer isDel = branchCompanyGive.getIsDel() == null ? 0 : branchCompanyGive.getIsDel();
        BranchCompanyGive branchCompanyGive1 = getUserCompanyGive(branchCompanyGive);
        if (branchCompanyGive1 == null){
            insertSelectiveRe(branchCompanyGive);
        }else {
            branchCompanyGive.setId(branchCompanyGive1.getId());
            updateSelectiveById(branchCompanyGive);
        }
        Integer companyId = branchCompanyGive.getCompanyId();
        BranchCompany branchCompany1 = branchCompanyBiz.selectById(companyId);
        if (branchCompany1 != null){
            BranchCompany branchCompany=new BranchCompany();
            branchCompany.setId(companyId);
            Integer giveNum = branchCompany1.getGiveNum() == null ? 0 :branchCompany1.getGiveNum();
            if (isDel == 1){
                giveNum=giveNum > 0 ? (giveNum-1):0;
                branchCompany.setGiveNum(giveNum);
            }else {
                giveNum=giveNum+1;
                branchCompany.setGiveNum(giveNum);
            }
            branchCompanyBiz.addOrUpd(branchCompany);
        }
    }

    public BranchCompanyGive getUserCompanyGive(BranchCompanyGive branchCompanyGive) {
        Example example = new Example(BranchCompanyGive.class);
        example.createCriteria().andEqualTo("userId", branchCompanyGive.getUserId()).andEqualTo("companyId", branchCompanyGive.getCompanyId()).andEqualTo("isDel", 0);
        List<BranchCompanyGive> list = mapper.selectByExample(example);
        if (list != null && list.size() != 0) {
            return list.get(0);
        }
        return null;
    }



}
