package com.huimv.admin.service.secondary.impl;


import com.huimv.admin.domain.secondary.DaLqda;
import com.huimv.admin.domain.secondary.DaZsda;
import com.huimv.admin.repo.secondary.DaLqdaRepository;
import com.huimv.admin.repo.secondary.DaZsdaRepository;
import com.huimv.admin.service.secondary.DaLqdaService;
import com.huimv.admin.utils.Result;
import com.huimv.admin.utils.ResultCode;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.dynamic.datasource.annotation.DS;


import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.Optional;

@Service
@DS("thired")
public class DaLqdaServiceImpl implements DaLqdaService {

	@Autowired
	private DaLqdaRepository rep;

	@Autowired
	private DaZsdaRepository  daZsdaRepository;

	@Override
	public Result add(DaLqda entity){
		if (entity == null){
			return new Result(ResultCode.FAIL);
		}
		//try {    //同时更新猪舍档案   添加数据

			rep.save(entity);


			//存储结束 获取最新一条
			DaLqda daLqda = rep.findlast();
			Integer ids = daLqda.getId();
			Integer zsid = daLqda.getZsid();
			//查找到猪舍档案，存储当前栏期
			DaZsda daZsda = daZsdaRepository.findById(zsid).get();
			daZsda.setDqlq(ids+"");
			daZsdaRepository.save(daZsda);

			/*entity.setMcid(11);
			Integer  id = rep.findMax().get(0);
			entity.setXgsj(new Date());
			DaJqda daJqda =new DaJqda() ;
			daJqda.setZSID(id);
			jqdaRepo.save(daJqda);
			rep.save(entity);*/

			return new Result(ResultCode.SUCCESS);
		//}catch (Exception e){
			//return new Result(ResultCode.FAIL);
		//}
	}


	@Override
	public Result remove(Integer[] ids) {
		if (ids == null || ids.length==0){
			return new Result(ResultCode.FAIL);
		}
		try {
			for (Integer id : ids) {
				rep.deleteById(id);
			}
			return new Result(ResultCode.SUCCESS);
		}catch (Exception e){
			return new Result(ResultCode.FAIL);
		}
	}

	@Override
	public Result update(DaLqda entity) {
		if (entity == null){
			return new Result(ResultCode.FAIL);
		}
		try {
		//entity.setMcid(11);
		//entity.setXgsj(new Date());
			rep.save(entity);
			return new Result(ResultCode.SUCCESS);
		}catch (Exception e){
			return new Result(ResultCode.FAIL);
		}
	}

	@Override
	public Result findAll(String name ,Integer pageNum , Integer pageSize) {
		try {
			Map map = new HashMap();
			int size = rep.findAll().size() ;
			Integer startPage = (pageNum-1) * pageSize;
			List<DaLqda> all = rep.findAll(name,startPage,pageSize);
			map.put("total",size);
			map.put("totalPageNum",(size  +  pageSize  - 1) / pageSize);
			map.put("data",all);

			return new Result(ResultCode.SUCCESS,map);
		}catch (Exception e){
			return new Result(ResultCode.FAIL);
		}
	}



	@Override
	public Result findAllById(Integer id) {
		try {
			DaLqda entity = rep.findById(id).get();
			return new Result(ResultCode.SUCCESS);
		}catch (Exception e){
			return new Result(ResultCode.FAIL);
		}
	}
}
