package com.iamberry.wechat.service.drp;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.iamberry.wechat.core.entity.AdminUtils;
import com.iamberry.wechat.core.entity.PageBean;
import com.iamberry.wechat.core.entity.PaperBean;
import com.iamberry.wechat.core.entity.ResultMsg;
import com.iamberry.wechat.core.entity.drp.ApplyPlaceLogs;
import com.iamberry.wechat.core.entity.drp.PlaceInfo;
import com.iamberry.wechat.core.entity.relationship.DealerRelation;
import com.iamberry.wechat.face.drp.PlaceInfoService;
import com.iamberry.wechat.service.mapper.DealerRelationMapper;
import com.iamberry.wechat.service.mapper.PlaceInfoMapper;
import com.iamberry.wechat.service.mapper.PlaceWithDrawalsLogsMapper;
import com.iamberry.wechat.tools.NameUtils;
import com.iamberry.wechat.tools.ResponseJson;
import com.iamberry.wechat.tools.ResultInfo;

/**
 * 
 * @author 欧阳明
 * @Description: 代理者信息服务-业务处理
 * @Date:2016年4月19日
 *
 */
@Service("placeInfoServiceImpl")
public class PlaceInfoServiceImpl implements PlaceInfoService {

	@Autowired
	private PlaceInfoMapper placeInfoMapper;
	@Autowired
	PlaceWithDrawalsLogsMapper placeWithDrawalsLogsMapper;
	@Autowired
	private AdminUtils adminUtils;
	@Autowired
	private DealerRelationMapper dealerRelationMapper;
	
	//删除分销商
	public ResultMsg delete(PlaceInfo placeInfo) {
		placeInfo.setStatus(3);
		int i=placeInfoMapper.update(placeInfo);
		ResultMsg remsg=new ResultMsg();
		 if(i>0){
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setMessage(ResultInfo.SUCCESSINFO);
			}else{
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setMessage(ResultInfo.ERRORINFO);
			}
		 return remsg;
	}

	//增加分销商
	public ResultMsg addOne(PlaceInfo placeInfo) {
		ResultMsg remsg=new ResultMsg();
		placeInfo.setCreateDate(new Date());
		placeInfo.setStatus(1);
		/*if(placeInfo.getType()!=1){
			PlaceInfo placeinfo2=placeInfoMapper.getOnePlaceInfo(placeInfo.getPlacePid());
			placeInfo.setSupperId(placeinfo2.getSupperId());
		}*/
		// 产生安全的code
		String code = adminUtils.byte2hex(adminUtils.createRandomByte());
		try {
			code = NameUtils.PLACE_CODE_PREFIX + adminUtils.byte2hex(adminUtils.createRandomByte()).substring(0, 10);
		} catch (Exception e) {
			code = NameUtils.PLACE_CODE_PREFIX + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 10);
		}
		placeInfo.setInitCode(code);
		
		placeInfo.setName(placeInfo.getName().trim());
		placeInfo.setUserName(placeInfo.getUserName().trim());
		
		int isExist=placeInfoMapper.testNameExist(placeInfo);
		if(isExist==1 || isExist>1 ){
			remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setMessage(ResultInfo.repeatNameError);
			remsg.setStatus(false);
			return remsg;
		}
		
		System.out.println("=================templateId=============="+placeInfo.getTemplateId());
		
		int i= placeInfoMapper.insertObj(placeInfo);
		 if(i<0){
			    remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setMessage(ResultInfo.ERRORINFO);
				remsg.setStatus(false);
				return remsg;
			}
		
		 //插入分销商层次表
		DealerRelation dealerRelation=new DealerRelation();
		if(placeInfo.getPlacePid()==0){
			dealerRelation.setDealerFirst(placeInfo.getId());
			dealerRelation.setDealerCount(1);
		}else{
			PlaceInfo placeInfoParent=placeInfoMapper.getOnePlaceInfo(placeInfo.getPlacePid());
			dealerRelation=dealerRelationMapper.getDealerRelationById(placeInfoParent.getPlaceIds());
			
			switch(dealerRelation.getDealerCount().intValue()){
			case 1:
				dealerRelation.setDealerCount(2);
				dealerRelation.setDealerSecond(placeInfo.getId());
				break;
			case 2:
				dealerRelation.setDealerCount(3);
				dealerRelation.setDealerThird(placeInfo.getId());
				break;
			case 3:
				dealerRelation.setDealerCount(4);
				dealerRelation.setDealerFourth(placeInfo.getId());
				break;
			case 4:
				dealerRelation.setDealerCount(5);
				dealerRelation.setDealerFifth(placeInfo.getId());
				break;
			case 5:
				dealerRelation.setDealerCount(6);
				dealerRelation.setDealerSixth(placeInfo.getId());
				break;	
			}
		}
		//更新分销商的的placeIds
		i=dealerRelationMapper.insertDealerRelation(dealerRelation);
		if(i<0){
		    remsg.setResultCode(ResultInfo.ERRORCODE);
			remsg.setMessage(ResultInfo.ERRORINFO);
			remsg.setStatus(false);
			return remsg;
		}
		//给分销商表插入id
		placeInfo.setPlaceIds(dealerRelation.getDealerId());
		System.out.println("=================templateId=============="+placeInfo.getTemplateId());
		i=placeInfoMapper.update(placeInfo);
		 if(i>0){
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setMessage(ResultInfo.SUCCESSINFO);
				remsg.setData(placeInfo);
				remsg.setStatus(true);
			}else{
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setMessage(ResultInfo.ERRORINFO);
				remsg.setStatus(false);
			}
		 return remsg;
	}

	//批量插入分销商
	public ResultMsg batchInsert(ArrayList list) {
		int i=placeInfoMapper.batchInsert(list);
		ResultMsg remsg=new ResultMsg();
		 if(i>0){
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setMessage(ResultInfo.SUCCESSINFO);
			}else{
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setMessage(ResultInfo.ERRORINFO);
			}
		 return remsg;
	}

	//获取分销商详情
	public PlaceInfo getPlaceInfoById(int id) {
	  return placeInfoMapper.getOnePlaceInfo(id);
	}

	//分销商查询
	public Map SearchPlaceInfo(PlaceInfo placeInfo) {
		Map hm=new HashMap();
		List<PlaceInfo> lists=placeInfoMapper.selectAll(placeInfo);
		hm.put("data",lists);
		hm.put("totalNumber", placeInfoMapper.getAllCount(placeInfo));
		return hm;
	}

	//分销商其他分页查询(只有后台)
	public Map SearchPlaceInfoPage(PageBean page) {
		Map hm=new HashMap();
		PageBean pageIndex=new PageBean();
		PlaceInfo placeInfo=(PlaceInfo)page.getCondition();
		
		pageIndex.setPageNumber(page.getPageNumber());
		pageIndex.setPageSize(page.getPageSize());
		
		if(page.getPageCount()>0){
			pageIndex.setCount(page.getPageCount());
		}else{
			pageIndex.setCount(placeInfoMapper.getAllCount(placeInfo));
		}
		
		pageIndex.initRecordBegin();
		placeInfo.setPage(pageIndex);
		List<PlaceInfo> lists=placeInfoMapper.selectAll(placeInfo);
        hm.put("data",lists);
		hm.put("page",pageIndex);
		return hm;
	}

	//更新对象
	public ResultMsg update(PlaceInfo placeInfo) {
		 HashMap<String,Integer> conditionMap=new HashMap<String,Integer>();
         int i=0;
         ResultMsg remsg=new ResultMsg();
         //获取更改前的对象
		 PlaceInfo orgin=placeInfoMapper.getOnePlaceInfo(placeInfo.getId());
		 i=placeInfoMapper.update(placeInfo);
		 if(i<0){
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setMessage(ResultInfo.ERRORINFO);
				remsg.setStatus(false);
				return remsg;
			}
		 PlaceInfo parent=placeInfoMapper.getOnePlaceInfo(placeInfo.getPlacePid());
		 if(parent==null){
			 remsg.setStatus(true);
			 remsg.setResultCode(ResultInfo.SUCCESSCODE);
			 remsg.setMessage(ResultInfo.SUCCESSINFO);
			 return remsg;
		 }

		 //if(placeInfo.getPlacePid()!=orgin.getPlacePid()){
		 if(1==1){
			DealerRelation dealerRelation=dealerRelationMapper.getDealerRelationById(parent.getPlaceIds());
			
			switch(dealerRelation.getDealerCount().intValue()){
			case 1:
				dealerRelation.setDealerSecond(placeInfo.getId());
				dealerRelation.setDealerCount(2);
				dealerRelation.setDealerId(orgin.getPlaceIds());
				i=dealerRelationMapper.updateRelation(dealerRelation);
				break;
			case 2:
				dealerRelation.setDealerThird(placeInfo.getId());
				dealerRelation.setDealerCount(3);
				dealerRelation.setDealerId(orgin.getPlaceIds());
				i=dealerRelationMapper.updateRelation(dealerRelation);
				break;
			case 3:
				dealerRelation.setDealerFourth(placeInfo.getId());
				dealerRelation.setDealerCount(4);
				dealerRelation.setDealerId(orgin.getPlaceIds());
				i=dealerRelationMapper.updateRelation(dealerRelation);
				break;
			case 4:
				dealerRelation.setDealerFifth(placeInfo.getId());
				dealerRelation.setDealerCount(5);
				dealerRelation.setDealerId(orgin.getPlaceIds());
				i=dealerRelationMapper.updateRelation(dealerRelation);
				break;	
			case 5:
				dealerRelation.setDealerSixth(placeInfo.getId());
				dealerRelation.setDealerCount(6);
				dealerRelation.setDealerId(orgin.getPlaceIds());
				i=dealerRelationMapper.updateRelation(dealerRelation);
				break;	
			}
			
		}
		 
		 if(orgin.getId()==orgin.getPlacePid() || orgin.getPlacePid()==0){
			 DealerRelation dealerRelation=new DealerRelation();
			 dealerRelation.setDealerId(orgin.getPlaceIds());
			 dealerRelation.setDealerFirst(orgin.getId());
			 dealerRelation.setDealerSecond(null);
			 dealerRelation.setDealerThird(null);
			 i=dealerRelationMapper.updateRelation(dealerRelation);
		 }

		 if(i>0){
				remsg.setResultCode(ResultInfo.SUCCESSCODE);
				remsg.setMessage(ResultInfo.SUCCESSINFO);
			}else{
				remsg.setResultCode(ResultInfo.ERRORCODE);
				remsg.setMessage(ResultInfo.ERRORINFO);
			}
		 return remsg;
	}

	//通过openid获取分销商信息
	public PlaceInfo getPlaceInfoByOpenId(String openid) {
		return placeInfoMapper.getOnePlaceInfo2(openid);
		
	}
	//查询分销商信息用于提供excel下载
	public List<PlaceInfo> selectPlaceInfosForDownLoad(Map map){
		return placeInfoMapper.getPlaceInfosForDownLoad(map);
	}
	
	//插入单条数据并返回对象
	public PlaceInfo insertOne(PlaceInfo placeInfo){
		 placeInfoMapper.insertObj(placeInfo);
		 return placeInfo;
		 
	}
	//获取单个用户提现总额
	@Override
	public int getTotalMoneyByPlaceId(int placeId) {
		// TODO Auto-generated method stub
		return placeWithDrawalsLogsMapper.getTotalMoneyByPlaceId(placeId);
	}

	@Override
	public Integer selectPlaceIdByOpenId(String openId) {
		// TODO Auto-generated method stub
		return placeInfoMapper.selectPlaceIdByOpenId(openId);
	}

	@Override
	public PlaceInfo getOnePlaceInfoByInitcode(PlaceInfo placeInfo) {
		// TODO Auto-generated method stub
		return placeInfoMapper.getOnePlaceInfoByInitcode(placeInfo);
	}
	
	//批量更新分銷商信息
	public int batchUpdate(List<PlaceInfo> placeInfos){
		return placeInfoMapper.batchUpdate(placeInfos);
	}

	@Override
	public List<PlaceInfo> getPlaceId(PlaceInfo placeInfo) {
		// TODO Auto-generated method stub
		return placeInfoMapper.getPlaceId(placeInfo);
	}

	@Override
	public List<ApplyPlaceLogs> selectApplyPlaceLogs(int pageNO, int pageSize) {
		// TODO Auto-generated method stub
		PaperBean bean = new PaperBean();
		bean.setPaperData(pageNO, pageSize);
		return placeInfoMapper.selectApplyPlaceLogs(bean);
	}

	@Override
	public int getCount(int pageSize) {
		int count = placeInfoMapper.getCount();
		return PaperBean.justPaperCount(count, pageSize);
	}

	@Override
	public int updateApplyStatus(ApplyPlaceLogs logs) {
		// TODO Auto-generated method stub
		return placeInfoMapper.updateApplyStatus(logs);
	}

	@Override
	public ApplyPlaceLogs selectApplyLogsByPlaceID(Integer placeID) {
		// TODO Auto-generated method stub
		return placeInfoMapper.selectApplyLogsByPlaceID(placeID);
	}

	@Override
	public boolean handlerApplyLogs(Integer applyID, Integer status) {
		// TODO Auto-generated method stub
		
		ApplyPlaceLogs logs = new ApplyPlaceLogs();
		logs.setApplyID(applyID);
		logs.setApplyStatus(status);
		
		if (status == 2) {
			// 通过
			logs = placeInfoMapper.selectApplyLogsByID(applyID);
			if (logs == null || logs.getApplyID() == null) {
				return false;
			}
			
			// 更新商户信息
			PlaceInfo info = new PlaceInfo();
			info.setId(logs.getApplyToPlaceID());
			info.setAreaName(logs.getApplyArea());
			info.setName(logs.getApplyName());
			info.setTel(logs.getApplyTel());
			info.setUserName(logs.getApplyUserName());
			info.setAddr(logs.getApplyAddr());
			
			placeInfoMapper.updatePlaceInfo(info);
			
			// 更新当前数据状态
			logs.setApplyStatus(status);
			return placeInfoMapper.updateApplyStatus(logs) >= 1 ? true : false;
		} else if (status == 3) {
			// 驳回
			return placeInfoMapper.updateApplyStatus(logs) >= 1 ? true : false;
		}
		return false;
	}

	@Override
	public ResponseJson handlerPlaceInfo(String openID) {
		// TODO Auto-generated method stub
		ResponseJson json = new ResponseJson();
		
		// 判断用户是否拥有权限管理对应的代理商
		Integer placeID = placeInfoMapper.selectPlaceIdByOpenId(openID);
		if (placeID == null) {
			json.setReturnCode(404);
			json.addResponseKeyValue("代理商信息没有找到!");
			return json;
		}
		
		// 判断代理商是否完善啦信息	完善后就不能修改？
//		int status = placeInfoMapper.selectPlaceInfoStatusByPlaceId(placeID);
//		if (status == 2) {
//			json.setReturnCode(200);
//			json.addResponseKeyValue("SUCCESS");
//			return json;
//		}
		
		// 用户需要完善信息
		ApplyPlaceLogs logs = placeInfoMapper.selectApplyLogsByPlaceID(placeID);
		if (logs == null) {
			json.setReturnCode(500);
			json.addResponseKeyValue("要求重填!");
			return json;
		}
		
		if (logs.getApplyStatus() == 1) {
			// 用户已经填过信息，而且是审核中，不要求填写
			json.setReturnCode(200);
			json.addResponseKeyValue("SUCCESS");
			return json;
		} else if (logs.getApplyStatus() == 3) {
			// 填写不正确，后台驳回，要求重填
			json.setReturnCode(302);
			json.addResponseKeyValue("applyInfo", logs);
			return json;
		}
		
		// 凡是到此，业务出现异常，需要重填
		json.setReturnCode(500);
		json.addResponseKeyValue("要求重填!");
		return json;
	}

	@Override
	public ResponseJson addApplyPlaceLogs(ApplyPlaceLogs applyPlaceLogs) {
		// TODO Auto-generated method stub
		// 判断用户是否拥有权限管理对应的代理商
		ResponseJson json = new ResponseJson();
		Integer placeID = placeInfoMapper.selectPlaceIdByOpenId(applyPlaceLogs.getApplyOpenID());
		if (placeID == null) {
			json.setReturnCode(404);
			json.addResponseKeyValue("代理商信息没有找到!");
			return json;
		}
		
		// 判断是否已经拥有在申请的数据
		ApplyPlaceLogs logsOld = placeInfoMapper.selectApplyLogsByPlaceID(placeID);
		if (logsOld != null && logsOld.getApplyStatus() == 1) {
			// 用户已经填过信息，而且是审核中，不要求填写
			json.setReturnCode(405);
			json.addResponseKeyValue("审核中!请稍后");
			return json;
		}
		
		// 充填
		applyPlaceLogs.setApplyToPlaceID(placeID);
		
		// 保存信息
		placeInfoMapper.insertApplyLogs(applyPlaceLogs);
		
		json.setReturnCode(200);
		json.addResponseKeyValue("SUCCESS");
		
		return json;
	}

	@Override
	public ResponseJson selectPlaceInfoDetailByOpenId(String openid) {
		// TODO Auto-generated method stub
		ResponseJson json = new ResponseJson();
		PlaceInfo place = placeInfoMapper.selectPlaceInfoDetailByOpenId(openid); 
		if(place == null || place.getId() == 0){
			json.setReturnCode(400);
			json.addResponseKeyValue("没有商户信息!");
			return json;
		}
		json.addResponseKeyValue("placeInfo", place);
		
		// 判断是否已经拥有在申请的数据
		ApplyPlaceLogs logsOld = placeInfoMapper.selectApplyLogsByPlaceID(place.getId());
		if(logsOld == null ){	//用户没有申请过
			json.setReturnCode(2001);
			json.addResponseKeyValue("FAILED");
			return json;
		}
		if (logsOld.getApplyStatus().intValue() == 1) {	// 用户已经填过信息，而且是审核中
			json.setReturnCode(2002);
			json.addResponseKeyValue("FAILED");
			return json;
		}else if(logsOld.getApplyStatus().intValue() == 3){		// 用户已经填过信息，而且是审核--未通过
			json.setReturnCode(2003);
			json.addResponseKeyValue("FAILED");
			return json;
		}else if(logsOld.getApplyStatus().intValue() == 2){		// 用户已经填过信息，而且是审核--通过
			json.setReturnCode(2005);
			json.addResponseKeyValue("FAILED");
			return json;
		}else {
			json.setReturnCode(200); 
			return json;
		}
	}

	@Override
	public ApplyPlaceLogs selectApplyLogsByOpenID(String openID) {
		// TODO Auto-generated method stub
		return placeInfoMapper.selectApplyLogsByOpenID(openID);
	}
}
