package com.uas.account.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import com.uas.account.core.Const;
import com.uas.account.core.Logger;
import com.uas.account.core.Page;
import com.uas.account.core.Status;
import com.uas.account.dao.PartnershipRecordDao;
import com.uas.account.dao.UserDao;
import com.uas.account.dao.UserSpaceDao;
import com.uas.account.entity.InvitationRecord;
import com.uas.account.entity.PartnershipRecord;
import com.uas.account.entity.RequsetStatus;
import com.uas.account.entity.Setting;
import com.uas.account.entity.User;
import com.uas.account.entity.UserSpace;
import com.uas.account.entity.UserSpaceDetail;
import com.uas.account.entity.UserView;
import com.uas.account.exception.VisibleError;
import com.uas.account.support.SystemSession;
import com.uas.message.mail.service.MailService;
import com.uas.message.sms.service.SmsService;

@Service
public class PartnershipServiceImpl implements PartnershipService {

	@Autowired
	private UserSpaceService userSpaceService;
	@Autowired
	private PartnershipRecordDao partnershipRecordDao;
	@Autowired
	private UserSpaceDao userSpaceDao;
	@Autowired
	private SettingService settingService;
	@Autowired
	private MailService mailService;
	@Autowired
	private SmsService smsService;
	@Autowired
	private UserDao userDao;

	private Logger logger = Logger.getLogger();

	@Override
	public void sendRequestById(Long id) {
		UserSpaceDetail detail = userSpaceService.findById(id);
		User custuser = SystemSession.getUser();
		if (custuser == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		UserSpaceDetail custEnter = userSpaceDao.findByBusinessCode(custuser.getSpaceUID());
		if (custEnter.getBusinessCode().equals(detail.getBusinessCode())) {
			throw new VisibleError("不能添加自己企业为合作伙伴");
		}
		PartnershipRecord oldSendRecord = partnershipRecordDao.findByCustUIDAndVendUID(custEnter.getBusinessCode(),
				detail.getBusinessCode());
		if (oldSendRecord != null) {
			if (oldSendRecord.getStatusCode().equals(Status.UNAUDIT.value())) {
				throw new VisibleError("对该企业的申请已经存在，请不要重复申请");
			}

			if (oldSendRecord.getStatusCode().equals(Status.ENABLED.value())) {
				throw new VisibleError("该企业已经同意您的申请，请不要重复申请");
			}
		}
		PartnershipRecord oldReceiveRecord = partnershipRecordDao.findByCustUIDAndVendUID(detail.getBusinessCode(),
				custEnter.getBusinessCode());
		if (oldReceiveRecord != null) {
			if (!oldReceiveRecord.getStatusCode().equals(Status.UNAPPLY.value())) {
				throw new VisibleError("该企业已经向您发出了申请，请注意查看您收到的申请记录");
			}
		}
		UserSpace userSpace = userSpaceService.findOne("b2b", detail.getBusinessCode());
		ModelMap data = new ModelMap();
		data.put("vendorusername", detail.getAdminName());
		data.put("vendorname", detail.getName());
		data.put("custname", custEnter.getName());
		if (null == userSpace) {// 未开通商务平台，提醒开通
			Setting mailTplId = settingService.findOne("templateForSendEmailWhenAddPartner");
			if (!StringUtils.isEmpty(mailTplId) && !StringUtils.isEmpty(detail.getAdminEmail())) {
				mailService.send(mailTplId.getValue(), detail.getAdminEmail(), data);
			}
			Setting smsTplId = settingService.findOne("templateForSendSmsWhenAddPartner");
			if (!StringUtils.isEmpty(smsTplId) && !StringUtils.isEmpty(detail.getAdminTel())) {
				smsService.send(smsTplId.getValue(), detail.getAdminTel(),
						new Object[] { detail.getAdminName(), detail.getName(), custEnter.getName() });
			}
		}
		PartnershipRecord record = new PartnershipRecord();
		record.setVendUID(detail.getBusinessCode());
		record.setVendName(detail.getName());
		record.setStatusCode(Status.UNAUDIT.value());
		record.setStatus(Status.UNAUDIT.getPhrase());
		record.setRequestDate(new Date());
		record.setCustName(custEnter.getName());
		record.setCustUID(custEnter.getBusinessCode());
		record.setCustUserName(custuser.getName());
		record.setCustUserCode(custuser.getDialectUID());
		record.setCustUserTel(custuser.getUid());
		record.setCustUserEmail(custuser.getSecondUID());
		record.setAppId(custuser.getAppId());
		logger.info(custuser.getDialectUID() + "向" + detail.getName() + "发出了建立合作关系的申请");
		partnershipRecordDao.save(record);
	}

	@Override
	public Page<PartnershipRecord> findAllSendUnAudit(String name, String businessCode, String custUserName,
			int pageNumber, int pageSize) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		return partnershipRecordDao.findAllSendView(pageNumber, businessCode, custUserName, pageSize, name,
				user.getSpaceUID(), null,
				Status.UNAUDIT.value());
	}

	@Override
	public Page<PartnershipRecord> findAllSendEnable(String name, String businessCode, String custUserName,
			int pageNumber, int pageSize) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		return partnershipRecordDao.findAllSendView(pageNumber, businessCode, custUserName, pageSize, name,
				user.getSpaceUID(), null,
				Status.ENABLED.value());
	}

	@Override
	public Page<PartnershipRecord> findAllSendUnApply(String name, String businessCode, String custUserName,
			int pageNumber, int pageSize) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		return partnershipRecordDao.findAllSendView(pageNumber, businessCode, custUserName, pageSize, name,
				user.getSpaceUID(), null,
				Status.UNAPPLY.value());
	}

	@Override
	public Page<PartnershipRecord> findAllReceivedUnAudit(String name, String businessCode, String custUserName,
			int pageNumber, int pageSize) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		return partnershipRecordDao.findAllReceivedView(pageNumber, businessCode, custUserName, pageSize, name,
				user.getSpaceUID(),
				Status.UNAUDIT.value());
	}

	@Override
	public Page<PartnershipRecord> findAllReceivedEnable(String name, String businessCode, String custUserName,
			int pageNumber, int pageSize) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		return partnershipRecordDao.findAllReceivedView(pageNumber, businessCode, custUserName, pageSize, name,
				user.getSpaceUID(), Status.ENABLED.value());
	}

	@Override
	public Page<PartnershipRecord> findAllReceivedUnApply(String name, String businessCode, String custUserName,
			int pageNumber, int pageSize) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		return partnershipRecordDao.findAllReceivedView(pageNumber, businessCode, custUserName, pageSize, name,
				user.getSpaceUID(), Status.UNAPPLY.value());
	}

	@Override
	public PartnershipRecord findSendRequestById(Long id) {
		return partnershipRecordDao.findById(id);
	}

	@Override
	public PartnershipRecord findReceivedRequestById(Long id) {
		return partnershipRecordDao.findById(id);
	}

	@Override
	public void enable(Long id) {
		User user = SystemSession.getUser();
		PartnershipRecord partner = partnershipRecordDao.findById(id);
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		if (partner == null) {
			throw new VisibleError("未找到该企业信息");
		}
		if (partner != null && user != null) {
			logger.info(user.getName() + "同意了" + partner.getCustName() + "的请求");
			partner.setStatus(Status.ENABLED.getPhrase());
			partner.setStatusCode(Status.ENABLED.value());
			partner.setOperateDate(new Date());
			partner.setVendUserCode(user.getDialectUID());
			partner.setVendUserTel(user.getUid());
			partner.setVendUserEmail(user.getSecondUID());
			partner.setVendUserName(user.getName());
			partner.setId(id);
			partnershipRecordDao.save(partner);
		}

	}

	@Override
	public void disable(Long id, String reason) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当期用户信息，请先通过UAS系统或商务平台登录");
		} else {
			PartnershipRecord partner = partnershipRecordDao.findById(id);
			logger.info(user.getName() + "拒绝了" + partner.getCustName() + "的请求");
			partner.setStatus(Status.UNAPPLY.getPhrase());
			partner.setStatusCode(Status.UNAPPLY.value());
			partner.setReason(reason);
			partner.setOperateDate(new Date());
			partner.setVendUserCode(user.getDialectUID());
			partner.setVendUserName(user.getName());
			partner.setVendUserEmail(user.getSecondUID());
			partner.setVendUserName(user.getName());
			partner.setId(id);
			partnershipRecordDao.save(partner);
		}
	}

	@Override
	public void resendRequestById(Long id) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当期用户信息，请先通过UAS系统或商务平台登录");
		} else {
			PartnershipRecord partner = partnershipRecordDao.findById(id);
			logger.info(user.getDialectUID() + "向" + partner.getVendName() + "发出了建立合作关系的申请");
			partner.setStatus(Status.UNAUDIT.getPhrase());
			partner.setStatusCode(Status.UNAUDIT.value());
			partner.setRequestDate(new Date());
			partner.setCustUserCode(user.getDialectUID());
			partner.setCustUserEmail(user.getSecondUID());
			partner.setCustUserName(user.getName());
			partner.setCustUserTel(user.getUid());
			partnershipRecordDao.save(partner);
		}
	}

	@Override
	public PartnershipRecord findBycustUIDAndVendUID(String custuid, String venduid) {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		return partnershipRecordDao.findByCustUIDAndVendUID(custuid, venduid);
	}

	@Override
	public ModelMap getsendRequestCount() {
		User user = SystemSession.getUser();
		if(user==null){
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		ModelMap map = new ModelMap("全部", partnershipRecordDao.getAllSendCount(user.getSpaceUID()));
		map.addAllAttributes(partnershipRecordDao.getSendRequestCount(user.getSpaceUID()));
		return map;
	}

	@Override
	public ModelMap getreceivedRequestCount() {
		User user = SystemSession.getUser();
		if (user == null) {
			throw new VisibleError("未检测到当前用户信息，请先通过UAS系统或商务平台登录");
		}
		ModelMap map = new ModelMap("全部", partnershipRecordDao.getAllReceivedCount(user.getSpaceUID()));
		map.addAllAttributes(partnershipRecordDao.getReceivedRequestCount(user.getSpaceUID()));
		return map;
	}

	@Override
	public Page<PartnershipRecord> findBySpaceUidAndStatusCode(String businessCode, Integer statusCode, String keyword,
															   int pageNumber, int pageSize) {
		return partnershipRecordDao.findBySpaceUidAndStatusCode(businessCode, statusCode, keyword, pageNumber,
				pageSize);
	}

	@Override
	public Page<PartnershipRecord> findBySpaceUidAndStatusCodeFilterByPartnerUUs(String businessCode, Integer statusCode, String keyword, List<Long> partnerUUs,
															   int pageNumber, int pageSize) {
		return partnershipRecordDao.findBySpaceUidAndStatusCodeFilterByPartnerUUs(businessCode, statusCode, keyword, partnerUUs, pageNumber,
				pageSize);
	}

	@Override
	public ModelMap addPartner(PartnershipRecord record) {
		ModelMap map = new ModelMap();
		PartnershipRecord oldSendRecord = partnershipRecordDao.findByCustUIDAndVendUID(record.getCustUID(),
				record.getVendUID());
		PartnershipRecord oldReceiveRecord = partnershipRecordDao.findByCustUIDAndVendUID(record.getVendUID(),
				record.getCustUID());
		if (oldSendRecord != null && !oldSendRecord.getStatusCode().equals(Status.UNAPPLY.value())) {
			if (oldSendRecord.getStatusCode().equals(Status.UNAUDIT.value())) {
				map.put("error", "对该企业的申请已发出，请耐心等待对方审核");
			}
			if (oldSendRecord.getStatusCode().equals(Status.ENABLED.value())) {
				map.put("error", "您们已是合作伙伴，请不要重复申请");
			}
		}
		if (oldReceiveRecord != null && !oldReceiveRecord.getStatusCode().equals(Status.UNAPPLY.value())) {
			if (!oldReceiveRecord.getStatusCode().equals(Status.UNAPPLY.value())) {
				map.put("error", "该企业已经向您发出了申请，请注意查看您收到的申请记录");
			}
			if (!oldReceiveRecord.getStatusCode().equals(Status.ENABLED.value())) {
				map.put("error", "您们已是合作伙伴，请不要重复申请");
			}
		}
		if ((oldSendRecord == null && oldReceiveRecord == null)
				|| (oldSendRecord != null && oldSendRecord.getStatusCode().equals(Status.UNAPPLY.value()))
				|| (oldReceiveRecord != null && !oldReceiveRecord.getStatusCode().equals(Status.UNAPPLY.value()))) {
			UserSpace userSpace = userSpaceService.findOne("b2b", record.getVendUID());
			UserSpaceDetail detail = userSpaceService.findByBusinessCode(record.getVendUID());
			ModelMap data = new ModelMap();
			data.put("vendorusername", detail.getAdminName());
			data.put("vendorname", detail.getName());
			data.put("custname", record.getCustName());
			if (null == userSpace) {// 未开通商务平台，提醒开通
				Setting mailTplId = settingService.findOne("templateForSendEmailWhenAddPartner");
				if (!StringUtils.isEmpty(mailTplId) && !StringUtils.isEmpty(detail.getAdminEmail())) {
					mailService.send(mailTplId.getValue(), detail.getAdminEmail(), data);
				}
				Setting smsTplId = settingService.findOne("templateForSendSmsWhenAddPartner");
				if (!StringUtils.isEmpty(smsTplId) && !StringUtils.isEmpty(detail.getAdminTel())) {
					smsService.send(smsTplId.getValue(), detail.getAdminTel(),
							new Object[] { detail.getAdminName(), detail.getName(), record.getCustName() });
				}
			}
			record.setStatusCode(Status.UNAUDIT.value());
			record.setStatus(Status.UNAUDIT.getPhrase());
			record.setRequestDate(new Date());
			logger.info(record.getCustName() + "向" + detail.getName() + "发出了建立合作关系的申请");
			partnershipRecordDao.save(record);
			map.put("success", "申请发送成功");
		}
		return map;
	}

	@Override
	public ModelMap synchronizePartner(PartnershipRecord record) {
		ModelMap map = new ModelMap();
		PartnershipRecord oldSendRecord = partnershipRecordDao.findByCustUIDAndVendUID(record.getCustUID(),
				record.getVendUID());
		PartnershipRecord oldReceiveRecord = partnershipRecordDao.findByCustUIDAndVendUID(record.getVendUID(),
				record.getCustUID());
		if (oldSendRecord != null && !oldSendRecord.getStatusCode().equals(Status.ENABLED.value())) {
			oldSendRecord.setStatusCode(Status.ENABLED.value());
			oldSendRecord.setStatus(Status.ENABLED.getPhrase());
			oldSendRecord.setRequestDate(new Date());
			oldSendRecord.setOperateDate(new Date());
			partnershipRecordDao.save(oldSendRecord);
		}
		if (oldReceiveRecord != null && !oldReceiveRecord.getStatusCode().equals(Status.ENABLED.value())) {
			oldReceiveRecord.setStatusCode(Status.ENABLED.value());
			oldReceiveRecord.setStatus(Status.ENABLED.getPhrase());
			oldReceiveRecord.setRequestDate(new Date());
			oldReceiveRecord.setOperateDate(new Date());
			partnershipRecordDao.save(oldReceiveRecord);
		}
		if (oldSendRecord == null && oldReceiveRecord == null) {
			record.setStatusCode(Status.ENABLED.value());
			record.setStatus(Status.ENABLED.getPhrase());
			record.setRequestDate(new Date());
			record.setOperateDate(new Date());
			logger.info(record.getCustName() + "与" + record.getVendName() + "通过单据交易建立了合作关系");
			partnershipRecordDao.save(record);
			map.put("success", "建立合作关系成功");
		}
		return map;
	}

	@Override
	public ModelMap acceptRequest(Long id, String vendUserTel, String appId) {
		PartnershipRecord record = partnershipRecordDao.findById(id);
		ModelMap map = new ModelMap();
		List<UserView> user = userDao.findByAppAndUID(appId, vendUserTel);
		record.setAppId(appId);
		record.setOperateDate(new Date());
		record.setVendUserName(user.get(0).getName());
		record.setStatus(Status.ENABLED.getPhrase());
		record.setStatusCode(Status.ENABLED.value());
		partnershipRecordDao.save(record);
		map.put("success", "审核成功");
		return map;
	}

	@Override
	public ModelMap rejectRequest(Long id, String reason, String vendUserTel, String appId) {
		PartnershipRecord record = partnershipRecordDao.findById(id);
		ModelMap map = new ModelMap();
		List<UserView> user = userDao.findByAppAndUID(appId, vendUserTel);
		record.setAppId(appId);
		record.setOperateDate(new Date());
		record.setVendUserName(user.get(0).getName());
		record.setStatus(Status.UNAPPLY.getPhrase());
		record.setStatusCode(Status.UNAPPLY.value());
		record.setReason(reason);
		partnershipRecordDao.save(record);
		map.put("success", "审核成功");
		return map;
	}

	@Override
	public RequsetStatus getRequestByCustUidAndVendUid(String custUid, String vendUid) {
		RequsetStatus request = new RequsetStatus();
		PartnershipRecord receivedRequest = partnershipRecordDao.findByCustUIDAndVendUID(custUid, vendUid);
		if (receivedRequest != null) {// 发出申请
			request.setCustUid(custUid);
			request.setVendUid(vendUid);
			request.setStatusCode(receivedRequest.getStatusCode());
			request.setMethod(Const.NO);
			if (receivedRequest.getStatusCode() == 311) {
				request.setNeedAgreed(Const.YES);
			} else {
				request.setNeedAgreed(Const.NO);
			}
		}
		PartnershipRecord sendRequest = partnershipRecordDao.findByCustUIDAndVendUID(vendUid, custUid);
		if (sendRequest != null) {// 收到申请
			request.setCustUid(custUid);
			request.setVendUid(vendUid);
			request.setStatusCode(sendRequest.getStatusCode());
			request.setMethod(Const.YES);
			request.setNeedAgreed(Const.NO);
		}
		return request;
	}

	@Override
	public ModelMap getRequestTodo(String businessCode) {
		ModelMap map = new ModelMap();
		map.put("todo", partnershipRecordDao.getRequestTodo(businessCode));
		return map;
	}

	@Override
	public void invite(InvitationRecord record) {
		partnershipRecordDao.saveInvitation(record);
	}

}
