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

import cn.com.countrygarden.bi.main.model.twerp.ErpCommunity;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysOrgan;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.transaction.Transactional;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.model.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.countrygarden.bi.main.model.investment.InvestProjectInvestment;
import cn.com.countrygarden.bi.main.model.investment.InvestRegionInvestment;
import cn.com.countrygarden.bi.main.model.investment.InvestRegionTotal;
import cn.com.countrygarden.bi.main.dao.investment.InvestProjectInvestmentMapper;
import cn.com.countrygarden.bi.main.dao.investment.InvestRegionInvestmentMapper;
import cn.com.countrygarden.bi.main.dao.investment.InvestRegionTotalMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbHsprCommunityMapper;
import cn.com.countrygarden.bi.main.dto.ManagerMapOrganTreeDTO;
import cn.com.countrygarden.bi.main.dto.investment.InvestRegionExcelSummaryVo;
import cn.com.countrygarden.bi.main.dto.investment.InvestRegionTotalDTO;
import cn.com.countrygarden.bi.main.exception.ServiceException;
import cn.com.countrygarden.bi.main.service.investment.InvestProjectProfitService;
import cn.com.countrygarden.bi.main.service.investment.InvestRegionTotalService;
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-15
 */
@Service
@Transactional
public class InvestRegionTotalServiceImpl implements InvestRegionTotalService {

	@Autowired
	private TbSysOrganService tbSysOrganService;
	@Autowired
	private InvestRegionTotalMapper investRegionTotalMapper;

	@Autowired
	private TbHsprCommunityMapper tbHsprCommunityMapper;

	@Autowired
	private InvestProjectProfitService investProjectProfitService;

	@Autowired
	private InvestProjectInvestmentMapper investProjectInvestmentMapper;

	@Autowired
	private InvestRegionInvestmentMapper investRegionInvestmentMapper;

	// 区域投资管理下拉框的数据
	public Result getOrganTreeInvestmentNameAndRegionId() {
		List<InvestRegionTotal> investRegionTotalList = investRegionTotalMapper.selectAll();
		ManagerMapOrganTreeDTO dto = null;
		List<ManagerMapOrganTreeDTO> dtoList = new ArrayList<>();
		for (InvestRegionTotal investRegionTotal : investRegionTotalList) {
			dto = new ManagerMapOrganTreeDTO();
			dto.setCode(String.valueOf(investRegionTotal.getId()));
			dto.setName(investRegionTotal.getRegionName() + "--" + investRegionTotal.getInvestmentName());
			dto.setRegionId(investRegionTotal.getRegionId());

			dtoList.add(dto);
		}

		return Response.response(dtoList);
	}

	public Result findAllCommByUserCode(AccessToken accessToken) {

		TbSysOrgan tbSysOrgan = tbSysOrganService.findByUserCode(accessToken.getUserCode());
		if (tbSysOrgan == null) {
			tbSysOrgan = new TbSysOrgan();
		}
		List<ErpCommunity> dupOrgans = tbHsprCommunityMapper.findAllCommByUserCode1(tbSysOrgan.getOrganCode());

		return Response.response(dupOrgans);
	}

	public Result queryPageList(InvestRegionTotalDTO investRegionTotalDTO, AccessToken accessToken) {

		TbSysOrgan tbSysOrgan = tbSysOrganService.findByUserCode(accessToken.getUserCode());
		List<InvestRegionTotalDTO> newInvestRegionTotalDTOList = new ArrayList<InvestRegionTotalDTO>();
		if (tbSysOrgan == null) {
			return Response.response(newInvestRegionTotalDTOList);
		}

		String[] regionIds = null;
		if (investRegionTotalDTO.getRegionId() != null && investRegionTotalDTO.getRegionId() != "") {
			regionIds = investRegionTotalDTO.getRegionId().split(","); // 注意分隔符
		}

		List<InvestRegionTotalDTO> RegionTotalDTOList = investRegionTotalMapper.findAllRegionInvestment(regionIds,
				tbSysOrgan.getOrganCode());
		for (InvestRegionTotalDTO investRegionTotalDto : RegionTotalDTOList) {
			newInvestRegionTotalDTOList.add(isRegionFlag(investRegionTotalDto.getId()));
		}
		return Response.response(newInvestRegionTotalDTOList);
	}

	// 个人项目投资的项目下拉框数据
	public Result getProjectSelect(ManagerMapOrganTreeDTO managerMapOrganTreeDTO) {

		List<ManagerMapOrganTreeDTO> dto = investProjectInvestmentMapper
				.findProjectInvestmentRegionTreeDTO(managerMapOrganTreeDTO.getRegionId());
		for (ManagerMapOrganTreeDTO organTreeDTO : dto) {
			List<ManagerMapOrganTreeDTO> cdto = investProjectInvestmentMapper
					.findProjectInvestmentProjectTreeDTO(organTreeDTO.getRegionId());
			organTreeDTO.setChildren(cdto);
		}
		return Response.response(dto);
	}

	public InvestRegionTotalDTO isRegionFlag(Integer id) {
		InvestRegionTotalDTO investRegionTotalDTO = investRegionTotalMapper.selectInvestRegionTotalDTO(id);
		// 返回数据前需判断区域id能不能编辑，如果有项目存在的情况下不能编辑
		/**
		 * 1.项目有使用此区域的情况下，下拉框不能被编辑,或不能删除 2.个人区域投资有使用此区域的情况下，下拉框不能被编辑，或不能删除
		 * 3.setRegionFlag是区域下拉框是否可编辑，false，能编辑，能删除，true，不能编辑，不能删除
		 */
		// InvestRegionTotalDTO
		Condition condition = new Condition(InvestRegionInvestment.class);
		Criteria criteria = condition.createCriteria();
		criteria.andEqualTo("regionId", id);

		int count = investProjectInvestmentMapper.selectCountByCondition(condition)
				+ investRegionInvestmentMapper.selectCountByCondition(condition);
		// regionFlag
		if (count > 0) {
			investRegionTotalDTO.setRegionFlag(true);
		} else {
			investRegionTotalDTO.setRegionFlag(false);
		}

		InvestRegionExcelSummaryVo investRegionExcelSummaryVo = investRegionTotalMapper
				.findInvestRegionExcelSummaryVo(null, null, String.valueOf(id), null);
		if (investRegionExcelSummaryVo == null) {
			// 项目资金池（理财收益）合计
			investRegionTotalDTO.setFinancialIncomeCapitalSummary(new BigDecimal(0));
			// 项目单独资金账户（理财收益）合计
			investRegionTotalDTO.setFinancialIncomeCapitalAccountSummary(new BigDecimal(0));
			// 区域-资金池（募集资金余额）合计
			investRegionTotalDTO.setRegionaRaisingBalanceCapitalSummary(new BigDecimal(0));
			// 区域-单独资金账户（募集资金余额）合计
			investRegionTotalDTO.setRegionaRaisingBalanceCapitalAccountSummary(new BigDecimal(0));
			// 区域-资金池（可用资金余额）合计
			investRegionTotalDTO.setRegionaAailableBalanceCapitalSummary(new BigDecimal(0));
			// 区域-单独资金账户（可用资金余额）合计
			investRegionTotalDTO.setRegionaAvailableBalanceCapitalAccountSummary(new BigDecimal(0));
		} else {
			// 项目资金池（理财收益）合计
			investRegionExcelSummaryVo.setRegionAmountRaisedSummary(investRegionTotalDTO.getRegionAmountRaised());
			investRegionExcelSummaryVo.setSingleAmountRaisedSummary(investRegionTotalDTO.getSingleAmountRaised());
			// 项目单独资金账户（理财收益）合计
			investRegionTotalDTO
					.setFinancialIncomeCapitalSummary(investRegionExcelSummaryVo.getFinancialIncomeCapitalSummary());

			investRegionTotalDTO.setFinancialIncomeCapitalAccountSummary(
					investRegionExcelSummaryVo.getFinancialIncomeCapitalAccountSummary());
			// 区域-资金池（募集资金余额）合计
			investRegionTotalDTO.setRegionaRaisingBalanceCapitalSummary(
					investRegionExcelSummaryVo.getRegionaRaisingBalanceCapitalSummary());
			// 区域-单独资金账户（募集资金余额）合计
			investRegionTotalDTO.setRegionaRaisingBalanceCapitalAccountSummary(
					investRegionExcelSummaryVo.getRegionaRaisingBalanceCapitalAccountSummary());
			// 区域-资金池（可用资金余额）合计
			investRegionTotalDTO.setRegionaAailableBalanceCapitalSummary(
					investRegionExcelSummaryVo.getRegionaAailableBalanceCapitalSummary());
			// 区域-单独资金账户（可用资金余额）合计
			investRegionTotalDTO.setRegionaAvailableBalanceCapitalAccountSummary(
					investRegionExcelSummaryVo.getRegionaAvailableBalanceCapitalAccountSummary());
		}
		return investRegionTotalDTO;

	}

	public Result queryById(Integer id) {

		return Response.response(this.isRegionFlag(id));
	}

	@Override
	public Result add(InvestRegionTotal investRegionInvestment, AccessToken accessToken) {
	
		Condition condition = null;
		condition = new Condition(InvestRegionTotal.class);
		condition.createCriteria().andEqualTo("investmentName", investRegionInvestment.getInvestmentName())
				.andEqualTo("regionId", investRegionInvestment.getRegionId());
		if (investRegionTotalMapper.selectCountByCondition(condition) > 0) {
			return Response.response("no");
		} else {
			investRegionInvestment.setCreateBy(accessToken.getUserCode());
			investRegionInvestment.setCreateTime(new Date());
			investRegionInvestment.setFlag(1);
			investRegionTotalMapper.insert(investRegionInvestment);
			return Response.response("ok");
		}
	}

	@Override
	public Result edit(InvestRegionTotal investRegionInvestment, AccessToken accessToken) {

		Condition condition = null;
		condition = new Condition(InvestRegionTotal.class);
		condition.createCriteria().andNotEqualTo("id", investRegionInvestment.getId())
				.andEqualTo("regionId", investRegionInvestment.getRegionId())
				.andEqualTo("investmentName", investRegionInvestment.getInvestmentName());
		if (investRegionTotalMapper.selectCountByCondition(condition) > 0) {
			return Response.response("no");
		}
		if(accessToken!=null) {
			investRegionInvestment.setUpdateBy(accessToken.getUserCode());
		}	
		investRegionInvestment.setUpdateTime(new Date());

		if (investRegionTotalMapper.updateByPrimaryKeySelective(investRegionInvestment) > 0) {
			investProjectProfitService.regionTotalEditComputeRegionInvestment(investRegionInvestment.getId());

		} else {
			throw new ServiceException("InvestRegionTotalService接口异常");
		}
		return Response.response("ok");
	}

	@Override
	public Result del(Integer id) {

		return Response.response(investRegionTotalMapper.deleteByPrimaryKey(id));
	}

	// 已经添加的区域下拉框
	public Result getRegionList(AccessToken accessToken) {
		TbSysOrgan tbSysOrgan = tbSysOrganService.findByUserCode(accessToken.getUserCode());
		if (tbSysOrgan == null) {
			return Response.response();
		}
		return Response.response(investRegionTotalMapper.getRegionList(tbSysOrgan.getOrganCode()));
	}

	public InvestRegionTotal findRegionTotalOne(Integer id) {
		InvestRegionTotal investRegionTotal = null;
		Condition condition = new Condition(InvestRegionTotal.class);
		condition.createCriteria().andEqualTo("id", id);
		List<InvestRegionTotal> investRegionTotalList = investRegionTotalMapper.selectByCondition(condition);
		if (investRegionTotalList.size() == 1) {
			investRegionTotal = investRegionTotalList.get(0);
		}

		return investRegionTotal;
	}
}