/**
 * Description: 抢客规则业务实现类
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-11-28 下午 13:41:47
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-11-28   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.service.impl;

import com.house365.beans.common.MessageTypeEnum;
import com.house365.beans.entity.RushCustomerEntity;
import com.house365.beans.entity.RushCustomerPushLogEntity;
import com.house365.beans.entity.RushCustomerRuleEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.QueryParams;
import com.house365.dao.system.interfaces.Dao;
import com.house365.service.system.impl.DefaultServiceImpl;
import com.house365.web.util.DateTimeUtils;
import com.house365.ws.dao.impl.UserDaoImpl;
import com.house365.ws.dao.interfaces.IRushCustomerRuleDao;
import com.house365.ws.service.interfaces.ICustomerService;
import com.house365.ws.service.interfaces.IRushCustomerPushLogService;
import com.house365.ws.service.interfaces.IRushCustomerRuleService;
import com.house365.ws.service.interfaces.IRushCustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 抢客规则业务实现类<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-11-28
 * @see
 * @since 1.0
 */
@Service("rushCustomerRuleService")
public class RushCustomerRuleServiceImpl<T extends RushCustomerRuleEntity> extends DefaultServiceImpl<T> implements IRushCustomerRuleService<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger(RushCustomerRuleServiceImpl.class);
    @Autowired
    IRushCustomerService<RushCustomerEntity> rushCustomerService;
    @Autowired
    IRushCustomerPushLogService pushLogService;
    @Autowired
    ICustomerService customerService;
    /**
     * 自动注入的数据访问对象
     */
    @Autowired
    private IRushCustomerRuleDao<T> rushCustomerRuleDao;
    @Autowired
    private UserDaoImpl userDao;

    @Override
    protected Dao<T> getDao() {
        return rushCustomerRuleDao;
    }

    @Override
    public List<RushCustomerRuleEntity> getActiveRules(Integer userId) {
        UserEntity userEntity = userDao.getById(userId);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        long whichDay = calendar.get(Calendar.DAY_OF_WEEK);


        Map<String, Object> ruleMap = new HashMap<>();
        //首尾匹配 类似于正则的\b
        ruleMap.put("REGEXP_department", "[[:<:]]" + userEntity.getDeptId() + "[[:>:]]");
        ruleMap.put("EQ_status", 1);//启用状态
        ruleMap.put("REGEXP_activeTime", "[[:<:]]" + whichDay + "[[:>:]]");//启用状态
        QueryParams<RushCustomerRuleEntity> ruleQueryParams = new QueryParams<>(ruleMap);
        return (List<RushCustomerRuleEntity>) rushCustomerRuleDao.queryAll(ruleQueryParams);
    }

    @Override
    public void pushRushCustomer() {
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        calendar.setTime(new Date());
        long whichDay = calendar.get(Calendar.DAY_OF_WEEK);


        Map<String, Object> ruleMap = new HashMap<>();
        //首尾匹配 类似于正则的\b
        ruleMap.put("EQ_status", 1);//启用状态
        ruleMap.put("REGEXP_activeTime", "[[:<:]]" + whichDay + "[[:>:]]");//启用状态
        QueryParams<RushCustomerRuleEntity> ruleQueryParams = new QueryParams<>(ruleMap);
        List<RushCustomerRuleEntity> rules = (List<RushCustomerRuleEntity>) rushCustomerRuleDao.queryAll(ruleQueryParams);

        // 时间过滤 半小时推送一次
        int minute = Integer.valueOf(DateTimeUtils.parseDate(calendar.getTime(), "mm"));
        String startTime = "";
        String endTime = "";
        if (minute >= 30) {
            endTime = DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:30:00");
            startTime = DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:00:00");
        } else {
            endTime = DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:00:00");
            calendar.add(Calendar.HOUR, -1);
            startTime = DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:30:00");
        }
        List<String> actIds = new ArrayList<>();
        List<String> projectIds = new ArrayList<>();
        for (RushCustomerRuleEntity rule : rules) {
            try {
                //获取该规则匹配的半小时内的客户数量
                Set<String> actIdsSet = new HashSet<>();
                Set<String> projectIdsSet = new HashSet<>();
                String[] ruleActIds = rule.getSource().split(",");
                String[] ruleProjectIds = rule.getProject().split(",");
                Collections.addAll(actIdsSet, ruleActIds);
                Collections.addAll(projectIdsSet, ruleProjectIds);
                Map<String, Object> searchParams = new HashMap<>();
                actIds.clear();
                actIds.addAll(actIdsSet);
                projectIds.clear();
                projectIds.addAll(projectIdsSet);
                searchParams.put("EQ_actIds", actIds);
                searchParams.put("EQ_projectIds", projectIds);
                searchParams.put("EQ_rushStatus", 0);
                searchParams.put("GTE_createTimeStart", startTime);
                searchParams.put("LTE_createTimeEnd", endTime);
                QueryParams<RushCustomerEntity> queryParams = new QueryParams<>(searchParams);
                List<RushCustomerEntity> rushCustomers = rushCustomerService.queryAll(queryParams);
                int rushCustomerCount = rushCustomers.size();
                //如果客户数量为零，则不推送
                if (rushCustomerCount == 0) {
                    continue;
                }
                //将客户数量推送给规则对应部门下所有的员工
                String[] departmentIds = rule.getDepartment().split(",");
                for (String departmentId : departmentIds) {
                    try {
                        //保存推送记录
                        for (RushCustomerEntity rushCustomer : rushCustomers) {
                            try {
                                RushCustomerPushLogEntity pushLog = new RushCustomerPushLogEntity();
                                pushLog.setRushCustomerId(rushCustomer.getId());
                                pushLog.setDepartmentId(Integer.valueOf(departmentId));
                                pushLog.setRushCustomerRuleId(rule.getId());
                                pushLog.setCrmSource(rule.getSource());
                                pushLog.setProject(rule.getProject());
                                pushLog.setCreateTime(new Date());
                                pushLogService.save(pushLog);
                            } catch (Exception e) {
                                LOGGER.error("保存抢客客户推送记录失败,抢客客户id[{}],规则id[{}],部门id[{}]",
                                        rushCustomer.getId(), rule.getId(), departmentId);
                            }
                        }
                        Map<String, Object> userSearchParams = new HashMap<>();
                        userSearchParams.put("EQ_deptId", departmentId);
                        QueryParams<RushCustomerEntity> userQueryParams = new QueryParams<>(userSearchParams);

                        List<UserEntity> users = userDao.queryAll(userQueryParams);
                        //向微信的每个会员推送抢客信息
                        for (UserEntity user : users) {
                            try {
                                LOGGER.debug("会员名[{}],会员id[{}],在过去的30分钟里，有[{}]个客户正在关注你负责的项目",
                                        user.getRealName(), user.getId(), rushCustomerCount);

                                Map<String, String> param = new HashMap<>();
                                param.put("rushCustomerCount", String.valueOf(rushCustomerCount));
                                customerService.sendMessageToWechat(MessageTypeEnum.RUSHCUSTOMER, String.valueOf(user.getId()), param);
                            } catch (Exception e) {
                                LOGGER.error("推送抢客客户信息失败,会员名[{}],会员id[{}],推送数量[{}]", user.getRealName(),
                                        user.getId(), rushCustomerCount);
                            }

                        }
                    } catch (Exception e) {
                        LOGGER.error("推送抢客信息至部门失败,规则id[{}],部门id[{}]", rule.getId(), departmentId);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("处理抢客规则失败,规则id[{}]", rule.getId());
            }
        }
    }
}