package com.palmnest.service.estateserve.impl;

import com.palmnest.application.ElementConstant;
import com.palmnest.application.bean.Page;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.dao.estateserve.AppUserDao;
import com.palmnest.dao.estateserve.ContractIinformationOrderDao;
import com.palmnest.dao.property.PropertyDao;
import com.palmnest.model.ContractIinformation;
import com.palmnest.model.ContractIinformationOrder;
import com.palmnest.model.estateserve.AppUser;
import com.palmnest.model.property.TbOrganization;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.estateserve.ContractIinformationOrderManager;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.ws.UserinformationSync;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;


@Slf4j
@Service("contractIinformationOrderManager")
public class ContractIinformationOrderManagerImpl extends
		GenericManagerImpl<ContractIinformationOrder, Integer> implements ContractIinformationOrderManager {


	private ContractIinformationOrderDao contractIinformationOrderDao;

	@Autowired
	private PropertyDao propertyDao;
	@Autowired
	private AppUserDao  appuserDao;

	@Autowired
	public void setContractIinformationOrderDao(
			ContractIinformationOrderDao contractIinformationOrderDao) {
		this.dao = contractIinformationOrderDao;
		this.contractIinformationOrderDao = contractIinformationOrderDao;
	}

	@Override
	public Page ContractIinformationOrderPage(Integer pageSize, Integer pageNo,
											  String orgId, String virtualArchitectureId) throws Exception {
		return contractIinformationOrderDao.ContractIinformationOrderPage(pageSize, pageNo, orgId, virtualArchitectureId);
	}

	@Override
	public String saveUpdateContart(String userId, String organizationId, String virtualArchitectureId, String controlUser)
			throws Exception {
		try {
			//1.更新用户的订购记录信息
			List<ContractIinformationOrder> list = contractIinformationOrderDao.getBusinessRecordBuyUser(Integer.parseInt(userId));
			if (!CollectionUtils.isEmpty(list)) {
				ContractIinformationOrder contractIinformationOrder = null;
				for (int i = 0; i < list.size(); i++) {
					list.get(i).setModifier(controlUser);
					list.get(i).setModifyTime(new Date());
					list.get(i).setOrganizationId(Integer.parseInt(organizationId));
					list.get(i).setVirtualArchitectureId(Integer.parseInt(virtualArchitectureId));
					contractIinformationOrderDao.updateObj(list.get(i));
					if (i == list.size() - 1) {
						contractIinformationOrder = list.get(i);
					}
				}
				boolean result = assignSyncUser("2", ElementConstant.OPRATETYPE_UPD, null, contractIinformationOrder);
				if (result) {
					//2.更新用户的资料信息
					AppUser appUser = appuserDao.get(Integer.parseInt(userId));
					appUser.setOrganizationId(Integer.parseInt(organizationId));
					appUser.setVirtualArchId(Integer.parseInt(virtualArchitectureId));
					appUser.setStatus("1");
					appUser.setModifyTime(new Date());
					appUser.setModifier(controlUser);
					appuserDao.updateObj(appUser);
					return "sucess";
				}
			}
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}
		return "error";
	}

	@Override
	public Page ContractIinformationPage(Integer pageSize, Integer pageNo,
										 String orgId, String virtualArchitectureId) throws Exception {
		try {
			return contractIinformationOrderDao.ContractIinformationPage(pageSize, pageNo, orgId, virtualArchitectureId);
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public Map<String, Object> saveUpdateBusinessRecord(
			ContractIinformation contractIinformation) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if (contractIinformation.getId() != null) {
				ContractIinformation contractIinformation2 = contractIinformationOrderDao.findContractIinformationObj(contractIinformation.getId());
				contractIinformation2.setType(contractIinformation.getType());
				contractIinformation2.setModifier(contractIinformation.getModifier());
				contractIinformation2.setModifyTime(contractIinformation.getModifyTime());
				propertyDao.updateObj(contractIinformation2);
				result.put("flag", true);
				result.put("desc", "签约记录更新成功！");
			} else {
				VirtualArchitecture virtual = propertyDao.getVirtualArchitectureById(contractIinformation.getVirtualArchitectureId());
				virtual.setContractStatus("1"); //签约状态
				propertyDao.updateObj(virtual);

				propertyDao.save(contractIinformation);
				result.put("desc", "约记录保存成功！");
				boolean resultFlag = assignSyncUser("1", ElementConstant.OPRATETYPE_ADD, contractIinformation, null);
				result.put("flag", resultFlag);
				if (!resultFlag) {
					result.put("desc", "同步信息异常！");
				}
			}
			return result;
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			result.put("flag", false);
			result.put("desc", "操作失败，程序异常！");
		}
		return result;
	}

	@Override
	public Map<String, Object> deleteBusinessRecord(Integer id) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			ContractIinformation contractIinformation = contractIinformationOrderDao.findContractIinformationObj(id);
			contractIinformation.setIsEnabled("0");
			propertyDao.updateObj(contractIinformation);
			result.put("desc", "签约记删除成功！");
			result.put("flag", true);

			assignSyncUser("1", ElementConstant.OPRATETYPE_DEL, contractIinformation, null);
			return result;
		} catch (Exception e) {
			log.error(LogExceptionStackUtil.LogExceptionStack(e));
			result.put("flag", false);
			result.put("desc", "操作失败，程序异常！");
		}
		return result;
	}

	@Override
	public Map<String, Object> businessRecordDetails(Integer id) {
		return contractIinformationOrderDao.businessRecordDetails(id);
	}

	@Override
	public List<Map<String, Object>> getBusinessRecordBuyUser(String userId) {
		return contractIinformationOrderDao.getBusinessRecordBuyUser(userId);
	}

	@Override
	public ContractIinformation getContractIinformationByVirtualId(
			Integer virtualId) {
		return contractIinformationOrderDao.getContractIinformation(virtualId);
	}

	@Override
	public boolean assignSyncUser(String type, String operateType,
								  ContractIinformation contractIinformation,
								  ContractIinformationOrder contractIinformationOrder) {
		if ("1".equals(type)) {
			TbOrganization      organization = propertyDao.getTbOrganizationById(contractIinformation.getOrganizationId());
			VirtualArchitecture virtual      = propertyDao.getVirtualArchitectureById(contractIinformation.getVirtualArchitectureId());
			log.info("organization----------" + organization);
			log.info("organization----------" + organization.getId());
			log.info("organization----------" + organization.getCode());
			log.info("virtual----------" + virtual.getId());
			log.info("virtual----------" + virtual);

			StringBuffer strParams = new StringBuffer();
			strParams.append("userName=" + virtual.getName());
			strParams.append("&userMobile=" + virtual.getPhone());
			strParams.append("&address=" + virtual.getAddress());
			strParams.append("&organizationCode=" + organization.getCode());
			strParams.append("&customerNo=" + virtual.getCustomerNumber());
			strParams.append("&customerType=" + 1);
			strParams.append("&signStatus=" + 1);
			strParams.append("&operateType=" + operateType);
			boolean result = UserinformationSync.assignuser(strParams.toString());
			log.info("assignSyncUser----------");
			log.info("strParams:" + strParams);
			log.info("result:" + result);
			return result;
		} else {
			StringBuffer strParams  = new StringBuffer();
			String       signStatus = "0";
			AppUser      appUser    = appuserDao.get(contractIinformationOrder.getUserId());
			strParams.append("userName=" + appUser.getUserName());
			strParams.append("&userMobile=" + appUser.getUserMobile());
			if (contractIinformationOrder.getOrganizationId() != null) {
				TbOrganization organization = propertyDao.getTbOrganizationById(contractIinformationOrder.getOrganizationId());
				strParams.append("&organizationCode=" + organization.getCode());
			}
			if (contractIinformationOrder.getVirtualArchitectureId() != null) {
				//获取企业是否签约
				contractIinformation = contractIinformationOrderDao.getContractIinformation(contractIinformationOrder.getVirtualArchitectureId());
				if (contractIinformation != null) {
					VirtualArchitecture virtual = propertyDao.getVirtualArchitectureById(contractIinformationOrder.getVirtualArchitectureId());
					strParams.append("&address=" + virtual.getAddress());
					strParams.append("&customerNo=" + virtual.getCustomerNumber());
					signStatus = "1";
				}
			}
			strParams.append("&customerType=" + 2);
			strParams.append("&signStatus=" + signStatus);
			strParams.append("&operateType=" + operateType);
			boolean result = UserinformationSync.assignuser(strParams.toString());
			log.info("assignSyncUser----------");
			log.info("strParams:" + strParams);
			log.info("result:" + result);
			return result;
		}
	}

	@Override
	public boolean saveContractIinformationOrder(String userMobile,
												 String serviceCode, String customerNo) {
		AppUser appUser = appuserDao.getAppUsersByPhone(userMobile);
		if (appUser != null) {
			if (StringUtils.isNotBlank(customerNo)) {
				VirtualArchitecture virtual = propertyDao.getVirtualArchitectureByCustomerNumber(customerNo);
				if (virtual != null) {
					appUser.setVirtualArchId(virtual.getId());
					appUser.setVirtualArchName(virtual.getName());
					appUser.setStatus(ElementConstant.USER_CERT_STATUSYES);
					appUser.setOrganizationId(virtual.getOrganizationId());
					appUser.setModifyTime(new Date());
					appuserDao.updateObj(appUser);
				}
			}
			ContractIinformationOrder contractIinformationOrder = contractIinformationOrderDao.getContractIinformationOrder(appUser.getId(), serviceCode);
			//如果用户记录不存在
			if (contractIinformationOrder == null) {
				contractIinformationOrder = new ContractIinformationOrder();
				contractIinformationOrder.setOrganizationId(appUser.getOrganizationId());
				if (appUser.getVirtualArchId() != null) {
					contractIinformationOrder.setVirtualArchitectureId(appUser.getVirtualArchId());
					ContractIinformation contractIinformation = contractIinformationOrderDao.getContractIinformation(appUser.getVirtualArchId());
					if (contractIinformation != null) {
						contractIinformationOrder.setStatus("1");
					} else {
						contractIinformationOrder.setStatus("0");
					}
				}
				contractIinformationOrder.setOrderType(serviceCode);
				contractIinformationOrder.setUserId(appUser.getId());
				contractIinformationOrder.setIsEnabled("1");
				propertyDao.saveObj(contractIinformationOrder);
			}
			//如果存在，看下customerNo是否为空
			else if (StringUtils.isNotBlank(customerNo)) {
				if (appUser.getVirtualArchId() != null) {
					contractIinformationOrder.setVirtualArchitectureId(appUser.getVirtualArchId());
					ContractIinformation contractIinformation = contractIinformationOrderDao.getContractIinformation(appUser.getVirtualArchId());
					if (contractIinformation != null) {
						contractIinformationOrder.setStatus("1");
					} else {
						contractIinformationOrder.setStatus("0");
					}
				}
				contractIinformationOrder.setOrderType(serviceCode);
				contractIinformationOrder.setUserId(appUser.getId());
				contractIinformationOrder.setIsEnabled("1");
				propertyDao.updateObj(contractIinformationOrder);
			}
			return true;
		}
		return false;
	}

	@Override
	public List<VirtualArchitecture> getSignVirtualArchitectureList(
			String organizationId) {
		List<VirtualArchitecture> resultList = new ArrayList<VirtualArchitecture>();

		List<ContractIinformation> list = contractIinformationOrderDao.getContractIinformationByOrgId(Integer.parseInt(organizationId));
		for (ContractIinformation contractIinformation : list) {
			VirtualArchitecture v = propertyDao.getVirtualArchitectureById(contractIinformation.getVirtualArchitectureId());
			resultList.add(v);
		}
		return resultList;
	}

	@Override
	public Integer getContractIinformationCount() {

		return contractIinformationOrderDao.getContractIinformationCount();
	}

	@Override
	public boolean assignContractIinformation(int virtualId, String serviceCode) {
		ContractIinformation model = contractIinformationOrderDao.getContractIinformation(virtualId);
		//更新
		if (model != null) {
			if (model.getType().contains(serviceCode + ",")) {
				return true;
			} else {
				model.setType(model.getType() + "," + serviceCode + ",");
				model.setModifyTime(new Date());
				propertyDao.updateObj(model);
				return assignSyncUser("1", "2", model, null);
			}
		}
		//新增
		else {
			VirtualArchitecture virtual = propertyDao.getVirtualArchitectureById(virtualId);
			virtual.setContractStatus("1"); //签约状态
			propertyDao.updateObj(virtual);

			model = new ContractIinformation();
			model.setOrganizationId(virtual.getOrganizationId());
			model.setVirtualArchitectureId(virtualId);
			model.setStatus("1");
			model.setType(serviceCode + ",");
			model.setCreateTime(new Date());
			model.setIsEnabled(ElementConstant.YESORNO_1);
			propertyDao.saveObj(model);
			return assignSyncUser("1", "1", model, null);
		}
	}

	@Override
	public void updateVirtualContractStatus() {
		List<ContractIinformation> constractInformation = contractIinformationOrderDao.getContractIinformationList();
		for (ContractIinformation contractIinformation : constractInformation) {
			VirtualArchitecture virtual = propertyDao.getVirtualArchitectureById(contractIinformation.getVirtualArchitectureId());
			virtual.setContractStatus("1");
			propertyDao.updateObj(virtual);
		}
	}

}
