/**
 * Description: 抢客WS接口
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-12-05 上午 09:44:17
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-12-05   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.RushCustomerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.RushCustomerListRequest;
import com.house365.ws.beans.request.RushCustomerRequest;
import com.house365.ws.beans.response.RushCustomerListResponse;
import com.house365.ws.beans.response.RushCustomerResponse;
import com.house365.ws.interfaces.server.IRushCustomer;
import com.house365.ws.service.interfaces.*;
import com.house365.ws.system.ReturnResult;
import com.house365.ws.util.Constant;
import com.house365.ws.util.OperateLogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.house365.beans.common.MessageTypeEnum.NEWCUSTOMER;


/**
 * 抢客WS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-12-05
 * @see
 * @since 1.0
 */
@Service("rushCustomer")
public class RushCustomerImpl implements IRushCustomer {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(RushCustomerImpl.class);

    /**
     * 抢客服务对象
     */
    @Autowired
    IRushCustomerService<RushCustomerEntity> rushCustomerService;
    @Autowired
    ICustomerService<CustomerEntity> customerService;
    @Autowired
    IUserService userService;
    @Autowired
    private ICustomerSourceService customerSourceService;
    @Autowired
    private IHgsCacheUtil hgsCacheUtil;
    @Autowired
    private OperateLogUtils logUtils;

    /**
     * 抢客列表查询
     *
     * @param request 抢客列表查询请求
     * @return 抢客列表查询响应
     */
    @Override
    public RushCustomerListResponse getRushCustomerList(RushCustomerListRequest request) {
        RushCustomerListResponse response = new RushCustomerListResponse();
        try {
            QueryParams<RushCustomerEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            List<RushCustomerEntity> rushCustomers = rushCustomerService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(rushCustomers);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 保存抢客
     *
     * @param request 抢客请求
     * @return 保存抢客响应
     */
    @Override
    public RushCustomerResponse addRushCustomer(RushCustomerRequest request) {
        RushCustomerResponse response = new RushCustomerResponse();
        try {
            RushCustomerEntity entity = request.getEntity();
            rushCustomerService.save(entity);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除抢客通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除抢客响应
     */
    @Override
    public RushCustomerResponse deleteRushCustomerById(Integer id) {
        RushCustomerResponse response = new RushCustomerResponse();
        try {
            RushCustomerEntity rushCustomerEntity = rushCustomerService.getById(id);
            rushCustomerEntity.setIsDeleted(1);
            rushCustomerService.update(rushCustomerEntity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改抢客
     *
     * @param request 修改抢客请求
     * @return 修改抢客响应
     */
    @Override
    public RushCustomerResponse updateRushCustomer(RushCustomerRequest request) {
        RushCustomerResponse response = new RushCustomerResponse();
        try {
            rushCustomerService.update(request.getEntity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 通过ID获取抢客
     *
     * @param id 唯一标识
     * @return 通过ID获取抢客响应
     */
    @Override
    public RushCustomerResponse getRushCustomerById(Integer id) {
        RushCustomerResponse response = new RushCustomerResponse();
        try {
            RushCustomerEntity entity = rushCustomerService.getById(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 派工
     *
     * @param rushCustomerIds
     * @param userId
     * @throws Exception
     */
    @Override
    public void bindUser(String[] rushCustomerIds, Integer userId, Integer operId, String userName) throws Exception {
        if (rushCustomerIds != null && userId != null) {
            hgsCacheUtil.delUserSummary(userId);
            UserEntity user = (UserEntity) userService.getById(userId);
            if (user != null) {
                for (String rushCustomerId : rushCustomerIds) {
                    RushCustomerEntity rushCustomer = rushCustomerService.getById(Integer.valueOf(rushCustomerId));

                    //客户信息入客户表
                    CustomerEntity customerEntity = new CustomerEntity();

                    Map<String, Object> map = new HashMap<>(10);
                    map.put("EQ_customerRelId", rushCustomerId);
                    QueryParams<CustomerEntity> queryParams = new QueryParams<>(map);
                    List<CustomerEntity> customerEntities = customerService.queryAll(queryParams);
                    if (customerEntities != null && customerEntities.size() != 0) {
                        customerEntity = customerEntities.get(0);

                        customerEntity.setManagerId(userId);
                        customerEntity.setIsRecycled(0);
                        customerEntity.setManagerName(user.getRealName());
                        customerEntity.setUpdateTime(new Date());
                        customerEntity.setUpdater(String.valueOf(operId));
                        //重置客户绑定置业顾问时间
                        customerEntity.setBindTime(new Date());
                        customerService.update(customerEntity);
                    } else {
                        //更新来源
                        Integer sourceId = customerSourceService.updateSource(customerEntity.getCityCode(),
                                customerEntity.getActSource(),
                                customerEntity.getCreateSource(), "CRM");
                        customerEntity.setActSourceId(sourceId);

                        customerEntity.setName(rushCustomer.getName());
                        customerEntity.setPhone(rushCustomer.getPhone());
                        customerEntity.setCityCode(rushCustomer.getCityCode());
                        customerEntity.setCityName(rushCustomer.getCityName());
                        customerEntity.setCrmId(rushCustomer.getCrmId());
                        customerEntity.setSex(rushCustomer.getSex());
                        customerEntity.setBizPort(rushCustomer.getBizPort());
                        customerEntity.setActSource(rushCustomer.getActSource());
                        customerEntity.setFirstSource(rushCustomer.getFirstSource());
                        customerEntity.setCreateSource(rushCustomer.getCreateSource());
                        customerEntity.setCustomerType(rushCustomer.getCustomerType());
                        customerEntity.setLatestSource(rushCustomer.getLatestSource());
                        customerEntity.setCrmLatestCall(rushCustomer.getCrmLatestCall());
                        customerEntity.setCrmLatestCallResult(rushCustomer.getCrmLatestCallResult());
                        customerEntity.setCreateTime(rushCustomer.getCreateTime());
                        customerEntity.setCreater(rushCustomer.getCreater());
                        customerEntity.setUpdater(user.getName());
                        customerEntity.setUpdateTime(new Date());
                        customerEntity.setStatus(Constant.CustomerStatusEnum.NORECORD.getStatus());
                        customerEntity.setBuyIntention(rushCustomer.getBuyIntention());
                        customerEntity.setCustomerSourceType(2);
                        customerEntity.setCustomerRelId(rushCustomer.getId());
                        customerEntity.setTraceStatus(0);
                        //数据公海中客户购房意向为“无效”的客户，如果被派工后，统一提升客户的“购房意向”为：待定
                        customerEntity.setBuyIntention("");
                        customerEntity.setIsDelete(0);

                        customerEntity.setManagerId(userId);
                        customerEntity.setIsRecycled(0);
                        customerEntity.setManagerName(user.getRealName());
                        customerEntity.setUpdateTime(new Date());
                        customerEntity.setUpdater(String.valueOf(operId));
                        //重置客户绑定置业顾问时间
                        customerEntity.setBindTime(new Date());
                        customerService.save(customerEntity);
                        //记录客户新增日志（抢客数据公海活动派工）
                        logUtils.saveCustomerLog(customerEntity, 9, operId, userName);
                    }

                    //保存客户被抢信息
                    rushCustomer.setManagerId(user.getId());
                    rushCustomer.setManagerName(user.getName());
                    rushCustomer.setRushStatus(1);
                    rushCustomer.setUpdateTime(new Date());
                    rushCustomerService.update(rushCustomer);

                    Map<String, String> param = new HashMap<>(10);
                    param.put("customerId", customerEntity.getId().toString());
                    customerService.sendMessageToWechat(NEWCUSTOMER, String.valueOf(user.getId()), param);

                }
            }
        }
    }

    @Override
    public RushCustomerListResponse getRushCustomerList(String timeType, String startTime, String endTime,
                                                        String type, String phone, Integer userId,
                                                        String city, Integer number) {
        RushCustomerListResponse response = new RushCustomerListResponse();
        try {
            Map<String, Object> searchParams = new HashMap<>();
            Page page = new Page();
            if (null != number) {
                page.setCurrentPage(number);
            }
            page.setPageSize(50);

            filterParam(timeType, startTime, endTime, type, phone, userId, city, searchParams);

            QueryParams<RushCustomerEntity> queryParams = new QueryParams<>(searchParams);
            queryParams.setPaging(page);
            queryParams.setOrderColumn("create_time");
            queryParams.setOrderMode("desc");
            List<RushCustomerEntity> rushCustomers = rushCustomerService.queryAllShow(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(rushCustomers);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    private void filterParam(String timeType, String startTime, String endTime, String type, String phone, Integer userId,
                             String city, Map<String, Object> searchParams) {
        UserEntity user = (UserEntity) userService.getById(userId);
        if (StringUtils.isNotBlank(phone)) {
            searchParams.put("LIKE_filterName", phone);
        }
        searchParams.put("EQ_isDeleted", 0);
        searchParams.put("EQ_type" + type, type);
        searchParams.put("EQ_cityCode", city);
        if (!"2".equals(type)) {
            searchParams.put("REGEXP_urlPath", "^" + user.getDeptUrlPath() + "$|^" + user.getDeptUrlPath() + "/");
        }
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        calendar.setTime(new Date());
        // 时间过滤 半小时推送一次
        int minute = Integer.valueOf(DateTimeUtils.parseDate(calendar.getTime(), "mm"));
        if (!Strings.isNullOrEmpty(endTime)) {
            if (minute >= 30) {
                searchParams.put("LTE_createTimeEnd", endTime + " " + DateTimeUtils.parseDate(calendar.getTime(), "HH:30:00"));
            } else {
                searchParams.put("LTE_createTimeEnd", endTime + " " + DateTimeUtils.parseDate(calendar.getTime(), "HH:00:00"));
            }
        } else {
            if (minute >= 30) {
                searchParams.put("LTE_createTimeEnd", DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:30:00"));
            } else {
                searchParams.put("LTE_createTimeEnd", DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd HH:00:00"));
            }
        }

        if (StringUtils.isNotBlank(timeType) && !"1".equals(timeType)) {

            if (!Strings.isNullOrEmpty(startTime)) {
                searchParams.put("GTE_createTimeStart", startTime + " 00:00:00");
            } else {
                if ("2".equals(timeType)) {
                    calendar.add(Calendar.DATE, -1);
                } else if ("3".equals(timeType)) {
                    calendar.add(Calendar.DATE, -7);
                }
                searchParams.put("GTE_createTimeStart",
                        DateTimeUtils.parseDate(calendar.getTime(), "yyyy-MM-dd 00:00:00"));
            }

        }
    }

    @Override
    public Map<String, Object> getRushCustomerCounts(String timeType, String startTime, String endTime,
                                                     Integer userId, String city, String phone) {
        Map<String, Object> result = new HashMap<>();

        String[] types = {"0", "1", "2"};
        for (String type : types) {
            Map<String, Object> searchParams = new HashMap<>();
            filterParam(timeType, startTime, endTime, type, phone, userId, city, searchParams);

            QueryParams<RushCustomerEntity> queryParams = new QueryParams<>(searchParams);
            int count = rushCustomerService.queryAllShowCount(queryParams);
            result.put("type" + type, count);
        }
        return result;
    }

    /**
     * 以下均为自动生成
     */

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {
    }
}
