package com.sys.service;

import com.cab.dao.CabMymessageMapper;
import com.cab.dao.UserMapper;
import com.cab.model.CabMymessage;
import com.cab.model.User;
import com.cku.core.PageBeanResult;
import com.cku.jpush.JpushExtras;
import com.cku.jpush.JpushNotification;
import com.cku.jpush.PushUtils;
import com.cku.util.PageBean;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by user on 2016/5/30.
 */
@Service("messageService")
public class MessageServiceImpl {
    private static Logger logger = Logger.getLogger(MessageServiceImpl.class);
    @Autowired
    private CabMymessageMapper cabMymessageMapper;
    @Autowired
    private UserMapper userMapper;

    public PageBeanResult<CabMymessage> getList(Integer type, String title, PageBean pb){
        PageBeanResult<CabMymessage> result = new PageBeanResult<CabMymessage>();

        List<CabMymessage> list = cabMymessageMapper.getList(type,title,pb.get_start(),pb.get_limit());
        Long count = cabMymessageMapper.getCount(type,title);
        result.setList(list);
        result.setTotalCount(count);
        return result;
    }
    public CabMymessage getMessageById(Integer id){

        return cabMymessageMapper.selectByPrimaryKey(id);
    }

    public int deleteMessage(Integer id){
        return cabMymessageMapper.deleteByPrimaryKey(id);
    }

    @Transactional
    public int changeStatus(Integer id){
        int i = 0;
        try {
            CabMymessage cabMymessage = cabMymessageMapper.selectByPrimaryKey(id);
            final List<CabMymessage> insertList = new ArrayList<CabMymessage>();
            cabMymessage.setStatus(1);
            i = cabMymessageMapper.updateByPrimaryKeySelective(cabMymessage);
            List<User> list = userMapper.selectAll();
            for(User u : list){
                cabMymessage.setUserId(u.getId());
                insertList.add(cabMymessage.clone());
            }
            cabMymessageMapper.insertUserMessage(insertList);
            JpushNotification notification = new JpushNotification(cabMymessage.getContent(),"宠爱王国",null);
            PushUtils.push_all_notification(notification);
        } catch (Exception e) {
            logger.error(e);
        }
        return i;
    };
    public int addMessage(Integer sysUserId,CabMymessage message){
        message.setCreateTime(new Date());
        message.setSysUserId(sysUserId);
        message.setStatus(0);
        return cabMymessageMapper.insertSelective(message);
    }
    public int updateMessage(Integer sysUserId,CabMymessage message){
        message.setSysUserId(sysUserId);
        return cabMymessageMapper.updateByPrimaryKeySelective(message);
    }
}
