package com.bcxin.ins.service.order.impl;

import com.bcxin.ins.dao.order.InsTopBuyersAPIDao;
import com.bcxin.ins.service.order.InsBuyersAPIService;
import com.bcxin.ins.service.order.InsTopBuyersAPIService;
import com.bcxin.ins.core.entity.SysUser;
import com.bcxin.ins.entity.common.ComBuyers;
import com.bcxin.ins.entity.policy_special.StTopBuyers;
import com.bcxin.ins.util.MyConverUtil;
import com.bcxin.ins.util.toolbox.DateUtil;
import com.bcxin.ins.util.toolbox.StrUtil;
import com.bcxin.ins.vo.BuyersVo_two;
import com.bcxin.ins.vo.ConstProp;
import com.bcxin.ins.vo.DwzPage;
import com.bcxin.ins.vo.TopBuyersVo;
import com.bcxin.mybatisplus.plugins.Page;
import com.bcxin.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


@Service
@Transactional
public class InsTopBuyersAPIServiceImpl extends ServiceImpl<InsTopBuyersAPIDao, StTopBuyers> implements InsTopBuyersAPIService {


	@Autowired
	private InsTopBuyersAPIDao dao;
	@Autowired
	private InsBuyersAPIService insBuyersService;

	/**
	 * <b>根据id查询 InsTopBuyers</b>
	 *
	 * @param oid ins_top_buyers_id
	 * @return
	 * @author ZXF
	 * @date 2017年1月5日 下午5:28:44
	 * @注意事项 </b>
	 * <b>
	 */
	@Override
	public StTopBuyers packagingInsTopBuyers(Long oid) {
		return dao.getInsTopBuyers(oid);
	}

	/**
	 * <b>通过特殊短期字段表id查询所有关联买家 </b>
	 *
	 * @param oid
	 * @return
	 * @author ZXF
	 * @date 2017年1月5日 下午4:59:37
	 * @注意事项 </b>
	 * <b>
	 */
	@Override
	public List<StTopBuyers> selectInsTopBuyersBySpecialID(Long oid) {
		return dao.selectInsTopBuyersBySpecialID(oid);
	}

	/**
	 * <b>接收页面传回的投保的前十大买家信息列表进行更新 </b>
	 *
	 * @param voList 投保的前十大买家信息列表
	 * @param special_id 企业短期出口表id
	 * @author ZXF
	 * @date 2017年1月8日 上午11:39:35
	 * @注意事项 </b>
	 * <b>
	 */
	@Override
	public void setTopBuyersByTopBuyersVo(List<TopBuyersVo> voList, Long special_id){
		if(voList != null && voList.size()>ConstProp.INT_NUMBER_ZERO){
			ruleOutDoesNotExist(voList, special_id);
			for(TopBuyersVo vo : voList){
				accordingToTheTopBuyersVoSetUpInsTopBuyers(vo,special_id);
			}
		}
	}

	/**
	 * <b>排除数据库存在的但页面被删除的条目信息，获取这些条目并删除 </b>
	 *
	 * @param voList
	 * @param special_id
	 * @author ZXF
	 * @date 2017年1月13日 上午10:59:02
	 * @注意事项 </b>
	 * <b>
	 */
	private void ruleOutDoesNotExist(List<TopBuyersVo> voList,
									 Long special_id) {
		List<StTopBuyers> tbList = selectInsTopBuyersBySpecialID(special_id);
		for(StTopBuyers itb : tbList){
			int i = ConstProp.INT_NUMBER_ZERO;
			for(TopBuyersVo vo : voList){
				if(StrUtil.isNotBlank(vo.getOid())){
					if(itb.getSt_top_buyers_id() == Long.parseLong(vo.getOid())){
						i = ConstProp.INT_NUMBER_ONE;
					}
				}
			}
			if(i == 0){
				dao.deleteById(itb.getSt_top_buyers_id());
			}
		}
	}

	/**
	 * <b>根据Vo及短期出口ID更新InsTopBuyers数据 </b>
	 * 注：同时关联全球买家表
	 * @param vo
	 * @param special_id 短期出口特殊字段表id
	 * @author ZXF
	 * @date 2017年1月7日 下午4:26:25
	 * @注意事项 </b>
	 * <b>
	 */
	@Override
	public void accordingToTheTopBuyersVoSetUpInsTopBuyers(TopBuyersVo vo,Long special_id){
		StTopBuyers insTopBuyers = null;
		ComBuyers insBuyers = null;
		if(StrUtil.isNotBlank(vo.getOid())){
			insTopBuyers = dao.selectById(Long.parseLong(vo.getOid()));
			insBuyers = insBuyersService.selectById(insTopBuyers.getCom_buyer().getCom_buyer_id());
			insTopBuyers.setUpdate_time(DateUtil.getTimestamp());
			insTopBuyers.setCom_buyer(insBuyers);
		}else{
			insTopBuyers = new StTopBuyers();
			insTopBuyers.setCreate_time(DateUtil.getTimestamp());
			insTopBuyers.setSpecial_id(special_id);

			if(StrUtil.isNotBlank(vo.getCode())){
				insBuyers = insBuyersService.selectInsBuyersByCode(vo.getCode());
				if(insBuyers == null){
					insBuyers = insBuyersService.selectInsBuyersBySomeField(vo.getCustomer_name(), vo.getAddress(), vo.getCountry());
				}
			}else{
				insBuyers = insBuyersService.selectInsBuyersBySomeField(vo.getCustomer_name(), vo.getAddress(), vo.getCountry());
			}
			insTopBuyers.setCom_buyer(insBuyers);
			dao.insert(insTopBuyers);
		}
		try {
			MyConverUtil.map2PO(MyConverUtil.PO2Map(vo), insTopBuyers);
		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			MyConverUtil.map2PO(MyConverUtil.PO2Map(vo), insBuyers);
		} catch (Exception e) {
			e.printStackTrace();
		}
		insBuyersService.updateById(insBuyers);
		insTopBuyers.setApply_type(ConstProp.DIGIT_ZERO);//设置为申请中
		if(vo.getUser_id()!=null){
			insTopBuyers.setUser_id(vo.getUser_id());
		}
		dao.updateById(insTopBuyers);
	}

	/**
	 * <b>根据企业短期id查询所有关联买家信息列表插入到TopBuyersVo集合 </b>
	 *
	 * @param special_id 企业短期id
	 * @author ZXF
	 * @date 2017年1月8日 上午11:39:35
	 * @注意事项 </b>
	 * <b>
	 */
	@Override
	public List<TopBuyersVo> getTopBuyersVoListBySpecialID(Long special_id){
		List<TopBuyersVo> voList = new ArrayList<TopBuyersVo>();
		List<StTopBuyers> bList = selectInsTopBuyersBySpecialID(special_id);
		if(bList != null && bList.size()>0){
			for(StTopBuyers tb : bList){
				voList.add(accordingToInsTopBuyersIntoTopBuyersVo(tb));
			}
		}
		return voList;
	}

	/**
	 * <b>根据前十大买家信息转换成 TopBuyersVo</b>
	 *
	 * @param tb 前十大买家信息
	 * @return
	 * @author ZXF
	 * @date 2017年1月8日 下午2:22:26
	 * @注意事项 </b>
	 * <b>
	 */
	@Override
	public TopBuyersVo accordingToInsTopBuyersIntoTopBuyersVo(StTopBuyers tb){
		TopBuyersVo vo = new TopBuyersVo();
		if(tb == null){
			return vo;
		}
		vo.setOid(String.valueOf(tb.getSt_top_buyers_id()));
		try {
			MyConverUtil.map2PO(MyConverUtil.PO2Map(tb), vo);
			MyConverUtil.map2PO(MyConverUtil.PO2Map(tb.getCom_buyer()), vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vo;
	}


	/**
	 *  取消申请状态
	 */
	@Override
	public boolean updateTopBuyerForDelStatus(Long oid) {
		StTopBuyers buyers= selectById(oid);
		buyers.setApply_type(ConstProp.DIGIT_FOUR);
		dao.updateById(buyers);
//		2	已批复
//		1	拒批
//		0	申请中
//		3	正常
//		4	取消申请

		return false;
	}

	@Override
	public List<StTopBuyers> findTopBuyers(Page<StTopBuyers> phPage,DwzPage page,TopBuyersVo  buyersVo) {
		List<StTopBuyers> bList = dao.findTopBuyers(phPage,buyersVo);
		return bList;
	}


	@Override
	public List<StTopBuyers> getInsTopBuyersByOrderFormId(Long orderFormId, DwzPage page) {
		Page<StTopBuyers> pageHelper = new Page(page.getPageNum(), page.getNumPerPage());
		List<StTopBuyers> lis = dao.getInsTopBuyersByOrderFormId(pageHelper,orderFormId);
		page.setTotalCount(new Long(pageHelper.getTotal()).intValue());
		if(null != lis){
			return lis;
		}else{
			return null;
		}
	}

	/**
	 *  根据全球买家信息 填充vo
	 */
	@Override
	public TopBuyersVo accordingToInsBuyersIntoTopBuyersVo(ComBuyers insBuyers) {
		TopBuyersVo vo = new TopBuyersVo();
		if(insBuyers == null){
			return vo;
		}
		vo.setOid(String.valueOf(insBuyers.getCom_buyer_id()));
		try {
			MyConverUtil.map2PO(MyConverUtil.PO2Map(insBuyers), vo);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return vo;
	}


	@Override
	public List<BuyersVo_two> getBuyersVoTwoByOrderFormId(Long orderFormId, DwzPage page) {
		Page<BuyersVo_two> pageHelper = new Page<>(page.getPageNum(), page.getNumPerPage());
		List<BuyersVo_two> lis = dao.getBuyersVoTwoByOrderFormId(pageHelper,orderFormId);
		page.setTotalCount(new Long(pageHelper.getTotal()).intValue());
		return lis.size() > ConstProp.INT_NUMBER_ZERO ? lis : null;
	}

	/**
	 * 后台 查询 个人额度 的订单类表（短期）
	 */
	@Override
	public List<TopBuyersVo> findTopBuyersOrder(DwzPage page, SysUser user) {

		return dao.findTopBuyersOrder(page,user.getId());
	}

	/**
	 *后台    根据  oid  查询 个人额度
	 */
	@Override
	public TopBuyersVo getBuyersVoById(Long oid) {

		return dao.getBuyersVoById(oid);
	}


	@Override
	public List<StTopBuyers> selectInsTopBuyersListBySpecialID(DwzPage page, TopBuyersVo topBuyersVo) {
		Page<StTopBuyers> pageHelper = new Page<>(page.getPageNum(), page.getNumPerPage());
		List<StTopBuyers> list= dao.selectInsTopBuyersListBySpecialID(pageHelper,topBuyersVo);
		page.setTotalCount(new Long(pageHelper.getTotal()).intValue());
		return list;
	}

	@Override
	public boolean updTopFreeAmount(String oid, Long userId, Long status, BigDecimal amount) {

		StTopBuyers  topBuyers =dao.selectById(oid);
		BigDecimal  replyAmount =topBuyers.getReply_amount();//批复总额
		BigDecimal  unUserdAmount=topBuyers.getUnused_amount();//现在可用额度
		BigDecimal  userdAmount=topBuyers.getUnused_amount();//已使用额度
////				  可以通过BigDecimal的compareTo方法来进行比较.
////				  返回的结果是int类型,-1表示小于,0是等于,1是大于.
////				  加:   a.add(b);
////				　　减: a.subtract(b);
////				　　乘:   a.multiply(b);
////				　　除:   a.divide(b,2);//2为精度取值
		if(status==1){//申请额度
			if(!(unUserdAmount.compareTo(amount)<0)){//未使用的额度大于申请额度
				topBuyers.setUnused_amount(unUserdAmount.subtract(amount));
				topBuyers.setUserd_amount(userdAmount.add(amount));
				dao.updateById(topBuyers);
				return true;
			}

		}else if(status==2){//取消申请额度
			if(!(replyAmount.compareTo(unUserdAmount.add(amount))<0)){//如果总申请的额度 大于  （取消申请 + 本身未使用的额度）
				topBuyers.setUnused_amount(unUserdAmount.add(amount));
				topBuyers.setUserd_amount(userdAmount.subtract(amount));
				dao.updateById(topBuyers);
				return true;
			}

		}

		return false;

	}

	@Override
	public List<BuyersVo_two> findBuyersListByOrderFormIdAndSearch(Long orderFormId, DwzPage page, String countrySearch,String companySearch) {
		Page<BuyersVo_two> pageHelper = new Page(page.getPageNum(), page.getNumPerPage());
		List<BuyersVo_two> lis = dao.findBuyersListByOrderFormIdAndSearch(pageHelper,orderFormId, countrySearch, companySearch);
		page.setTotalCount(new Long(pageHelper.getTotal()).intValue());
		return lis.size() > ConstProp.INT_NUMBER_ZERO ? lis : null;
	}


	@Override
	public Long getInsTopBuyerPifu(Long userId) {

		return dao.getInsTopBuyerPifu(userId);
	}


	@Override
	public Long getInsTopBuyerWPifu(Long userId) {

		return dao.getInsTopBuyerWPifu(userId);
	}

	@Override
	public List<TopBuyersVo> findPifuList(Long userId,  DwzPage page, String statusType) {
		Page<TopBuyersVo> pageHelper = new Page(page.getPageNum(), page.getNumPerPage());
		List<TopBuyersVo> list = Lists.newArrayList();
		if(statusType.equals(ConstProp.DIGIT_ZERO)){
			//未批复
			list = dao.findNoPifuList(pageHelper,userId);
		}
		else if(statusType.equals(ConstProp.DIGIT_ONE)){
			//已批复
			list = dao.findPifuList(pageHelper,userId);
		}
		page.setTotalCount(new Long(pageHelper.getTotal()).intValue());
		return list;
	}

	/**
	 * 查询添加的买家  在该订单中是否 重复
	 *
	 * @param country
	 * @param city
	 * @param customer_name
	 * @param oid
	 */
	@Override
	public Long findTopBuyersBySerach(String country, String city, String customer_name,String spid ,String oid) {
		return dao.findTopBuyersBySerach(country,city,customer_name,spid,oid);


//		select t.special_id, b.* from  ins_top_buyers  t
//		LEFT JOIN    ins_buyers  b  on b.id =t.buyers_id
//		where
//
//		b.country  ='中国'  and b.city='33'  and  b.customer_name='第三方'
//		and t.special_id='818807861584224256'
//      and  t.id !=''


	}


}
