package com.uas.platform.b2b.service.impl;

import com.uas.sso.entity.PartnershipRecordView;
import com.uas.sso.support.Page;
import com.uas.sso.util.AccountUtils;
import com.uas.platform.b2b.core.util.ThreadTask;
import com.uas.platform.b2b.dao.*;
import com.uas.platform.b2b.model.*;
import com.uas.platform.b2b.service.AddPartnerService;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.b2b.temporary.model.BasePartnersInfo;
import com.uas.platform.core.model.Constant;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class AddPartnerServiceImpl implements AddPartnerService {

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private VendorDao vendorDao;

	@Autowired
	private UserBaseInfoDao userBaseInfoDao;

	@Autowired
	private UserDao userDao;

	@Autowired
	private UserOrderDao userOrderDao;

	@Override
	public ModelMap addSupplier(String businessCode) {
		Enterprise vendEnter = enterpriseDao.findEnterpriseByEnBussinessCode(businessCode);
		Enterprise myEnter = SystemSession.getUser().getEnterprise();
		ModelMap map = new ModelMap();
		if (vendEnter == null) {
			map.put("error","未查找到对应企业，请确认信息是否正确");
			return map;
		}
		// 先判断是否为供应商(因为添加了服务商概念，所以可能有存在记录但未添加的状况)
		List<Vendor> oldVendor = vendorDao.findByMyEnUUAndVendUU(myEnter.getUu(), vendEnter.getUu());
		if (!CollectionUtils.isEmpty(oldVendor)) {
			Vendor vendor = oldVendor.get(0);
			vendor.setVendswitch(Constant.YES);
			vendorDao.save(vendor);
			map.put("success", "添加供应商成功");
		} else {
			Vendor vendor = new Vendor();
			UserBaseInfo vendUser = userBaseInfoDao.findByUserUU(myEnter.getEnAdminuu());
			UserBaseInfo myUser = userBaseInfoDao.findByUserUU(vendEnter.getEnAdminuu());
			vendor.setMyEnterprise(myEnter);
			vendor.setMyEnUU(myEnter.getUu());
			vendor.setMyUser(myUser);
			vendor.setMyUserUU(myEnter.getEnAdminuu());
			vendor.setVendorEnterprise(vendEnter);
			vendor.setVendorUser(vendUser);
			vendor.setVendUserUU(vendEnter.getEnAdminuu());
			vendor.setVendEnUU(vendEnter.getUu());
			vendor.setVendswitch(Constant.YES);
			vendor.setCustswitch(Constant.YES);
			vendorDao.save(vendor);
			saveSupplierUserOrders(vendor);
			map.put("success", "添加供应商成功");
		}
		return map;
	}

	@Override
	public ModelMap addServicer(String businessCode) {
		Enterprise vendEnter = enterpriseDao.findEnterpriseByEnBussinessCode(businessCode);
		Enterprise myEnter = SystemSession.getUser().getEnterprise();
		ModelMap map = new ModelMap();
		if (vendEnter == null) {
			map.put("error","未查找到对应企业，请确认信息是否正确");
			return map;
		}
		// 先判断是否存在供应商关系记录
		List<Vendor> oldVendor = vendorDao.findByMyEnUUAndVendUU(myEnter.getUu(), vendEnter.getUu());
		if (!CollectionUtils.isEmpty(oldVendor)) {
			Vendor vendor = oldVendor.get(0);
			vendor.setServicerswitch(Constant.YES);
			vendorDao.save(vendor);
			map.put("success", "添加服务商成功");
		} else {
			Vendor vendor = new Vendor();
			UserBaseInfo vendUser = userBaseInfoDao.findByUserUU(myEnter.getEnAdminuu());
			UserBaseInfo myUser = userBaseInfoDao.findByUserUU(vendEnter.getEnAdminuu());
			vendor.setMyEnterprise(myEnter);
			vendor.setMyEnUU(myEnter.getUu());
			vendor.setMyUser(myUser);
			vendor.setMyUserUU(myEnter.getEnAdminuu());
			vendor.setVendorEnterprise(vendEnter);
			vendor.setVendorUser(vendUser);
			vendor.setVendUserUU(vendEnter.getEnAdminuu());
			vendor.setVendEnUU(vendEnter.getUu());
			vendor.setCustswitch(Constant.YES);
			vendor.setServicerswitch(Constant.YES);
			vendorDao.save(vendor);
			saveSupplierUserOrders(vendor);
			map.put("success", "添加服务商成功");
		}
		return map;
	}

	private void saveSupplierUserOrders(final Vendor vendor){
		final Long uu = SystemSession.getUser().getUserUU();
		ThreadTask.getInstance().execute(new Runnable() {
			@Override
			public void run() {
			/* 添加客户的阅读记录*/
				List<User> users = userDao.findByEnUU(vendor.getMyEnUU());
				UserOrders userOrders;
				List<UserOrders> list = new ArrayList<>();
				for (User user : users) {
					if (user == null || Objects.equals(user.getUserUU(), uu)) {
						continue;
					}
					userOrders = new UserOrders(user.getUserUU(), vendor.getMyEnUU(), vendor.getId(), "purc", "purc$vendors");
					list.add(userOrders);
				}
				userOrderDao.save(list);
			}
		});
	}

	@Override
	public ModelMap addCust(String businessCode) {
		Enterprise vendEnter = enterpriseDao.findEnterpriseByEnBussinessCode(businessCode);
		Enterprise myEnter = SystemSession.getUser().getEnterprise();
		ModelMap map = new ModelMap();
		// 先判断是否为客户
		List<Vendor> oldVendor = vendorDao.findByMyEnUUAndVendUU(vendEnter.getUu(), myEnter.getUu());
		if (!CollectionUtils.isEmpty(oldVendor)) {
			map.put("error", "该企业已经是您的客户，请不要重复添加");
		} else {
			Vendor vendor = new Vendor();
			UserBaseInfo vendUser = userBaseInfoDao.findByUserUU(vendEnter.getEnAdminuu());
			UserBaseInfo myUser = userBaseInfoDao.findByUserUU(myEnter.getEnAdminuu());
			vendor.setMyEnterprise(vendEnter);
			vendor.setMyEnUU(vendEnter.getUu());
			vendor.setMyUser(vendUser);
			vendor.setMyUserUU(vendUser.getUserUU());
			vendor.setVendorEnterprise(myEnter);
			vendor.setVendorUser(myUser);
			vendor.setVendUserUU(myUser.getUserUU());
			vendor.setVendEnUU(myEnter.getUu());
			vendor.setCustswitch(Constant.YES);
			vendor = vendorDao.save(vendor);
			// 添加用户未读状态
			saveCustomerUserOrders(vendor);
			map.put("success", "添加客户成功");
		}
		return map;
	}

	private void saveCustomerUserOrders(final Vendor vendor){
		final Long uu = SystemSession.getUser().getUserUU();
		ThreadTask.getInstance().execute(new Runnable() {
			@Override
			public void run() {
			/* 添加客户的阅读记录*/
				List<User> users = userDao.findByEnUU(vendor.getVendEnUU());
				UserOrders userOrders;
				List<UserOrders> list = new ArrayList<>();
				for (User user : users) {
					if (user == null || Objects.equals(user.getUserUU(), uu)) {
						continue;
					}
					userOrders = new UserOrders(user.getUserUU(), vendor.getVendEnUU(), vendor.getId(), "sale", "purc$vendors");
					list.add(userOrders);
				}
				userOrderDao.save(list);
			}
		});
	}

	/**
	 *  ERP企业圈获取全部合作伙伴
	 * @param keyword
	 * @param statusCode
	 * @param pageSize
	 * @param pageNumber
	 * @return
	 * @throws Exception
	 */
	@Override
	public Page<BasePartnersInfo> findByBusCodeAndKeyWordForERP(String keyword, Integer statusCode, int pageSize,
			int pageNumber) throws Exception {
	    // 供应商或客户存在一个即过滤
		String businessCode = SystemSession.getUser().getEnterprise().getEnBussinessCode();
		Page<PartnershipRecordView> pageRecords = AccountUtils.getAllRequest(businessCode, statusCode, keyword, pageNumber,
				pageSize);
		Page<BasePartnersInfo> partnerRecords = new Page<>();
		List<PartnershipRecordView> records = pageRecords != null ? pageRecords.getContent() : null;
		List<BasePartnersInfo> baseInfos = new ArrayList<>();
		if (!CollectionUtils.isEmpty(records)) {
			for (PartnershipRecordView record : records) {
				BasePartnersInfo partner = new BasePartnersInfo();
				List<Vendor> vendor;
				List<Vendor> customer;
				// cust为当前企业,发出申请
				if (record.getCustUID().equals(businessCode)) {
					partner.setRequestDate(record.getRequestDate());
					partner.setAppId(record.getAppId());
					partner.setId(record.getId());
					partner.setOperateDate(record.getOperateDate());
					partner.setVendName(record.getVendName());
					partner.setVendUID(record.getVendUID());
					partner.setVendUserCode(String.valueOf(record.getVendUserCode()));
					partner.setVendUserName(record.getVendUserName());
					partner.setVendUserTel(record.getVendUserTel());
					partner.setMethod(Constant.YES);
					partner.setNeedAgreed(Constant.NO);
					if (record.getStatusCode() == 311) {
						partner.setIsTodo(Constant.YES);
					} else {
						partner.setIsTodo(Constant.NO);
					}
					partner.setStatusCode(record.getStatusCode());
					partner.setCustUserName(record.getCustUserName());
					partner.setCustUserTel(record.getCustUserTel());
					partner.setReason(record.getReason());
					// 供应商
					vendor = vendorDao.findByMyEnBusinessCodeAndVendBusinessCode(businessCode, record.getVendUID());
					if (!CollectionUtils.isEmpty(vendor)) {
						// 开关为null时，表示未添加，为0表示关闭，为1表示开启
						partner.setVendor((short) (vendor.get(0).getVendswitch() == null ? 0 : 1));
						partner.setVendorId(vendor.get(0).getId());
						partner.setVendswitch(vendor.get(0).getVendswitch());
						partner.setServicer((short) (vendor.get(0).getServicerswitch() == null ? 0 : 1));
						partner.setServicerswitch(vendor.get(0).getServicerswitch());
					} else {
						partner.setVendor(Constant.NO);
						partner.setServicer(Constant.NO);
					}
					// 客户
					customer = vendorDao.findByMyEnBusinessCodeAndVendBusinessCode(record.getVendUID(), businessCode);
					if (!CollectionUtils.isEmpty(customer)) {
						partner.setCustomer(Constant.YES);
						partner.setCustId(customer.get(0).getId());
						partner.setCustswitch(customer.get(0).getCustswitch());
					} else {
						partner.setCustomer(Constant.NO);
					}
					Enterprise enterprise = enterpriseDao.findEnterpriseByEnBussinessCode(record.getVendUID());
					partner.setEnterprise(enterprise);
					if (null != enterprise && null != enterprise.getEnAdminuu()) {
						UserBaseInfo admin = userBaseInfoDao.findOne(enterprise.getEnAdminuu());
						partner.setContact(admin);
					}
					baseInfos.add(partner);
				}
				// vend为当前企业,收到申请
				if (record.getVendUID().equals(businessCode)) {
					partner.setRequestDate(record.getRequestDate());
					partner.setAppId(record.getAppId());
					partner.setOperateDate(record.getOperateDate());
					partner.setId(record.getId());
					partner.setVendName(record.getCustName());
					partner.setVendUID(record.getCustUID());
					partner.setVendUserCode(String.valueOf(record.getVendUserCode()));
					partner.setVendUserName(record.getVendUserName());
					partner.setVendUserTel(record.getVendUserTel());
					partner.setMethod(Constant.NO);
					partner.setStatusCode(record.getStatusCode());
					if (record.getStatusCode() == 311) {
						partner.setIsTodo(Constant.YES);
						partner.setNeedAgreed(Constant.YES);
					} else {
						partner.setIsTodo(Constant.NO);
						partner.setNeedAgreed(Constant.NO);
					}
					partner.setCustUserName(record.getCustUserName());
					partner.setCustUserTel(record.getCustUserTel());
					partner.setReason(record.getReason());
					// 供应商
					vendor = vendorDao.findByMyEnBusinessCodeAndVendBusinessCode(businessCode, record.getCustUID());
					if (!CollectionUtils.isEmpty(vendor)) {
						partner.setVendor((short) (vendor.get(0).getVendswitch() == null ? 0 : 1));
						partner.setVendorId(vendor.get(0).getId());
						partner.setVendswitch(vendor.get(0).getVendswitch());
						partner.setServicerswitch(vendor.get(0).getServicerswitch());
						partner.setServicer((short) (vendor.get(0).getServicerswitch() == null ? 0 : 1));
					} else {
						partner.setVendor(Constant.NO);
					}
					// 客户
					customer = vendorDao.findByMyEnBusinessCodeAndVendBusinessCode(record.getCustUID(), businessCode);
					if (!CollectionUtils.isEmpty(customer)) {
						partner.setCustomer(Constant.YES);
						partner.setCustId(customer.get(0).getId());
						partner.setCustswitch(customer.get(0).getCustswitch());
					} else {
						partner.setCustomer(Constant.NO);
					}
					Enterprise enterprise = enterpriseDao.findEnterpriseByEnBussinessCode(record.getCustUID());
					partner.setEnterprise(enterprise);
					if (null != enterprise && null != enterprise.getEnAdminuu()) {
						UserBaseInfo admin = userBaseInfoDao.findOne(enterprise.getEnAdminuu());
						partner.setContact(admin);
					}
					baseInfos.add(partner);
				}
			}
		}
		partnerRecords.setContent(baseInfos);
		partnerRecords.setTotalElements(pageRecords != null ? pageRecords.getTotalElements() : 0);
		return partnerRecords;
	}

}
