package cn.com.countrygarden.bi.main.service.investment.impl;

import cn.com.countrygarden.bi.main.model.PageData;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.transaction.Transactional;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.AccessToken;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.countrygarden.bi.main.model.investment.InvestProjectAccount;
import cn.com.countrygarden.bi.main.model.investment.InvestProjectInvestment;
import cn.com.countrygarden.bi.main.model.investment.InvestProjectProfit;
import cn.com.countrygarden.bi.main.model.investment.InvestRegionInvestment;
import cn.com.countrygarden.bi.main.model.investment.InvestRegionTotal;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;
import cn.com.countrygarden.bi.main.dao.investment.InvestProjectAccountMapper;
import cn.com.countrygarden.bi.main.dao.investment.InvestProjectInvestmentMapper;
import cn.com.countrygarden.bi.main.dao.investment.InvestProjectProfitMapper;
import cn.com.countrygarden.bi.main.dao.investment.InvestRegionInvestmentMapper;
import cn.com.countrygarden.bi.main.dao.investment.InvestRegionTotalMapper;
import cn.com.countrygarden.bi.main.dto.investment.InvestProjectAppVO;
import cn.com.countrygarden.bi.main.dto.investment.InvestProjectExcelVO;
import cn.com.countrygarden.bi.main.dto.investment.InvestProjectProfitVo;
import cn.com.countrygarden.bi.main.dto.investment.InvestRegionTotalVo;
import cn.com.countrygarden.bi.main.dto.investment.RegionInvestmentAndProjectAccountVO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.investment.InvestProjectAccountService;
import cn.com.countrygarden.bi.main.service.investment.InvestProjectProfitService;
import cn.com.countrygarden.bi.main.service.investment.InvestRegionInvestmentService;
import cn.com.countrygarden.bi.main.service.twerp.hm.TbSysOrganService;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example.Criteria;
import cn.com.countrygarden.bi.main.core.Response;

/**
 * 个人区域投资-业务逻辑层实现
 *
 * @author 汤婷
 * @email www.justintoforest@gamail.com
 * @url
 * @date 2018-08-20
 */
@Service
@Transactional
public class InvestRegionInvestmentServiceImpl implements InvestRegionInvestmentService {
	@Autowired
	private InvestProjectAccountService investProjectAccountService;
	@Autowired
	private InvestRegionInvestmentMapper investRegionInvestmentMapper;
	@Autowired
	private InvestProjectInvestmentMapper investProjectInvestmentMapper;
	@Autowired
	private InvestRegionTotalMapper investRegionTotalMapper;
	@Autowired
	private InvestProjectProfitMapper investProjectProfitMapper;

	@Autowired
	private InvestProjectProfitService investProjectProfitService;

	@Autowired
	private TbSysOrganService tbSysOrganService;
	@Autowired
	private InvestProjectAccountMapper investProjectAccountMapper;
	// private Map<String, String> investRegionTotalId = null;

	public Result queryPageList(InvestRegionInvestment investRegionInvestment, AccessToken accessToken) {
		TbSysOrgan tbSysOrgan = tbSysOrganService.findByUserCode(accessToken.getUserCode());
		if (tbSysOrgan == null) {
			tbSysOrgan = new TbSysOrgan();
		}

		String regionId = investRegionInvestment.getRegionId();
		String projectId = investRegionInvestment.getProjectId();
		String userName = investRegionInvestment.getUserName();

		return Response.response(investRegionInvestmentMapper.selectInvestRegionInvestmentlist(regionId, projectId,
				userName, tbSysOrgan.getOrganCode()));
	}

	// 验证bip是否已经存在，一个bip只能投一个区域，可以连续投
	public Result validateBIP(InvestRegionInvestment investRegionInvestment) {
		Condition condition = new Condition(InvestRegionInvestment.class);
		Criteria criteria = condition.createCriteria();
		criteria.andEqualTo("bipUserAccount", investRegionInvestment.getBipUserAccount());

		// 编辑排除当前个人投资id
		if (investRegionInvestment.getId() != null && investRegionInvestment.getId() != 0) {
			criteria.andNotEqualTo("id", investRegionInvestment.getId());

		}

		if (investRegionInvestmentMapper.selectCountByCondition(condition) > 0) {
			return Response.response("bipExist");
		} else {
			return Response.response("ok");
		}

	}

	public Result queryById(Integer id) {
		RegionInvestmentAndProjectAccountVO investmentAndProjectAccountVO = new RegionInvestmentAndProjectAccountVO();
		InvestRegionInvestment investRegionInvestment = investRegionInvestmentMapper.selectByPrimaryKey(id);
		Condition condition = new Condition(InvestProjectAccount.class);
		condition.createCriteria().andEqualTo("investRegionInvestmentId", id);
		List<InvestProjectAccount> investProjectAccountList = investProjectAccountMapper.selectByCondition(condition);
		if (investProjectAccountList.size() < 1) {
			InvestProjectAccount investProjectAccount = new InvestProjectAccount();
			investProjectAccount.setFollowCapitalAccountTime(new Date());

			investProjectAccountList.add(investProjectAccount);
		}
		investmentAndProjectAccountVO.setInvestRegionInvestment(investRegionInvestment);
		investmentAndProjectAccountVO.setProjectAccountList(investProjectAccountList);
		return Response.response(investmentAndProjectAccountVO);
	}

	public Result edit(InvestRegionInvestment investRegionInvestment,
			List<InvestProjectAccount> investProjectAccountList, AccessToken accessToken) {
		// 删除个人投资项目利益后重新再计算添加

		Condition condition = null;
		condition = new Condition(InvestProjectProfit.class);
		condition.createCriteria().andEqualTo("personInvestmentId", investRegionInvestment.getId());
		investProjectProfitMapper.deleteByCondition(condition);
		investRegionInvestment.setFinancialIncomeCapital(new BigDecimal(0));
		investRegionInvestment.setFinancialIncomeCapitalAccount(new BigDecimal(0));
		investRegionInvestment.setRaisingBalanceCapital(new BigDecimal(0));
		investRegionInvestment.setRaisingBalanceCapitalAccount(new BigDecimal(0));
		investRegionInvestment.setAvailableBalanceCapital(new BigDecimal(0));
		investRegionInvestment.setAvailableBalanceCapitalAccount(new BigDecimal(0));
		investRegionInvestment.setUpdateBy(accessToken.getUserCode());
		investRegionInvestment.setUpdateTime(new Date());
		// 删除个人单独资金跟投后重新添加
		condition = new Condition(InvestProjectAccount.class);
		condition.createCriteria().andEqualTo("investRegionInvestmentId", investRegionInvestment.getId());
		investProjectAccountMapper.deleteByCondition(condition);
		condition = new Condition(InvestProjectInvestment.class);
		condition.createCriteria().andEqualTo("regionId", investRegionInvestment.getRegionId());
		int count = investProjectInvestmentMapper.selectCountByCondition(condition);
		if (count < 1) {
			investRegionInvestment.setFollowCapitalAccount(new BigDecimal(0));
		} else {
			investProjectAccountService.addinvestProjectAccountList(investRegionInvestment, investProjectAccountList);
		}

		List<InvestRegionInvestment> investRegionInvestmentList = new ArrayList<InvestRegionInvestment>();

		List<InvestProjectInvestment> investProjectInvestmentList = null;

		// 1.当前区域没有项目时只编辑（个人区域投资）

		if (investRegionInvestment != null) {
			if (investRegionInvestmentMapper.updateByPrimaryKeySelective(investRegionInvestment) < 1) {
				throw new ServiceException("个人区域投资异常");
			} else {

				// 1-1.根据区域id(这里的区域id指invest_region_total的id)查询（项目投资）表得到相当的项目id及名字,如果没有项目时没不添加（个人项目收益）及更新（个人区域投资）需要计算的部分
				investProjectInvestmentList = investProjectInvestmentMapper
						.selectProjectIdAndprojectName(investRegionInvestment.getRegionId());

			}
		}
		// 2.当前区域有项目时同时添加（个人项目收益）及更新（个人区域投资）需要计算的部分
		if (investProjectInvestmentList.size() > 0) {
			investRegionInvestmentList.add(investRegionInvestment);
			investProjectProfitService.addOrUpdate(investRegionInvestmentList);

		}

		return Response.response();
	}

	public Result add(InvestRegionInvestment investRegionInvestment, String followCapitalAccountStr,
			AccessToken accessToken) {

		// 1-1.根据区域id(这里的区域id指invest_region_total的id)查询（项目投资）表得到相当的项目id及名字,如果没有项目时没不添加（个人项目收益）及更新（个人区域投资）需要计算的部分
		List<InvestProjectInvestment> investProjectInvestmentList = investProjectInvestmentMapper
				.selectProjectIdAndprojectName(investRegionInvestment.getRegionId());
		List<InvestProjectAccount> investProjectAccountList = JSON.parseObject(followCapitalAccountStr,
				new TypeReference<ArrayList<InvestProjectAccount>>() {
				});

		// 编辑后如果更换bip并且bip已经存在的 情况对 数据进行处理
		Condition condition = null;
		if (investRegionInvestment.getId() != null) {
			investRegionInvestmentMapper.deleteByPrimaryKey(investRegionInvestment.getId());
			condition = new Condition(InvestProjectProfit.class);
			condition.createCriteria().andEqualTo("personInvestmentId", String.valueOf(investRegionInvestment.getId()));
			investProjectProfitMapper.deleteByCondition(condition);
		}

			List<InvestRegionInvestment> investRegionInvestmentList = new ArrayList<InvestRegionInvestment>();
			// 1.当前区域没有项目时只添加（个人区域投资）
				investRegionInvestment.setCreateBy(accessToken.getUserCode());
				investRegionInvestment.setCreateTime(new Date());	
			investRegionInvestment.setFlag(1);
			if (investRegionInvestment != null) {
				if (investRegionInvestmentMapper.insert(investRegionInvestment) < 1) {
					throw new ServiceException("添加添加个人区域投资异常");
				} else {

					// 2.当前区域有项目时同时添加（个人项目收益）及更新（个人区域投资）需要计算的部分
					if (investProjectInvestmentList != null && investProjectInvestmentList.size() > 0) {
						// 增加个人区域投资时也同时增加个人单独项目跟投数据，由于单投总投资改变，所以investRegionInvestment重新赋值

						investRegionInvestment = investProjectAccountService
								.addinvestProjectAccountList(investRegionInvestment, investProjectAccountList);
						investRegionInvestmentList.add(investRegionInvestment);
						investProjectProfitService.addOrUpdate(investRegionInvestmentList);

					}

				}
			}

		

		return Response.response();
	}

	/**
	 * 
	 * @param investRegionInvestment
	 */
	public void addOrEditValidation(InvestRegionInvestment investRegionInvestment) {
		Condition condition = new Condition(InvestRegionTotal.class);
		condition.selectProperties("regionAmountRaised", "singleAmountRaised");
		condition.createCriteria().andEqualTo("id", investRegionInvestment.getRegionId());
		List<InvestRegionTotal> investRegionTotal = investRegionTotalMapper.selectByCondition(condition);

		// if (investRegionTotal.get(0).getRegionAmountRaised().doubleValue() <
		// investRegionInvestment.getFollowCapital()
		// .doubleValue()) {
		// throw new ServiceException("跟投（资金池）不能大于区域总募集金额,操作失败，请更改后再提交");
		// } else if (investRegionTotal.get(0).getSingleAmountRaised().doubleValue() <
		// investRegionInvestment
		// .getFollowCapitalAccount().doubleValue()) {
		// throw new ServiceException("跟投（独资金账户）不能大于区域独资金总募资金额");
		// }

	}

	public Result del(Integer id) {
		int count = investRegionInvestmentMapper.deleteByPrimaryKey(id);
		if (count > 0) {
			Condition condition = null;
			// 删除当前个人的所有项目收益
			condition = new Condition(InvestProjectProfit.class);
			condition.createCriteria().andEqualTo("personInvestmentId", String.valueOf(id));
			investProjectProfitMapper.deleteByCondition(condition);
			// 删除当前个人的所有单独资金跟投
			condition = new Condition(InvestProjectAccount.class);
			condition.createCriteria().andEqualTo("investRegionInvestmentId", id);
			investProjectAccountMapper.deleteByCondition(condition);

		} else {
			throw new ServiceException("InvestRegionInvestmentService接口异常，删除失败");
		}
		return Response.response(count);
	}

	public Result findApp(String bipUserAccount) {
		InvestProjectAppVO vo=investRegionInvestmentMapper.findApp(bipUserAccount);
		return Response.response(vo);
	}

	public Result findRegionInvestmentInfo(InvestProjectInvestment investProjectInvestment) {
		List<InvestRegionInvestment> investRegionInvestment = investRegionInvestmentMapper.findRegionInvestmentInfo(
				investProjectInvestment.getRegionId(), investProjectInvestment.getProjectName());
		return Response.response(investRegionInvestment);
	}

	public Result findInvestmentAppInfo(Integer id) {
		if(id==null||id<1) {
			return null;
		}
		Map<String, Object> map = new HashMap<String, Object>();
		List<InvestProjectExcelVO> investProjectExcelVOList = investRegionInvestmentMapper.selectInvestAppInfo(null,
				null, id);
		InvestProjectProfitVo investProjectProfitVo = investProjectProfitMapper
				.findInvestProjectProfitVo(String.valueOf(id), null);
		if (investProjectProfitVo == null) {
			investProjectProfitVo = new InvestProjectProfitVo();
		}
		map.put("investProjectExcelVOList", investProjectExcelVOList);
		map.put("investProjectProfitVo", investProjectProfitVo);
		return Response.response(map);
	}
}