package com.dst.slms.plan.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dst.slms.common.excetion.BizException;
import com.dst.slms.common.service.util.DataGrid;
import com.dst.slms.common.service.util.EntityQuery;
import com.dst.slms.common.support.BillBaseCrudServiceImpl;
import com.dst.slms.common.utils.ModelInvokeHelper;
import com.dst.slms.common.utils.R;
import com.dst.slms.common.utils.UIRuleUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.dst.slms.plan.entity.ExpectedUnpaidInfo;
import com.dst.slms.plan.entity.MonthlyPaymentPlanInfo;
import com.dst.slms.plan.entity.SignedInfo;
import com.dst.slms.plan.service.IMonthlyPaymentPlanService;

/**   
 * @Title: 月度支付计划 ServiceImpl
 * @Description: 月度支付计划
 * @author 
 * @date 2020-05-02 16:24:33
 * @version V1.0   
 */
@SuppressWarnings("unchecked")
@Service
@Transactional
public class IMonthlyPaymentPlanServiceImpl extends BillBaseCrudServiceImpl<MonthlyPaymentPlanInfo> implements IMonthlyPaymentPlanService{

	/**
	 * Logger for this class
	 */
	private static final Logger logger = LoggerFactory.getLogger(IMonthlyPaymentPlanServiceImpl.class);
	
	@Autowired
	private IMonthlyPaymentPlanService iMonthlyPaymentPlanService;
	
	@Override
	protected R verifyInput(MonthlyPaymentPlanInfo entity) {
		if(entity.getMonthlyPaymentPlanE()==null||entity.getMonthlyPaymentPlanE().size()==0){
			throw new BizException("规划余额不能为空！");
		}
		EntityQuery eq = new EntityQuery(MonthlyPaymentPlanInfo.class);
		eq.eq("year",entity.getYear());
		eq.eq("month",entity.getMonth());
		eq.eq("marketProject.id",entity.getMarketProject().getId());
		eq.notEq("number",entity.getNumber());
		if(UIRuleUtil.isNotNull(entity.getId())){
			eq.notEq("id",entity.getId());
		}
		eq.add();
		if(iMonthlyPaymentPlanService.entityExits(eq)){
			throw new BizException("该项目同一年月已有月度支付计划，请进行修订操作！");
		}
		return super.verifyInput(entity);
	}

	/**
	 * 已付款数据获取
	 */
	@Override
	public Object getSignedByid(HttpServletResponse response, HttpServletRequest request, DataGrid dataGrid) {
		String parentid = request.getParameter("parentid");
		String newparentid = request.getParameter("newparentid");
		if(UIRuleUtil.isNotNull(newparentid)&&newparentid.equals("-1")){
			parentid = null;
 		}
		String year = request.getParameter("year");
		String month = request.getParameter("month");
		String marketProjectId = request.getParameter("marketProjectId");
		if(UIRuleUtil.isNotNull(parentid)){
			EntityQuery eq = new EntityQuery(SignedInfo.class);
			eq.eq("parent.id",parentid);
			eq.add();
			String field[] = new String[]{"id","saleContract.id","saleContract.name","saleContract.number","saleContractName","supplierProfile.id","supplierProfile.name","supplierProfile.number","marketAccount.id","marketAccount.name","marketAccount.number","contractAmount","amountPaid","unpaidAmount","monthOne","monthTwo","monthThree"};
			List<SignedInfo> infolist= iMonthlyPaymentPlanService.getEntityList(eq,field );
			JSONArray caseEntityDataToJson = new JSONArray();
			if(infolist!=null&&infolist.size()>0){
				for (SignedInfo info : infolist) {
					JSONObject jsonboj = new JSONObject();
					if(info.getSaleContract()!=null){
						JSONObject saleContractobj = new JSONObject();
						saleContractobj.put("number", info.getSaleContract().getNumber());
						saleContractobj.put("name",info.getSaleContract().getName());
						saleContractobj.put("id", info.getSaleContract().getId());
						jsonboj.put("saleContract",saleContractobj);
						jsonboj.put("saleContractName", info.getSaleContract().getName());
					}
					if(info.getSupplierProfile()!=null){
						JSONObject supplieobj = new JSONObject();
						supplieobj.put("number", info.getSupplierProfile().getNumber());
						supplieobj.put("name",info.getSupplierProfile().getName());
						supplieobj.put("id", info.getSupplierProfile().getId());
						jsonboj.put("supplierProfile",supplieobj);
					}
					if(info.getMarketAccount()!=null){
						JSONObject marketobj = new JSONObject();
						marketobj.put("number", info.getMarketAccount().getNumber());
						marketobj.put("name", info.getMarketAccount().getName());
						marketobj.put("id", info.getMarketAccount().getId());
						jsonboj.put("marketAccount",marketobj);
					}
					jsonboj.put("contractAmount", info.getContractAmount());
					jsonboj.put("amountPaid",info.getAmountPaid());
					jsonboj.put("unpaidAmount",info.getUnpaidAmount());
					jsonboj.put("monthOne",info.getMonthOne());
					jsonboj.put("monthTwo",info.getMonthTwo());
					jsonboj.put("monthThree",info.getMonthThree());
					caseEntityDataToJson.add(jsonboj);
				}
			}
			return caseEntityDataToJson;
		}else{
			if(UIRuleUtil.isNotNull(year)&&UIRuleUtil.isNotNull(month)&&UIRuleUtil.isNotNull(marketProjectId)){
				JSONArray caseEntityDataToJson = getSignedDate(year,month,marketProjectId);
				return caseEntityDataToJson;
			}
		}
		return null;
	}
	/**
	 * 逾期未支付数据获取
	 */
	public Object getExpectedUnpaidByid(HttpServletResponse response, HttpServletRequest request, DataGrid dataGrid) {
		String parentid = request.getParameter("parentid");
		String newparentid = request.getParameter("newparentid");
		if(UIRuleUtil.isNotNull(newparentid)&&newparentid.equals("-1")){
			parentid = null;
 		}
		String year = request.getParameter("year");
		String month = request.getParameter("month");
		String marketProjectId = request.getParameter("marketProjectId");
		if(UIRuleUtil.isNotNull(parentid)){
			EntityQuery eq = new EntityQuery(ExpectedUnpaidInfo.class);
			eq.eq("parent.id",parentid);
			eq.add();
			String field[] = new String[]{"id","saleContract.id","saleContract.name","saleContract.number","saleContractName","supplierProfile.id","supplierProfile.name","supplierProfile.number","marketAccount.id","marketAccount.name","marketAccount.number","contractAmount","amountPaid","unpaidAmount","overdue"};
			List<ExpectedUnpaidInfo> infolist= iMonthlyPaymentPlanService.getEntityList(eq,field);
			JSONArray caseEntityDataToJson = new JSONArray();
			if(infolist!=null&&infolist.size()>0){
				for (ExpectedUnpaidInfo info : infolist) {
					JSONObject jsonboj = new JSONObject();
					if(info.getSaleContract()!=null){
						JSONObject saleContractobj = new JSONObject();
						saleContractobj.put("number", info.getSaleContract().getNumber());
						saleContractobj.put("name",info.getSaleContract().getName());
						saleContractobj.put("id", info.getSaleContract().getId());
						jsonboj.put("saleContract",saleContractobj);
						jsonboj.put("saleContractName", info.getSaleContract().getName());
					}
					if(info.getSupplierProfile()!=null){
						JSONObject supplieobj = new JSONObject();
						supplieobj.put("number", info.getSupplierProfile().getNumber());
						supplieobj.put("name",info.getSupplierProfile().getName());
						supplieobj.put("id", info.getSupplierProfile().getId());
						jsonboj.put("supplierProfile",supplieobj);
					}
					if(info.getMarketAccount()!=null){
						JSONObject marketobj = new JSONObject();
						marketobj.put("number", info.getMarketAccount().getNumber());
						marketobj.put("name", info.getMarketAccount().getName());
						marketobj.put("id", info.getMarketAccount().getId());
						jsonboj.put("marketAccount",marketobj);
					}
					jsonboj.put("contractAmount", info.getContractAmount());
					jsonboj.put("amountPaid",info.getAmountPaid());
					jsonboj.put("unpaidAmount",info.getUnpaidAmount());
					jsonboj.put("overdue",info.getOverdue());
					caseEntityDataToJson.add(jsonboj);
				}
			}
		}else{
			if(UIRuleUtil.isNotNull(year)&&UIRuleUtil.isNotNull(month)&&UIRuleUtil.isNotNull(marketProjectId)){
				JSONArray caseEntityDataToJson = getexpectedUnpaDate(year,month,marketProjectId);
				return caseEntityDataToJson;
			}
		}
		return null;
	}
	
	public JSONArray getexpectedUnpaDate(String year, String month, String marketProjectId) {
		if(Integer.valueOf(month)<10){
			month="0"+month;
		}
		StringBuilder sql = new StringBuilder(" select l8.*,(l8.payAmt-l7.taxReqAmt) overdue from ((select ifnull(sum(FtaxReqAmt),0) taxReqAmt,FcontractID from yc_cost_paymentReq where FSTATE='AUDIT'  ");
	//	sql.append("  and FprojectID='"+marketProjectId+"' ");
		sql.append("  and date_format(FAUDITTIME,'%Y%m') <'"+year+month+"' group by FcontractID) l7 ");
		sql.append(" inner join ");
		sql.append("  (select l2.FNUMBER,l2.FNAME,l2.fid,l3.fid supplierid,l3.FNAME suppliername,l3.FNUMBER suppliernumber,l4.fid marketid,  ");
		sql.append(" l4.FNAME marketname,l4.FNUMBER marketnumber,l2.FtaxConAmt,ifnull(sum(l1.FpayAmt),0) payAmt from  yc_cost_saleConEconomics  l1 ");
		sql.append(" left join yc_cost_saleContract l2 on l1.FparentId=l2.fid  ");
		sql.append(" left join yc_cost_supplierProfile l3 on l2.FsupplierID=l3.fid ");
		sql.append(" left join yc_cost_marketAccount l4 on l2.FmarkAccountID=l4.fid ");
		sql.append(" where  date_format(l1.FbizDate,'%Y%m') <'"+year+month+"' ");
		sql.append(" and  l2.FprojectID='"+marketProjectId+"' ");
		sql.append(" group by l2.FNUMBER,l2.FNAME,l2.fid,l3.fid ,l3.FNAME ,l3.FNUMBER ,l4.fid, ");
		sql.append(" l4.FNAME ,l4.FNUMBER ,l2.FtaxConAmt) l8 ");
		sql.append(" on l7.FcontractID = l8.fid and ");
		sql.append(" l7.taxReqAmt<l8.payAmt ) ");
		List<Map<String,Object>> list = iMonthlyPaymentPlanService.executeSqlQuery(sql.toString());
		JSONArray caseEntityDataToJson = new JSONArray();
		if(list!=null&&list.size()>0){
			for (Map<String, Object> map : list) {
				JSONObject jsonboj = new JSONObject();
				JSONObject saleContractobj = new JSONObject();
				saleContractobj.put("number", map.get("FNUMBER"));
				saleContractobj.put("name", map.get("FNAME"));
				saleContractobj.put("id", map.get("fid"));
				jsonboj.put("saleContract",saleContractobj);
				jsonboj.put("saleContractName", map.get("FNAME"));
				JSONObject supplieobj = new JSONObject();
				supplieobj.put("number", map.get("suppliernumber"));
				supplieobj.put("name", map.get("suppliername"));
				supplieobj.put("id", map.get("supplierid"));
				jsonboj.put("supplierProfile",supplieobj);
				JSONObject marketobj = new JSONObject();
				marketobj.put("number", map.get("marketnumber"));
				marketobj.put("name", map.get("marketname"));
				marketobj.put("id", map.get("marketid"));
				jsonboj.put("marketAccount",marketobj);
				jsonboj.put("contractAmount", map.get("FtaxConAmt"));
				//已用金额
				List<Map<String,Object>> useamtlist = iMonthlyPaymentPlanService.executeSqlQuery(" select ifnull(sum(FtaxReqAmt),0) taxReqAmt from yc_cost_paymentReq where FSTATE='AUDIT' and FcontractID='"+ map.get("fid")+"' ");
				BigDecimal taxReqAmt = new BigDecimal("0");
				if(useamtlist!=null&&useamtlist.size()>0){
					taxReqAmt = new BigDecimal(useamtlist.get(0).get("taxReqAmt")+"");
				}
				jsonboj.put("amountPaid",taxReqAmt);
				jsonboj.put("unpaidAmount",new BigDecimal( map.get("FtaxConAmt")+"").add(new BigDecimal("-"+taxReqAmt)));
				jsonboj.put("overdue",map.get("overdue")+"");
				caseEntityDataToJson.add(jsonboj);
			}
		}
		return caseEntityDataToJson;
	}

	/**
	 * 
	 * @param year
	 * @param month
	 * @param marketProjectId
	 * @return
	 */
	public JSONArray  getSignedDate(String year, String month, String marketProjectId) {
		String twomonth = (Integer.valueOf(month)+2)+"";
		String twoyear = year;
		if(Integer.valueOf(month)<10){
			month="0"+month;
		}
		if(Integer.valueOf(twomonth)<10){
			twomonth="0"+twomonth;
		}
		if(Integer.valueOf(twomonth)>12){
			twoyear = (Integer.valueOf(twoyear)+1)+"";
			if(Integer.valueOf(twomonth)==13){
				twomonth = "01";
			}
			if(Integer.valueOf(twomonth)==14){
				twomonth = "02";
			}
		}
		StringBuilder sql = new StringBuilder(" select distinct l2.FNUMBER,l2.FNAME,l2.fid,l3.fid supplierid,l3.FNAME suppliername,l3.FNUMBER suppliernumber,l4.fid marketid, ");
		sql.append(" l4.FNAME marketname,l4.FNUMBER marketnumber,l2.FtaxConAmt from  yc_cost_saleConEconomics  l1  ");
		sql.append(" left join yc_cost_saleContract l2 on l1.FparentId=l2.fid   ");
		sql.append(" left join yc_cost_supplierProfile l3 on l2.FsupplierID=l3.fid  ");
		sql.append(" left join yc_cost_marketAccount l4 on l2.FmarkAccountID=l4.fid   ");
		sql.append(" where  date_format(l1.FbizDate,'%Y%m') between '"+year+month+"' and '"+twoyear+twomonth+"' ");
		sql.append(" and  l2.FprojectID='"+marketProjectId+"' ");
		List<Map<String,Object>> list = iMonthlyPaymentPlanService.executeSqlQuery(sql.toString());
		JSONArray caseEntityDataToJson = new JSONArray();
		if(list!=null&&list.size()>0){
			for (Map<String, Object> map : list) {
				JSONObject jsonboj = new JSONObject();
				JSONObject saleContractobj = new JSONObject();
				saleContractobj.put("number", map.get("FNUMBER"));
				saleContractobj.put("name", map.get("FNAME"));
				saleContractobj.put("id", map.get("fid"));
				jsonboj.put("saleContract",saleContractobj);
				jsonboj.put("saleContractName", map.get("FNAME"));
				JSONObject supplieobj = new JSONObject();
				supplieobj.put("number", map.get("suppliernumber"));
				supplieobj.put("name", map.get("suppliername"));
				supplieobj.put("id", map.get("supplierid"));
				jsonboj.put("supplierProfile",supplieobj);
				JSONObject marketobj = new JSONObject();
				marketobj.put("number", map.get("marketnumber"));
				marketobj.put("name", map.get("marketname"));
				marketobj.put("id", map.get("marketid"));
				jsonboj.put("marketAccount",marketobj);
				jsonboj.put("contractAmount", map.get("FtaxConAmt"));
				//已用金额
				List<Map<String,Object>> useamtlist = iMonthlyPaymentPlanService.executeSqlQuery(" select ifnull(sum(FtaxReqAmt),0) taxReqAmt from yc_cost_paymentReq where FSTATE='AUDIT' and FcontractID='"+ map.get("fid")+"' ");
				BigDecimal taxReqAmt = new BigDecimal("0");
				if(useamtlist!=null&&useamtlist.size()>0){
					taxReqAmt = new BigDecimal(useamtlist.get(0).get("taxReqAmt")+"");
				}
				jsonboj.put("amountPaid",taxReqAmt);
				jsonboj.put("unpaidAmount",new BigDecimal( map.get("FtaxConAmt")+"").add(new BigDecimal("-"+taxReqAmt)));
				//近3个月
				sql = new StringBuilder(" select date_format(FbizDate,'%Y%m') bizDate,ifnull(sum(FpayAmt),0) payAmt from yc_cost_saleConEconomics  ");
				sql.append(" where date_format(FbizDate,'%Y%m') between '"+year+month+"' and '"+twoyear+twomonth+"'  ");
				sql.append(" and  FparentId='"+map.get("fid")+"' ");
				sql.append(" GROUP BY date_format(FbizDate,'%Y%m') ORDER BY date_format(FbizDate,'%Y%m')    ");
				List<Map<String,Object>> monthlist = iMonthlyPaymentPlanService.executeSqlQuery(sql.toString());
				if(monthlist!=null&&monthlist.size()>0){
					for (Map<String, Object> map2 : monthlist) {
						String bizDate =map2.get("bizDate")+"";
						String payAmt = map2.get("payAmt")+"";
						if(bizDate.equals(year+month)){
							jsonboj.put("monthOne",payAmt);
						}else if(bizDate.equals(twoyear+twomonth)){
							jsonboj.put("monthThree",payAmt);
						}else{
							jsonboj.put("monthTwo",payAmt);
						}
					}
				}
				caseEntityDataToJson.add(jsonboj);
			}
		}
		return caseEntityDataToJson;
	}

}