package com.ifish.serviceImpl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.ifish.dao.UserActivityDao;
import com.ifish.dao.UserDao;
import com.ifish.entity.User;
import com.ifish.entity.UserActivity;
import com.ifish.enums.ActivityTypeEnum;
import com.ifish.netease.NeteaseIM;
import com.ifish.service.AsyncTaskService;
import com.ifish.util.IfishFilePath;
import java.util.Date;

/**
 * 异步执行任务service
 *
 * @author Administrator
 *
 */
@Service
@Async
@Transactional
public class AsyncTaskServiceImpl implements AsyncTaskService {
    
    @Autowired
    private UserDao userDao;
    @Autowired
    private NeteaseIM neteaseIM;
    @Autowired
    private UserActivityDao userActivityDao;

    /**
     * 分享爱鱼看看后给所有用户发送云信消息
     */
    @Override
    public void sendMsgToAll(Integer userId) {
        Integer firstResult = 0;
        Integer maxResults = 500;
        User user = userDao.get(userId);
        if (user != null) {
            String content = user.getNickName() + "刚在爱鱼看看分享了TA的爱鱼,快去瞅瞅~";
            while (true) {
                List<Integer> list = userDao.getUserIds(userId, firstResult, maxResults);
                Integer size = list.size();
                if (size <= 0) {
                    break;
                } else {
                    firstResult += size;
                    //批量发送
                    neteaseIM.sendBatchMsg(IfishFilePath.ifish_account, JSONArray.toJSONString(list), content);
                    //云信接口有访问限制，延迟600毫秒发送
                    try {
                        Thread.sleep(600);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 给商家和用户发送消息
     */
    @Override
    public void sendMsgToShopsUser(Integer userId, Integer shopsUserId, String nickName) {
        //爱鱼奇消息主手给商家发送消息
        String msg1 = "恭喜你，" + nickName + "已成为你的会员，快去会员管理中看看吧~";
        neteaseIM.sendMsg(IfishFilePath.ifish_account, shopsUserId.toString(), msg1, null);
        //商家发送消息给用户
        String msg2 = "恭喜你成为本店会员，有什么疑问，都可以随时联系我。";
        neteaseIM.sendMsg(shopsUserId.toString(), userId.toString(), msg2, null);
    }

    /**
     * 新增用户动态
     *
     * @param userId
     * @param activityType
     */
    @Override
    public void saveUserActivity(Integer userId, String activityType) {
        //是否有这个动态类型
        if (ActivityTypeEnum.getValueByKey(activityType)) {
            UserActivity activity = new UserActivity();
            activity.setUserId(userId);
            activity.setActivityType(activityType);
            activity.setCreateTime(new Date());
            userActivityDao.save(activity);
        }
    }
    
}
