/**
 * Description: CustomerCallbackLogWS接口
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-15 下午 15:36:17
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-15   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.house365.beans.common.HGSConstant;
import com.house365.beans.entity.CustomerCallbackLogEntity;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.LabelEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.QueryParams;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.ws.beans.request.CustomerCallbackLogListRequest;
import com.house365.ws.beans.request.CustomerCallbackLogRequest;
import com.house365.ws.beans.request.CustomerRequest;
import com.house365.ws.beans.response.CustomerCallbackLogListResponse;
import com.house365.ws.beans.response.CustomerCallbackLogResponse;
import com.house365.ws.dao.interfaces.ICustomerDao;
import com.house365.ws.dao.interfaces.IUserDao;
import com.house365.ws.dao.mapper.CustomerCallbackMapper;
import com.house365.ws.dao.mapper.CustomerMergeMapper;
import com.house365.ws.interfaces.server.ICustomer;
import com.house365.ws.interfaces.server.ICustomerCallbackLog;
import com.house365.ws.interfaces.server.IMarketCustomer;
import com.house365.ws.interfaces.server.IUser;
import com.house365.ws.service.interfaces.ICustomerCallbackLogService;
import com.house365.ws.service.interfaces.IHgsCacheUtil;
import com.house365.ws.system.ReturnResult;
import com.house365.ws.util.Constant;
import com.house365.ws.util.MergeCustomerUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * CustomerCallbackLogWS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-15
 * @see
 * @since 1.0
 */
@Service("customerCallbackLog")
public class CustomerCallbackLogImpl implements ICustomerCallbackLog {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerCallbackLogImpl.class);
    private final String CRM_URL_PREFIX = "http://218.94.115.131:97";
    /**
     * CustomerCallbackLog服务对象
     */
    @Autowired
    ICustomerCallbackLogService<CustomerCallbackLogEntity> customerCallbackLogService;
    @Autowired
    private IHgsCacheUtil hgsCacheUtil;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private ICustomerDao customerDao;
    @Autowired
    private ICustomer customer;
    @Autowired
    private IUser user;
    @Autowired
    private IMarketCustomer marketCustomer;
    @Autowired
    private CustomerCallbackMapper callbackMapper;
    @Autowired
    private MergeCustomerUtil mergeCustomerUtil;

    @Autowired
    private CustomerMergeMapper mergeMapper;

    /**
     * CustomerCallbackLog列表查询
     *
     * @param request CustomerCallbackLog列表查询请求
     * @return CustomerCallbackLog列表查询响应
     */
    @Override
    public CustomerCallbackLogListResponse getCustomerCallbackLogList(
            CustomerCallbackLogListRequest request
    ) {
        CustomerCallbackLogListResponse response = new CustomerCallbackLogListResponse();
        try {
            QueryParams<CustomerCallbackLogEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<CustomerCallbackLogEntity> customerCallbackLogs = customerCallbackLogService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(customerCallbackLogs);
            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;
    }

    @Override
    public List<CustomerCallbackLogEntity> getCustomerCallbackLogList(Map<String, Object> map) {
        return callbackMapper.getCustomerCallbackLogList(map);
    }

    @Override
    public void saveCallBackLog(CustomerCallbackLogEntity customercallbacklogentity) {
        callbackMapper.saveCallBackLog(customercallbacklogentity);
    }

    /**
     * 保存CustomerCallbackLog
     *
     * @param request CustomerCallbackLog请求
     * @return 保存CustomerCallbackLog响应
     */
    @Override
    public CustomerCallbackLogResponse addCustomerCallbackLog(CustomerCallbackLogRequest request) {
        CustomerCallbackLogResponse response = new CustomerCallbackLogResponse();
        try {
            CustomerCallbackLogEntity entity = request.getEntity();
            hgsCacheUtil.delUserSummary(entity.getManagerId());
            customerCallbackLogService.save(entity);
            //添加回访时更新客户是否交接标志(同时更新是否活跃标志)
            Map<String, Object> map = new HashMap<>(10);
            map.put("id", entity.getCustomerId());
            map.put("isHandover", 0);
            map.put("isActive", 0);
            map.put("updateTime", new Date());
            map.put("updater", entity.getCreater());
            mergeMapper.update(map);
            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;
    }

    /**
     * 删除CustomerCallbackLog通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除CustomerCallbackLog响应
     */
    @Override
    public CustomerCallbackLogResponse deleteCustomerCallbackLogById(Integer id) {
        CustomerCallbackLogResponse response = new CustomerCallbackLogResponse();
        try {
            customerCallbackLogService.delete(id);
            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;
    }

    /**
     * 修改CustomerCallbackLog
     *
     * @param request 修改CustomerCallbackLog请求
     * @return 修改CustomerCallbackLog响应
     */
    @Override
    public CustomerCallbackLogResponse updateCustomerCallbackLog(CustomerCallbackLogRequest request) {
        CustomerCallbackLogResponse response = new CustomerCallbackLogResponse();
        try {
            customerCallbackLogService.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获取CustomerCallbackLog
     *
     * @param id 唯一标识
     * @return 通过ID获取CustomerCallbackLog响应
     */
    @Override
    public CustomerCallbackLogResponse getCustomerCallbackLogById(Integer id) {
        CustomerCallbackLogResponse response = new CustomerCallbackLogResponse();
        try {
            CustomerCallbackLogEntity entity = customerCallbackLogService.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 memPhone
     * @param customerId
     * @param userId     唯一标识
     * @return 通过ID获取CustomerCallbackLog响应
     */
    @Override
    public Integer calling(String memPhone, Integer customerId, Integer userId) {
        UserEntity userEntity = (UserEntity) userDao.getById(userId);

        CustomerCallbackLogEntity callbackLogEntity = new CustomerCallbackLogEntity();
        callbackLogEntity.setCustomerId(customerId);
        callbackLogEntity.setManagerId(userEntity.getId());
        callbackLogEntity.setManagerName(userEntity.getRealName());
        callbackLogEntity.setCreateTime(new Date());
        callbackLogEntity.setContent("");
        customerCallbackLogService.save(callbackLogEntity);
        try {
            System.out.println("---------开始进入拨号接口---------");
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            nameValuePairList.add(new BasicNameValuePair("Call", userEntity.getCornet()));
            nameValuePairList.add(new BasicNameValuePair("Dialed", memPhone));
            nameValuePairList.add(new BasicNameValuePair("pid", callbackLogEntity.getId().toString()));
            nameValuePairList.add(new BasicNameValuePair("Tag", "1"));

            System.out.println("---------进入拨号---------");
            System.out.println("---------id---------" + callbackLogEntity.getId());
            System.out.println("---------cornetNew---------" + userEntity.getCornet());
            String result = HttpClientUtil.doGet(CRM_URL_PREFIX + "/CallCenterUnicom/SinglePhone.json",
                    nameValuePairList,
                    10000, "utf-8");
            System.out.println("userEntity.getCornet():" + userEntity.getCornet() + ",,Dialed:" + memPhone + ",,pid:" + callbackLogEntity.getId().toString() + ",,result:" + result);
            LOGGER.info("call single phone call:[{}] dia20181108" +
                            "led [{}] id [{}],result:[{}]", userEntity.getCornet(), memPhone,
                    callbackLogEntity.getId(), result);
        } catch (Exception ex) {
            LOGGER.error("调用打电话接口失败", ex);
            System.out.println("---------cornetNewError---------" + userEntity.getCornet());
        }
        return callbackLogEntity.getId();
    }

    /**
     * 挂断电话
     *
     * @param userId
     * @return 通过ID获取CustomerCallbackLog响应
     */
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void handUp(Integer callbackLogId, String callContent, String buyIntention, Integer userId, String labelIds,String abandon) {
        try {
            UserEntity userEntity = (UserEntity) userDao.getById(userId);
            CustomerCallbackLogEntity callbackLogEntity = customerCallbackLogService.getById(callbackLogId);
            CustomerEntity customerEntity = (CustomerEntity) customerDao.getById(callbackLogEntity.getCustomerId());
            Date newdate = new Date();
            callbackLogEntity.setContent(callContent);
            if (null != customerEntity.getIsWaitCall() && 1 == customerEntity.getIsWaitCall()) {
                callbackLogEntity.setSource(1);
            }
            //添加标签
            List<String> labIds = new ArrayList<String>();
            String[] lids;
            if(labelIds != null && labelIds.contains(",")){
                lids = labelIds.split(",");
                //标签ids
                for(String lid: lids){
                    labIds.add(lid);
                }
            }else{
                if(labelIds != null && !"".equals(labelIds)){
                    lids = new String[1];
                    lids[0] = labelIds;
                    //标签ids
                    for(String lid: lids){
                        labIds.add(lid);
                    }
                }
            }
            Map<String, Object> callMap = new HashMap<>(10);
            callMap.put("managerId", customerEntity.getManagerId());
            callMap.put("phone", customerEntity.getPhone());
            //该客户合并id
            LabelEntity labelentity = new LabelEntity();
            CustomerEntity mergerentity = customer.getMergeCustomerId(callMap);
            if(mergerentity != null){
                labelentity.setCustomerId(mergerentity.getId());
//                labelentity.setManagerId(mergerentity.getManagerId());
            }else{
                labelentity.setCustomerId(customerEntity.getId());
//                labelentity.setManagerId(userId);
            }
            List<LabelEntity> oldLabList = user.getCustomerLabelById(labelentity);
            ArrayList<String> tempArr = new ArrayList<>();
            //删除旧标签
            labelentity.setManagerId(userEntity.getId());
            user.updateUserCustomerLabel(labelentity);
            //将该用户下标记的该客户标签删除
            if(oldLabList != null && oldLabList.size()>0){
                for(int i=0;i<oldLabList.size();i++){
                    tempArr.add(oldLabList.get(i).getLabelId());
                }
//                user.updateUserCustomerLabel(labelentity);
            }
            //该客户重新绑定该用户下的标签
            List<LabelEntity> paramList = new ArrayList<LabelEntity>();
            //去重复标签
            for(String lid: labIds){
                LabelEntity le = new LabelEntity();
                le.setManagerId(userEntity.getId());
                le.setCustomerId(labelentity.getCustomerId());
//                if(!tempArr.contains(lid)){
                    le.setLabelId(lid);
                    paramList.add(le);
//                }
            }
            if(paramList.size()>0) {
                user.saveCustomersLabels(paramList);
                paramList.clear();
            }
            labIds.clear();

            //添加回访
            callbackLogEntity.setCreateTime(newdate);
            customerCallbackLogService.update(callbackLogEntity);
            customerEntity.setIsWaitCall(0);
            customerEntity.setUpdateTime(new Date());
            customerEntity.setUpdater(userEntity.getRealName());
            customerEntity.setBuyIntention("99".equalsIgnoreCase(buyIntention) ? "" : buyIntention);
            //更新回访记录的时候，同时更新会员备注
            customerEntity.setRemark(callContent);
            //会员状态 已跟踪 0 跟踪状态为98时，才可以转为已跟踪
            if (Constant.CustomerSourceEnum.HOTLINE.getMsg().equals(customerEntity.getCreateSource())) {
                if (customerEntity.getStatus().intValue() == Constant.HotLineStatusEnum.INIT.getMsg().intValue()) {
                    //重置客户绑定置业顾问时间
                    customerEntity.setBindTime(newdate);
                    customerEntity.setStatus(Constant.HotLineStatusEnum.NORECORD.getMsg());
                }
            }
            CustomerRequest customerRequest = new CustomerRequest();
            customerRequest.setEntity(customerEntity);
            customer.updateCustomerNew(customerRequest, userId, userEntity.getRealName());

            customer.crmAddCallBack(callbackLogEntity.getCustomerId());
            marketCustomer.addCallbackCount(customerEntity.getId());
            if ("1".equalsIgnoreCase(abandon)) {
                customer.abandonCustomer(String.valueOf(callbackLogEntity.getCustomerId()), userId, userEntity.getRealName(),
                        callbackLogEntity.getId());
            } else {
                //更新合并客户表
                CustomerEntity oldEntity = customer.getCustomerMerge(customerEntity.getPhone(), customerEntity.getManagerId());
                if (oldEntity == null) {
                    customerEntity.setBindTime(newdate);
                    customerEntity.setLastCallTime(newdate);
                    customer.saveCustomerMerge(customerEntity);
                    //去公海原顾问名下此客户同步更新
//                    customer.updateSeaCustomerByPhone(customerEntity, userEntity);
                } else {
                    if (Constant.CustomerSourceEnum.HOTLINE.getMsg().equals(oldEntity.getCreateSource())) {
                        if (oldEntity.getStatus().intValue() == Constant.HotLineStatusEnum.INIT.getMsg().intValue()) {
                            oldEntity.setStatus(Constant.HotLineStatusEnum.NORECORD.getMsg());
                        }
                    }
                    mergeCustomerUtil.checkMergeCustomer(customerEntity, oldEntity, userId, userEntity.getRealName());
                    // 意向等级、跟踪状态更新
                    //重置客户绑定置业顾问时间
                    oldEntity.setBindTime(newdate);
                    oldEntity.setLastCallTime(newdate);
                    oldEntity.setUpdateTime(new Date());
                    oldEntity.setCreateTime(oldEntity.getCreateTime());
                    oldEntity.setUpdater(String.valueOf(userEntity.getId()));
                    oldEntity.setIsActive(0);
                    oldEntity.setIsHandover(0);
                    customer.updateCustomerMerge(oldEntity);
                }
            }
            //无效客户回公海
            if (HGSConstant.BUYINTENTIONENUM.E.getCode().equalsIgnoreCase(buyIntention)) {
                //删除合并客户
                List<CustomerEntity> customerList = customer.getDetailCustomers(customerEntity.getPhone(), customerEntity.getManagerId());
                Map<String, Object> idMap = new HashMap<>(5);
                List<Integer> idList = new ArrayList<>();
                if (customerList != null) {
                    for (CustomerEntity ce : customerList) {
                        idList.add(ce.getId());
                    }
                }
                idMap.put("ids", idList);
                customer.deleteCustomerMergeById(idMap);

                //合并前客户回公海
                if (CollectionUtils.isNotEmpty(customerList)) {
                    for (CustomerEntity customerentity : customerList) {
                        customer.removeCustomer(customerentity.getId(), userEntity.getId());
                    }
                }
            }
            List<NameValuePair> nameValuePairList = new ArrayList<>();
            nameValuePairList.add(new BasicNameValuePair("Call", userEntity.getCornet()));
            String result = HttpClientUtil.doGet(CRM_URL_PREFIX + "/CallCenterUnicom/HandUp.json", nameValuePairList,
                    10000,
                    "utf-8");
            LOGGER.info("handUp phone call:[{}] result:[{}]", userEntity.getCornet(), result);
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error(ex.getMessage(), ex);
        }
    }

    @Override
    public List<CustomerCallbackLogEntity> queryByConditions(Map<String, Object> map) {
        List<CustomerCallbackLogEntity> list = callbackMapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        return Collections.emptyList();
    }

    /**
     * 以下均为自动生成
     */
    @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() {
    }
}
