package com.pj.project.tb_declare;

import java.util.List;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.project.tb_business.TbBusiness;
import com.pj.project.tb_business.TbBusinessService;
import com.pj.utils.so.SoMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.pj.utils.sg.*;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * Service: tb_declare --
 *
 * @author lzm
 */
@Service
@Transactional
public class TbDeclareService extends ServiceImpl<TbDeclareMapper, TbDeclare> implements IService<TbDeclare> {

    /**
     * 底层 Mapper 对象
     */
    @Autowired
    TbDeclareMapper tbDeclareMapper;

    @Resource
    private TbBusinessService tbBusinessService;

    /**
     * 增
     */
    int add(TbDeclare t) {
        return tbDeclareMapper.add(t);
    }

    /**
     * 删
     */
    int delete(Long id) {
        return tbDeclareMapper.delete(id);
    }

    /**
     * 改
     */
    int update(TbDeclare t) {
        String declareNo = t.getDeclareNo();
        TbDeclare db = this.getById(t.getId());
        if (StrUtil.isEmpty(t.getBusinessId())) {
            t.setBusinessId(null);
            this.rebackDeclareNo(declareNo);
        }
        if (StrUtil.equals(db.getSendUnit(), t.getSendUnit())) {
           TbBusiness tbBusiness= tbBusinessService.findByDeclareNo(db.getDeclareNo());
           if (tbBusiness!=null){
               tbBusiness.setOwner(t.getSendUnit());
           }
        }
        return tbDeclareMapper.update(t);
    }

    /**
     * 查
     */
    TbDeclare getById(Long id) {
        return tbDeclareMapper.getById(id);
    }

    /**
     * 查集合 - 根据条件（参数为空时代表忽略指定条件）
     */
    public List<TbDeclare> getList(SoMap so) {
        return tbDeclareMapper.getList(so);
    }


    public TbDeclare findByDeclareNo(String declareNo) {
        QueryWrapper<TbDeclare> ew = new QueryWrapper<>();
        ew.eq("declare_no", declareNo);
        return getOne(ew);
    }


    public void removeBusinessId(String businessId) {
        tbDeclareMapper.removeBusinessId(businessId);
    }

    public void rebackDeclareNo(String declareNo) {
        tbDeclareMapper.rebackDeclareNo(declareNo);
    }
}
