package com.house365.ws.service.impl;

import com.house365.beans.entity.CustomerRemindEntity;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.dao.mapper.CustomerRemindMapper;
import com.house365.ws.service.interfaces.ISendWeChatMsgService;
import com.house365.ws.service.interfaces.IWechatService;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Created by Administrator on 2019/5/27.
 */
@Service("sendWeChatTask")
public class SendWeChatMsgImpl implements ISendWeChatMsgService {

    private static final Logger logger = LoggerFactory.getLogger(SendWeChatMsgImpl.class);

    @Autowired
    private CustomerRemindMapper remindMapper;

    @Autowired
    private IWechatService service;

    private final String wxUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("WECHAT.SERVICE.URL");

    @Autowired
    private RedisUtilsInterface redisUtil;

    @Override
    public void sendWeChatMsg() {
        try {
            //通过redis查询key来实现只在一台机器上执行
            String key = "wxPut_job";
            String value = "wxPutValue";
            long seconds = 100;
            if (redisUtil.setNX(key, value, seconds)) {
                Map<String, Object> map = new HashMap<>(10);
                map.put("returnRemindTime", "11");
                List<CustomerRemindEntity> list = remindMapper.queryByConditions(map);
                if (CollectionUtils.isNotEmpty(list)) {
                    logger.info("size : " + list.size());
                    for (CustomerRemindEntity entity : list) {
                        String userId = String.valueOf(entity.getCreateUserId());
                        String name = entity.getCustomerName();
                        String title = "跟进提醒";
                        String description = "您的客户【" + name + "】需要跟进了，请及时更进";
                        String url = wxUrl + "/customer/customerdetail?customerId=" + entity.getCustomerId();
                        String btnTxt = "查看详情";
                        service.sendCardTextMessage(userId, title, description, url, btnTxt);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("定时发送wx提醒失败", e);
        }
    }
}
