package com.palmnest.service.wechat.impl;

import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.ElementConstant;
import com.palmnest.application.core.util.LogExceptionStackUtil;
import com.palmnest.application.core.util.Pages;
import com.palmnest.dao.estateserve.StaffDao;
import com.palmnest.dao.property.PropertyDao;
import com.palmnest.dao.wechat.SignContractDao;
import com.palmnest.model.StaffRelationBuild;
import com.palmnest.model.estateserve.*;
import com.palmnest.model.property.TbBuild;
import com.palmnest.model.property.VirtualArchitecture;
import com.palmnest.service.impl.GenericManagerImpl;
import com.palmnest.service.property.PropertyManager;
import com.palmnest.service.wechat.SignContractManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 签约管理微信端实现类
 *
 * @author xiemin
 * @date 2017-05-18
 */
@Slf4j
@Component("signContractManager")
public class SignContractManagerImpl extends GenericManagerImpl<Recharge, Integer> implements SignContractManager {


	@Autowired
	private SignContractDao signContractDao;
	@Autowired
	private PropertyManager propertyManager;
	@Autowired
	private StaffDao        staffDao;
	@Autowired
	private PropertyDao     propertyDao;

	@Override
	public List<VirtualArchitecture> findVirtualArchitectureList(String virtualName, Integer organizationId, String type) {
		try {
			return signContractDao.findVirtualArchitectureList(virtualName, organizationId, type);
		} catch (Exception e) {
			log.error("findVirtualArchitectureList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public JSONObject addVirtualArchitecture(Map<String, String> map) {

		JSONObject json = new JSONObject();

		try {
			if (map == null) {
				json.put("code", -1);
				json.put("msg", "添加失败");
				return json;
			}
			if (null == map.get("name") || map.get("name").equals("")) {
				json.put("code", -1);
				json.put("msg", "企业名称不能为空");
				return json;
			}
			if (null == map.get("employees") || map.get("employees").equals("")) {
				json.put("code", -1);
				json.put("msg", "企业人数不能为空");
				return json;
			}
			if (null == map.get("contacts") || map.get("contacts").equals("")) {
				json.put("code", -1);
				json.put("msg", "企业联系人不能为空");
				return json;
			}
			if (null == map.get("phone") || map.get("phone").equals("")) {
				json.put("code", -1);
				json.put("msg", "企业联系方式不能为空");
				return json;
			}

			//验证手机号码、带区号、不带区号的电话号码、400、800号码
			String expression = "^((13[0-9])|(15[^4,\\D])|(14[0,1-9])|(18[0,1-9])|(17[0,1-9]))\\d{8}$"
					+ "||" + "^\\d{3}-?\\d{3}-?\\d{4}|\\d{3}-?\\d{3}-?\\d{4}&"
					+ "||" + "^\\d{4}-?\\d{8}|\\d{4}-?\\d{8}&"
					+ "||" + "^\\d{4}-?\\d{7}|\\d{4}-?\\d{7}&"
					+ "||" + "^\\d{3}-?\\d{7}|\\d{4}-?\\d{7}&"
					+ "||" + "^\\d{3}-?\\d{8}|\\d{4}-?\\d{8}&"
					+ "||" + "^\\d{8}|\\d{4}-?\\d{8}&";

			Pattern pattern = Pattern.compile(expression);
			Matcher matcher = pattern.matcher(map.get("phone"));

			if (!matcher.matches()) {
				json.put("code", "-1");
				json.put("msg", "请输入正确的电话号码");
				return json;
			}

			if (null == map.get("organizationId") || map.get("organizationId").equals("")) {
				json.put("code", -1);
				json.put("msg", "请选择企业");
				return json;
			}
			VirtualArchitecture virtualArchitecture = signContractDao.findVirtualArchitecture(map.get("name"), Integer.valueOf(map.get("organizationId")), ElementConstant.YESORNO_1);
			if (null != virtualArchitecture) {
				json.put("code", -1);
				json.put("msg", "该企业已经签约，请前往个人中心续约");
				return json;
			}
			
			/*TbOrganization to = propertyManager.getTbOrganizationById(Integer.valueOf(map.get("organizationId")));
			//根据最大id查询企业编号
			String customerNumber = signContractDao.findCustomerNumberMaxId(map.get("organizationId"));
			
			String cityCode = "";
			if(null != to){
				String city = to.getCityName().replace("市", "");
				cityCode = FirstLetterUtil.getPinYinHeadCharCode(city,customerNumber).toUpperCase();
			}*/

			String newCustomerNumber = propertyManager.getVirtualCustomerNo(Integer.parseInt(map.get("organizationId")));
			map.put("customerNumber", newCustomerNumber);

			int result = signContractDao.addVirtualArchitecture(map);
			if (result > 0) {
				virtualArchitecture = new VirtualArchitecture();
				virtualArchitecture = propertyManager.getVirtualArchitectureById(result);
				virtualArchitecture.setCode(result + "");
				propertyManager.saveModel(virtualArchitecture);
				json.put("virtualArchitectureId", result);
				json.put("code", 0);
				json.put("msg", "签约企业添加成功");
				return json;
			}
		} catch (Exception e) {
			log.error("addVirtualArchitecture occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		json.put("code", -1);
		json.put("msg", "签约企业添加失败");
		return json;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public JSONObject addSignContract(Map<String, String> map) {
		JSONObject json = new JSONObject();
		try {
			if (map == null) {
				json.put("code", -1);
				json.put("msg", "添加失败");
				return json;
			}
			if (null == map.get("serviceId") || map.get("serviceId").equals("")) {
				json.put("code", -1);
				json.put("msg", "请选择服务项");
				return json;
			}
			if (null == map.get("startTime") || map.get("startTime").equals("")) {
				json.put("code", -1);
				json.put("msg", "请选择服务开始时间");
				return json;
			}
			if (null == map.get("endTime") || map.get("endTime").equals("")) {
				json.put("code", -1);
				json.put("msg", "请选择服务结束时间");
				return json;
			}
			if (null == map.get("paymentType") || map.get("paymentType").equals("")) {
				json.put("code", -1);
				json.put("msg", "请选择支付方式");
				return json;
			}
			/*if(null == map.get("dataIdarr") || map.get("dataIdarr").equals("")){
				json.put("code", -1);
				json.put("msg", "请选择商品");
				return json;
			}*/
			if (null != map.get("remarks") && !map.get("remarks").equals("")) {
				if (map.get("remarks").length() >= 200) {
					json.put("code", -1);
					json.put("msg", "详情长度超过200字符，请重新填写");
					return json;
				}
			}
			//根据服务id企业id查询企业已经签约信息，存在则不让继续签约
			if (null == map.get("signContractId") || map.get("signContractId").equals("")) {
				Map<String, String> newMap = new HashMap<String, String>();
				newMap.put("isEnabled", "1");//已经签名的信息
				newMap.put("serviceId", map.get("serviceId"));
				newMap.put("organizationId", map.get("organizationId"));
				newMap.put("virtualArchitectureId", map.get("virtualArchitectureId"));
				SignContract sc = signContractDao.findSignContract(newMap);
				if (null != sc) {
					json.put("code", -1);
					json.put("msg", "该企业的该服务已经签约，请勿重复签约！");
					return json;
				}
			}

			//查询签约信息，更新未签名的签约
			if (null == map.get("signContractId") || map.get("signContractId").equals("")) {
				map.put("isEnabled", "0");//未签名的信息
				SignContract sc = signContractDao.findSignContract(map);
				if (null != sc) {
					map.put("signContractId", sc.getId() + "");
				}
			}
			int result = signContractDao.addSignContract(map);
			if (result > 0) {
				//添加押金子项
				if (null != map.get("deposititem") && !map.get("deposititem").equals("") && null != map.get("deposititemId") && !map.get("deposititemId").equals("")) {
					String deposititemId[] = map.get("deposititemId").replaceAll("\"", "").toString().split(",");
					String deposititem[]   = map.get("deposititem").replaceAll("\"", "").toString().split(",");
					/*for(String dtId : deposititemId){//押金子项id
						for(String dt : deposititem){//押金子项数量
							Map<String,String> mapBignBasics = new HashMap<String, String>();
							mapBignBasics.put("basicsId", dtId);
							DepositItemInformationForm dif = signContractDao.queryDepositItem(dtId);
							mapBignBasics.put("number", dt);
							mapBignBasics.put("signid", result+"");
							BigDecimal totalAmount = dif.getPrice().multiply(BigDecimal.valueOf(Double.valueOf(dt)));
							mapBignBasics.put("totalAmount", String.valueOf(totalAmount));
							signContractDao.addSignBasics(mapBignBasics);
						}
					}*/
					if (null != deposititemId && deposititemId[0].length() > 0 && null != deposititem && deposititem[0].length() > 0) {
						for (int i = 0; i < deposititemId.length; i++) {

							Map<String, String> mapBignBasics = new HashMap<String, String>();
							String              dtId          = deposititemId[i];//押金子项id
							signContractDao.deleteSignBasics(dtId, result);//删除押金子项目

							String dt = deposititem[i];//押金子项数量
							if (dt.equals("0")) {
								continue;
							}
							mapBignBasics.put("basicsId", dtId);
							DepositItemInformationForm dif = signContractDao.queryDepositItem(dtId);
							mapBignBasics.put("number", dt);
							mapBignBasics.put("signId", result + "");
							BigDecimal totalAmount = dif.getPrice().multiply(BigDecimal.valueOf(Double.valueOf(dt)));
							mapBignBasics.put("totalAmount", String.valueOf(totalAmount));
							signContractDao.addSignBasics(mapBignBasics);
						}
					}
				}
				Map<String, String> mapProductSign = new HashMap<String, String>();
				String              dataIdarr[]    = map.get("dataIdarr").replaceAll("\"", "").toString().split(",");

				if (null != dataIdarr && dataIdarr[0].length() > 0) {
					//添加商品与签约中间信息
					for (String servicePackDetailsId : dataIdarr) {//商品id
						signContractDao.deleteProductSign(result, servicePackDetailsId);//删除意向商品信息
						mapProductSign.put("signContractId", result + "");
						mapProductSign.put("servicePackDetailsId", servicePackDetailsId);
						signContractDao.addProductSign(mapProductSign);
					}
				}
				json.put("signContractId", result);
				json.put("code", 0);
				json.put("msg", "签约添加成功");
				return json;
			}
		} catch (Exception e) {
			log.error("addSignContract occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		json.put("code", -1);
		json.put("msg", "签约添加失败");
		return json;
	}

	@Override
	public JSONObject updateSignContract(String id, String imageUrl, String renewalContractId) {
		JSONObject json = new JSONObject();
		try {
			int result = signContractDao.updateSignContract(id, imageUrl);
			if (result > 0) {
				//根据原始id更新原始续约状态
				if (StringUtils.isNotEmpty(renewalContractId) && !id.equals(renewalContractId)) {//相等则用户返回了
					signContractDao.updateRenewalContract(renewalContractId, ElementConstant.YESORNO_1);
				}
				json.put("code", 0);
				json.put("msg", "添加签名信息成功");
				return json;
			}

		} catch (Exception e) {
			log.error("updateSignContract occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		json.put("code", -1);
		json.put("msg", "添加签名信息失败");
		return json;
	}

	@Override
	public int updateSignContractStatus(String id, String status) {
		try {
			int result = signContractDao.updateSignContractStatus(id, status);
			return result;
		} catch (Exception e) {
			log.error("updateSignContractStatus occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return -1;
	}

	@Override
	public JSONObject addSignServiceInvoice(Map<String, String> map) {
		JSONObject json = new JSONObject();
		if (map == null) {
			json.put("code", -1);
			json.put("msg", "添加失败");
			return json;
		}
		if (map.get("type") == null || map.get("type").equals("")) {
			json.put("code", -1);
			json.put("msg", "请选择发票类型");
			return json;
		}
		if (map.get("raise") == null || map.get("raise").equals("")) {
			json.put("code", -1);
			json.put("msg", "请填写发票抬头");
			return json;
		}
		if (map.get("type").equals("2") && (map.get("address") == null || map.get("address").equals(""))) {
			json.put("code", -1);
			json.put("msg", "请填写详细地址");
			return json;
		}
		if (map.get("identificationNumber") == null || map.get("identificationNumber").equals("")) {
			json.put("code", -1);
			json.put("msg", "请填写纳税人识别号");
			return json;
		}
		if (map.get("type").equals("2") && (map.get("mobile") == null || map.get("mobile").equals(""))) {
			json.put("code", -1);
			json.put("msg", "请填写联系电话");
			return json;
		}

		if (map.get("type").equals("2")) {
			//验证手机号码、带区号、不带区号的电话号码、400、800号码
			String expression = "^((13[0-9])|(15[^4,\\D])|(14[0,1-9])|(18[0,1-9])|(17[0,1-9]))\\d{8}$"
					+ "||" + "^\\d{3}-?\\d{3}-?\\d{4}|\\d{3}-?\\d{3}-?\\d{4}&"
					+ "||" + "^\\d{4}-?\\d{8}|\\d{4}-?\\d{8}&"
					+ "||" + "^\\d{4}-?\\d{7}|\\d{4}-?\\d{7}&"
					+ "||" + "^\\d{3}-?\\d{7}|\\d{4}-?\\d{7}&"
					+ "||" + "^\\d{3}-?\\d{8}|\\d{4}-?\\d{8}&"
					+ "||" + "^\\d{8}|\\d{4}-?\\d{8}&";

			Pattern pattern = Pattern.compile(expression);
			Matcher matcher = pattern.matcher(map.get("mobile"));

			if (!matcher.matches()) {
				json.put("code", "-1");
				json.put("msg", "请输入正确的电话号码");
				return json;
			}
		}

		if (map.get("type").equals("2") && (map.get("bank") == null || map.get("bank").equals(""))) {
			json.put("code", -1);
			json.put("msg", "请填写开户行");
			return json;
		}
		if (map.get("type").equals("2") && (map.get("bankCard") == null || map.get("bankCard").equals(""))) {
			json.put("code", -1);
			json.put("msg", "请填写银行卡号");
			return json;
		}
		try {
			int result = signContractDao.addSignServiceInvoice(map);
			if (result > 0) {
				json.put("signServiceInvoiceId", result);
				json.put("code", 0);
				json.put("msg", "添加发票信息成功");
				return json;
			}
		} catch (Exception e) {
			log.error("updateSignContract occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		json.put("code", -1);
		json.put("msg", "添加发票信息失败");
		return json;
	}

	@Override
	public List<Map<String, Object>> getSignContractListByVirId(int virtualId) {
		return signContractDao.getSignContractListByVirId(virtualId);
	}

	@Override
	public List<Map<String, Object>> getSignContractListBySignid(String signid)
			throws Exception {
		try {
			return signContractDao.getSignContractListBySignid(signid);
		} catch (Exception e) {
			log.error("getSignContractListBySignid occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public SignBasics getSignBasicsObj(Integer id) {
		try {
			return signContractDao.getSignBasicsObj(id);
		} catch (Exception e) {
			log.error("getSignBasicsObj occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public Map<String, Object> getIsSignBasics(String signId, String basicsId,
											   Integer id) {
		try {
			return signContractDao.getIsSignBasics(signId, basicsId, id);
		} catch (Exception e) {
			log.error("getIsSignBasics occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}


	@Override
	public SignServiceInvoice getSignServiceInvoiceObj(Integer virtualId,
													   String type) {
		try {
			return signContractDao.getSignServiceInvoiceObj(virtualId, type);
		} catch (Exception e) {
			log.error("getSignServiceInvoiceObj occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getIntentionalGoods(Integer id) {
		try {
			return signContractDao.getIntentionalGoods(id);
		} catch (Exception e) {
			log.error("getIntentionalGoods occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<TbBuild> findTbOrganizationById(String userId) {
		try {
			List<TbBuild>            tbBuildList = new ArrayList<TbBuild>();
			List<StaffRelationBuild> relations   = new ArrayList<StaffRelationBuild>();
			//查询员工管辖的楼栋信息
			relations = staffDao.getStaffRelationBuildList(Integer.valueOf(userId));

			for (StaffRelationBuild sbd : relations) {
				//关联楼栋
				TbBuild tb = propertyDao.getTbBuildById(sbd.getBuildId());
				tbBuildList.add(tb);
			}
			return tbBuildList;
		} catch (Exception e) {
			log.error("findTbOrganizationById occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public Pages<Map<String, String>> findContract(Map<String, String> map) {
		try {
			return signContractDao.findContract(map);
		} catch (Exception e) {
			log.error("findContract occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getStaffByOrganztion(Integer userId) {
		try {
			return signContractDao.getStaffByOrganztion(userId);
		} catch (Exception e) {
			log.error("getStaffByOrganztion occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<SignServiceInvoice> getSignServiceInvoiceList(Integer virtualId) {
		try {
			return signContractDao.getSignServiceInvoiceList(virtualId);
		} catch (Exception e) {
			log.error("getSignServiceInvoiceList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getSignContractList(Integer virtualId) {
		try {
			return signContractDao.getSignContractList(virtualId);
		} catch (Exception e) {
			log.error("getSignContractList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> getSignBasicsList(String id)
			throws Exception {
		try {
			return signContractDao.getSignBasicsList(id);
		} catch (Exception e) {
			log.error("getSignBasicsList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public SignContract findSignContract(String signContractId) {
		try {
			return signContractDao.findSignContract(signContractId);
		} catch (Exception e) {
			log.error("findSignContract occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> findProductSign(String signContractId) {
		try {
			return signContractDao.findProductSign(signContractId);
		} catch (Exception e) {
			log.error("findProductSign occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<Map<String, Object>> findSignBasics(String signContractId) {
		try {
			return signContractDao.findSignBasics(signContractId);
		} catch (Exception e) {
			log.error("findSignBasics occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

	@Override
	public List<SignContract> findSignContractList() {
		try {
			return signContractDao.findSignContractList();
		} catch (Exception e) {
			log.error("findSignContractList occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		}
		return null;
	}

}
