package com.uas.platform.b2b.listener;

import com.uas.platform.b2b.dao.*;
import com.uas.platform.b2b.event.*;
import com.uas.platform.b2b.mobile.service.MobileReleaseService;
import com.uas.platform.b2b.model.*;
import com.uas.platform.core.model.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 监听新增数据事件
 * 生成对应消息
 */
@Component
public class MessageListener implements ApplicationListener<SaveReleaseEvent<?, ?>> {

    @Autowired
    private PagingReleaseDetailDao pagingReleaseDetailDao;

    @Autowired
    private VendorDao vendorDao;

    @Autowired
    private EnterpriseDao enterpriseDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private DistributeDao distributeDao;

    @Autowired
    private MobileReleaseService mobileReleaseService;

    @SuppressWarnings("unchecked")
    @Async
    @Override
    public void onApplicationEvent(final SaveReleaseEvent<?, ?> event) {
        List<PagingReleaseDetail> pagingReleaseDetails = (List<PagingReleaseDetail>) event.release();
        List<PagingReleaseDetail> otherReleaseDetails = new ArrayList<>(); // 用来保存单据新增的其他消息
        if (event instanceof PurchaseInquiryItemSaveReleaseEvent || event instanceof PurchaseInquiryItemInvalidReleaseEvent || event instanceof PurchaseInquiryItemDecideReleaseEvent) {
            for (PagingReleaseDetail detail : pagingReleaseDetails) {
                Set<Long> userUUs = new HashSet<>(); // 存储需要接收消息的用户UU
                PagingRelease release = detail.getPagingRelease();
                if (null != detail.getVendUU() && null != release.getEnUU()) { // 确保消息有效才继续
                    List<Vendor> vendors;
                    // 判断提前，防止客户方收到过多单据提示消息
                    vendors = vendorDao.findByMyEnUUAndVendUU(release.getEnUU(), detail.getVendUU());
                    // 不添加供应商联系人
                    // 查找被分配客户的业务员
                    if (!CollectionUtils.isEmpty(vendors)) {
                        Long vendorId = vendors.get(0).getId();
                        List<Distribute> distributes = distributeDao.findByVendorId(vendorId);
                        List<Role> roles = roleDao.findByEnUUAndDesc(detail.getVendUU(), "业务员");
                        if (!CollectionUtils.isEmpty(roles) && !CollectionUtils.isEmpty(distributes)) {
                            List<User> salesmans = userDao.findByRole(roles.get(0).getId());
                            Set<Long> salesManUUs = new HashSet<>();
                            for (User salesman : salesmans) {
                                salesManUUs.add(salesman.getUserUU());
                            }
                            for (Distribute distribute : distributes) {
                                if (!userUUs.contains(distribute.getUserUU()) && salesManUUs.contains(distribute.getUserUU())) {
                                    userUUs.add(distribute.getUserUU());
                                }
                            }
                        }
                    }
                    // 新增消息
                    if (!CollectionUtils.isEmpty(userUUs)) {
                        for (Long userUU : userUUs) {
                            try { //去除userUU为空值的情况
                                if (null != userUU) {
                                    User user = userDao.findOne(userUU);
                                    if (null != user) {
                                        PagingReleaseDetail pagingReleaseDetail = new PagingReleaseDetail(detail.getVendUU(), userUU, user.getUserName());
                                        pagingReleaseDetail.setPagingRelease(release);
                                        otherReleaseDetails.add(pagingReleaseDetail);
                                    }
                                }
                            } catch (RuntimeException e) {
                                e.getStackTrace();
                            }
                        }
                    } else {
                        Enterprise vendor = enterpriseDao.findOne(detail.getVendUU());
                        if (null != vendor && null != vendor.getEnAdminuu()) {
                            User admin = userDao.findOne(vendor.getEnAdminuu());
                            PagingReleaseDetail pagingReleaseDetail = new PagingReleaseDetail(detail.getVendUU(), vendor.getEnAdminuu(), admin.getUserName());
                            pagingReleaseDetail.setPagingRelease(release);
                            otherReleaseDetails.add(pagingReleaseDetail);
                        }
                    }
                }
            }
            otherReleaseDetails = pagingReleaseDetailDao.save(otherReleaseDetails);
            if (!CollectionUtils.isEmpty(otherReleaseDetails)) {
                pagingReleaseDetails.addAll(otherReleaseDetails);
            }
            try { // 推送消息
                mobileReleaseService.pushReleases(pagingReleaseDetails);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            for (PagingReleaseDetail detail : pagingReleaseDetails) {
                Set<Long> userUUs = new HashSet<>(); // 存储需要接收消息的用户UU
                PagingRelease release = detail.getPagingRelease();
                if (null != detail.getVendUU() && null != release.getEnUU()) { // 确保消息有效才继续
                    if (release.getToVendor() == Constant.YES) { // 如果是发给供应商的消息，才会管理员和有权限用户都可以收到消息--2017年8月24日 16:12:05加，避免客户方用户收到太多消息
                        List<Vendor> vendors;
                        // 判断提前，防止客户方收到过多单据提示消息
                        vendors = vendorDao.findByMyEnUUAndVendUU(release.getEnUU(), detail.getVendUU());
                        // 查找有权限的用户
                        if (!CollectionUtils.isEmpty(vendors)) {
                            Long vendorId = vendors.get(0).getId();
                            List<Distribute> distributes = distributeDao.findByVendorId(vendorId);
                            if (!CollectionUtils.isEmpty(distributes)) {
                                // 找出当前企业拥有管理员权限的角色
                                List<Role> roles = roleDao.findByEnUUAndIssys(detail.getVendUU(), Constant.YES);
                                Set<Long> adminUUs = new HashSet<>();
                                if (!CollectionUtils.isEmpty(roles)) {
                                    List<User> admins = userDao.findByRole(roles.get(0).getId());
                                    for (User admin : admins) {
                                        adminUUs.add(admin.getUserUU());
                                    }
                                }
                                // 被分配客户的，且不是管理员的用户才接收消息
                                for (Distribute distribute : distributes) {
                                    if (!userUUs.contains(distribute.getUserUU()) && !adminUUs.contains(distribute.getUserUU())) {
                                        userUUs.add(distribute.getUserUU());
                                    }
                                }
                            }
                        }
                        // 新增消息
                        for (Long userUU : userUUs) {
                            try { //去除userUU为空值的情况
                                if (null != userUU) {
                                    User user = userDao.findOne(userUU);
                                    if (null != user) {
                                        PagingReleaseDetail pagingReleaseDetail = new PagingReleaseDetail(detail.getVendUU(), userUU, user.getUserName());
                                        pagingReleaseDetail.setPagingRelease(release);
                                        otherReleaseDetails.add(pagingReleaseDetail);
                                    }
                                }
                            } catch (RuntimeException e) {
                                e.getStackTrace();
                            }
                        }
                    } else { // 发送给客户方的，直接添加消息到保存列表
                        otherReleaseDetails.add(detail);
                    }
                }
            }
            otherReleaseDetails = pagingReleaseDetailDao.save(otherReleaseDetails);
            if (!CollectionUtils.isEmpty(otherReleaseDetails)) {
                pagingReleaseDetails.addAll(otherReleaseDetails);
            }
            try { // 推送消息
                mobileReleaseService.pushReleases(pagingReleaseDetails);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
