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

import com.uas.message.mail.service.MailService;
import com.uas.platform.b2b.core.util.ThreadUtils;
import com.uas.platform.b2b.dao.EnterpriseDao;
import com.uas.platform.b2b.dao.InvitationRecordDao;
import com.uas.platform.b2b.dao.ProductDao;
import com.uas.platform.b2b.dao.UserDao;
import com.uas.platform.b2b.model.Enterprise;
import com.uas.platform.b2b.model.InvitationRecord;
import com.uas.platform.b2b.model.User;
import com.uas.platform.b2b.search.SearchService;
import com.uas.platform.b2b.service.InvitationRecordService;
import com.uas.platform.b2b.support.MessageConf;
import com.uas.platform.b2b.support.SendMsgUtils;
import com.uas.platform.b2b.support.SysConf;
import com.uas.platform.b2b.support.SystemSession;
import com.uas.platform.core.model.Constant;
import com.uas.platform.core.util.serializer.FlexJsonUtils;
import com.uas.search.b2b.model.PageParams;
import com.uas.search.b2b.model.SPage;
import com.uas.sso.util.AccountUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class InvitationRecordServiceImpl implements InvitationRecordService {

	@Autowired
	private InvitationRecordDao invitationRecordDao;

	@Autowired
	private MailService mailService;

	@Autowired
	private MessageConf messageConf;

	@Autowired
	private SearchService searchService;

	@Autowired
	private EnterpriseDao enterpriseDao;

	@Autowired
	private UserDao userDao;

	@Autowired
    private ProductDao productDao;

	@Autowired
    private SysConf sysConf;

    /**
     * 企业注册标志
     */
    final String spaceRegisterSign = "enterpriseRegistration";

	@Override
	public ModelMap invite(InvitationRecord record) {
		ModelMap map = new ModelMap();
		List<Enterprise> enterprises = enterpriseDao.findByEnName(record.getVendname());
		if (!CollectionUtils.isEmpty(enterprises)) {
			map.put("error", "该企业已注册！");
			return map;
		}
		Long useruu = SystemSession.getUser().getUserUU();
		Long enuu = SystemSession.getUser().getEnterprise().getUu();
		// UAS邀请注册通过Systemsession获取的用户UU不是当前用户UU，所以参数传过来
		if (record.getUseruu() != null) { // 用户存在才设置进去，不然数据库会报错
			User erpUser = userDao.findOne(record.getUseruu());
			if (erpUser != null) {
				useruu = record.getUseruu();
			}
		}
		if (record.getEnuu() != null) { // 企业信息也一样
			Enterprise enterprise = enterpriseDao.findOne(record.getEnuu());
			if (enterprise != null) {
				enuu = record.getEnuu();
			}
		}
		// 先判断记录
		InvitationRecord oldrecord = invitationRecordDao.findByUseruuAndVendname(useruu, record.getVendname());
			if (record.getId() != null) { // 如果是已存在的，直接替换
			oldrecord = invitationRecordDao.findOne(record.getId());
		}
		if (oldrecord != null) {
			oldrecord.setCount(oldrecord.getCount() + 1);
			oldrecord.setDate(new Date());
			if (record.getVendname() != null) {
				oldrecord.setVendname(record.getVendname());
			}
			if (record.getVendusername() != null) {
				oldrecord.setVendusername(record.getVendusername());
			}
			if (record.getVendusertel() != null) {
				oldrecord.setVendusertel(record.getVendusertel().trim());
			}
			if (record.getVenduseremail() != null) {
				oldrecord.setVenduseremail(record.getVenduseremail().trim());
			}
			record = invitationRecordDao.save(oldrecord);
			if (oldrecord.getVenduseremail() != null) {
			    sendEmail(record);
			}
			if (oldrecord.getVendusertel() != null) {
				sendMsg(record);
			}
			map.put("success", "邀请已发送");
		} else {
			record.setCount(1);
			record.setEnuu(enuu);
			record.setUseruu(useruu);
			record.setDate(new Date());
			record.setActive(Constant.NO);
			record = invitationRecordDao.save(record);
			if (record.getVenduseremail() != null) {
				sendEmail(record);
			}
			if (record.getVendusertel() != null) {
				sendMsg(record);
			}
			if (record.getId() != null) {
				map.put("success", "邀请已发送");
			} else {
				map.put("error", "邀请发送失败");
			}
		}
        syncToAccount(record, SystemSession.getUser().getEnterprise().getEnBussinessCode());
        return map;
	}

    /**
     * 同步到账户中心
     *
     * @param record 邀请记录
     * @param businessCode 营业执照
     */
    @Override
    public void syncToAccount(final InvitationRecord record, final String businessCode) {
        // 同步一个数据到账户中心（不是必须，不判断状态）
        ThreadUtils.task(new Runnable() {
            @Override
            public void run() {
                try {
                    record.setUser(null);
                    record.setId(null);
                    record.setSamecount(null);
                    record.setVenduu(null);
                    record.setBussinesscode(businessCode);
                    AccountUtils.synchroInvitation(FlexJsonUtils.toJsonDeep(record));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).run();
    }

    /**
     * 发送短信通知
     *
     * @param record 邀请记录
     */
    private void sendMsg(InvitationRecord record) {
    	String[] args = {record.getVendusername(), record.getVendname(), SystemSession.getUser().getUserName() + "("
				+ SystemSession.getUser().getEnterprise().getEnName() + ")"};
		SendMsgUtils.sendMsg(record.getVendusertel(), messageConf.getMsgAddPartForB2B(), args);
    }


    /**
     * 发送邮件通知
     *
     * @param record 邀请记录
     */
    @Override
    public void sendEmail(final InvitationRecord record) {
        Map<String, Object> model = new HashMap<String, Object>();
        // 邮件信息
        if (null != record.getVendusername()) {
            model.put("vendorusername", record.getVendusername().trim());
        }
        Enterprise e = enterpriseDao.findOne(record.getEnuu());
        User u = userDao.findOne(record.getUseruu());
        model.put("vendorname", record.getVendname().trim());
        model.put("custname", u.getUserName() + "(" + e.getEnName() + ")");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String time = sdf.format(new Date());
        String url = sysConf.getRegisterUrl();
        if (url.contains(spaceRegisterSign)) {
            url = url + "?inviteUserUU=" + record.getUseruu() + "&inviteSpaceUU=" + record.getEnuu()
                    + "&invitationTime=" + time + "&source=" + record.getSource();
        } else {
            url = url + "/enterpriseRegistration?inviteUserUU=" + record.getUseruu() + "&inviteSpaceUU=" + record.getEnuu()
                    + "&invitationTime=" + time + "&source=" + record.getSource();
        }
        model.put("registerUrl", url);
        final Map<String, Object> modMap = model;
        ThreadUtils.task(new Runnable() {
            @Override
            public void run() {
                try {
                    mailService.send(messageConf.getTplInvitationForB2B(), record.getVenduseremail(), modMap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).run();
    }

	@Override
	public SPage<InvitationRecord> getRecords(PageParams params, String keyword) {
		SPage<InvitationRecord> invitatrecords = new SPage<InvitationRecord>();
		try {
			invitatrecords = searchService.getInvitationByKeyword(keyword, params);
		} catch (Exception e) {
		}
		if (!CollectionUtils.isEmpty(invitatrecords.getContent())) {
            for (InvitationRecord record : invitatrecords.getContent()) {
            	if (null != record.getVenduu()) {
            		Enterprise e = enterpriseDao.findOne(record.getVenduu());
					covert(record, e);
				} else {
					List<Enterprise> enters = enterpriseDao.findByEnName(record.getVendname());
					if (!CollectionUtils.isEmpty(enters)) {
						if (enters.size() == 1) {
							Enterprise e = enters.get(0);
							record.setActive(Constant.YES);
							record.setSamecount(enters.size());
							record.setVenduu(e.getUu());
							record = covert(record, e);
						} else {
							record.setActive(Constant.NO);
							record.setSamecount(enters.size());
						}
					} else {
						record.setActive(Constant.NO);
						record.setSamecount(enters.size());
					}
					invitationRecordDao.save(record);
				}
            }
        }
		return invitatrecords;
	}

    /**
     * 将企业信息封装到邀请记录
     *
     * @param record 邀请记录
     * @param e 企业信息
     * @return
     */
    private InvitationRecord covert(InvitationRecord record, Enterprise e) {
        record.setProductNum(productDao.countByEnUU(record.getVenduu()));
        if (null != e.getInviteUU()) {
            Enterprise inviteEn = enterpriseDao.findOne(e.getInviteUU());
            record.setInviteEnName(inviteEn != null ? inviteEn.getEnName() : null);
        }
        if (null != e.getInviteUserUU()) {
            User inviteUser = userDao.findOne(e.getInviteUserUU());
            record.setInviteUserName(inviteUser != null ? inviteUser.getUserName() : null);
        }
        record.setRegisterDate(e.getEnDate());
        record.setEnAddress(e.getEnAddress());
        record.setEnCorporation(e.getEnCorporation());
        if (null != e.getEnAdminuu()) {
            User admin = userDao.findOne(e.getEnAdminuu());
            if (null != admin) {
                record.setAdminName(admin.getUserName());
            }
        }
        return record;
    }

    /**
     * 通过注册UU号查询邀请记录
     *
     * @param enuu 注册UU号
     * @return
     */
    @Override
    public List<InvitationRecord> findByVendUU(Long enuu) {
        return invitationRecordDao.findByVenduu(enuu);
    }
}
