package com.pj.tb_cooperative;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pj.api.dto.CooperativeDto;
import com.pj.current.satoken.StpUserUtil;
import com.pj.enummj.DeleteStatus;
import com.pj.utils.so.SoMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * Service: tb_cooperative -- 合作社
 * @author lsw
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TbCooperativeService extends ServiceImpl<TbCooperativeMapper,TbCooperative> implements IService<TbCooperative>{

	/** 底层 Mapper 对象 */
	@Autowired
    TbCooperativeMapper tbCooperativeMapper;

	/** 增 */
	void add(TbCooperative t){
		t.setCreateTime(new Date());
		t.setCreateName(StpUserUtil.getPCLoginInfo().getLoginName());
		save(t);
	}

	/** 删 */
	void delete(Long id){
		removeById(id);
	}

	/** 改 */
	void update(TbCooperative t){
		t.setUpdateTime(new Date());
		t.setUpdateName(StpUserUtil.getPCLoginInfo().getLoginName());
		updateById(t);

	}

	/** 查 */
	TbCooperative getById(Long id){
		return super.getById(id);
	}

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


	/*------            正常业务👆👆    rpc远程调用👇👇                         -----------*/

	public CooperativeDto getCooperativeById(Long id) {
		TbCooperative cooperative = tbCooperativeMapper.selectById(id);
		CooperativeDto dto = new CooperativeDto();
		BeanUtils.copyProperties(cooperative, dto);
		return dto;
	}

	/** 远程调用: 对合作社信息进行事务处理 */
	public boolean cooperativeDto(CooperativeDto cooperativeDto){
		TbCooperative tbCooperative = new TbCooperative();
		BeanUtils.copyProperties(cooperativeDto,tbCooperative);
		tbCooperative.setDeleteStatus(DeleteStatus.DELETE_STATUS_ON.getCode());
		tbCooperative.setCreateTime(new Date());
		//查询是否有数据
		List<TbCooperative> tbCooperativeList = tbCooperativeMapper.selectList(new LambdaQueryWrapper<TbCooperative>().eq(TbCooperative::getPlatSeqNo, cooperativeDto.getPlatSeqNo()));
		if(tbCooperativeList.size() == 0){
			//新增
			boolean save = this.save(tbCooperative);
			return save;
		}
		//修改
		BeanUtils.copyProperties(tbCooperativeList.get(0),tbCooperative);
		int i = tbCooperativeMapper.updateById(tbCooperative);
		return i == 1;
	}

}
