package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.common.HGSConstant;
import com.house365.beans.entity.CustomerCallbackLogEntity;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.response.CustomerResponse;
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.service.interfaces.ICustomerService;
import com.house365.ws.service.interfaces.IUserService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.Constant;
import com.house365.ws.util.MergeCustomerUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>Title: 新增客户信息</p>
 * <p>Description: </p>
 * <p>Date: 16/9/15</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("addCustomer")
public class AddCustomerInfoImpl implements IAddCustomer {
    /**
     * 跟踪状态：有效
     */
    private static final int TRACE_STATUS_INVALID = 1;
    private static final Logger LOGGER = LoggerFactory.getLogger(AddCustomerInfoImpl.class);
    @Autowired
    private ICustomerService<CustomerEntity> customerService;
    @Autowired
    private IUserService<UserEntity> userService;
    @Autowired
    private ICustomer customer;
    @Autowired
    private ICustomerCallbackLog customercallbacklog;
    @Autowired
    private MergeCustomerUtil mergeCustomerUtil;
    @Autowired
    private CustomerMergeMapper mergeMapper;


    private synchronized static CustomerEntity getCustomer(Map<String, Object> map) {
        String name = getMapValueByKey(Constant.CUSTOMER_NAME, map, "");
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, map, "");
        String cityCode = getMapValueByKey(Constant.CITY_CODE, map, "");
        String cityName = getMapValueByKey(Constant.CITY_NAME, map, "");
        String crmId = getMapValueByKey(Constant.CRMID, map, "");
        String sex = getMapValueByKey(Constant.CUSTOMER_SEX, map,
                String.valueOf(Constant.CustomerSexEnum.NOTSURE.getMsg()));
        String actSource = getMapValueByKey(Constant.CUSTOMER_ACTSOURCE, map, "");
        String firstSource = getMapValueByKey(Constant.CUSTOMER_FIRSTSOURCE, map, "");
        String latestSource = getMapValueByKey(Constant.CUSTOMER_LATESTSOURCE, map, "");
        String latestCall = getMapValueByKey(Constant.CUSTOMER_CRM_LATESTSCALL, map, "");
        String latestCallResult = getMapValueByKey(Constant.CUSTOMER_CRM_LATESTSCALL_RESULT, map, "");
        String bizPort = getMapValueByKey("bizPort", map, "");
        String buyIntention = getMapValueByKey("buyIntention", map, "");

        String lastJoinVisitRemark = getMapValueByKey("lastJoinVisitRemark", map, "");
        String lastJoinVisitWorker = getMapValueByKey("lastJoinVisitWorker", map, "");
        String lastJoinVisitTime = getMapValueByKey("lastJoinVisitTime", map, "");

        actSource = StringUtils.StringFilter(actSource);
        CustomerEntity customerEntity = new CustomerEntity();
        switch (latestCallResult) {
            case "A":
                customerEntity.setBuyIntention("1");
                break;
            case "B":
                customerEntity.setBuyIntention("2");
                break;
            case "C":
                customerEntity.setBuyIntention("3");
                break;
            case "D":
                customerEntity.setBuyIntention("4");
                break;
            case "E":
                customerEntity.setBuyIntention("5");
                break;
            default:
                customerEntity.setBuyIntention("");
                break;
        }
        customerEntity.setName(name);
        customerEntity.setPhone(phone);
        customerEntity.setCityCode(cityCode);
        customerEntity.setCityName(cityName);
        customerEntity.setCrmId(crmId);
        customerEntity.setSex(Integer.valueOf(sex));
        customerEntity.setBizPort(bizPort);
        customerEntity.setActSource(actSource);
        customerEntity.setFirstSource(firstSource);
        customerEntity.setCrmLatestCallResult(latestCallResult);
//        customerEntity.setCreateSource(Constant.CustomerSourceEnum.CRM.getMsg());
        customerEntity.setCreateSource("CRM导入");
        customerEntity.setCustomerType(Constant.CustomerTypeEnum.ONLINE.getMsg());
        customerEntity.setLatestSource(latestSource);
        customerEntity.setCrmLatestCall(latestCall);

        customerEntity.setCreateTime(new Date());
        customerEntity.setCreater(Constant.CustomerSourceEnum.CRM.getMsg());
        customerEntity.setUpdater(Constant.CustomerSourceEnum.CRM.getMsg());
        customerEntity.setUpdateTime(new Date());
        customerEntity.setStatus(Constant.CustomerStatusEnum.NORECORD.getStatus());
        customerEntity.setTraceStatus(TRACE_STATUS_INVALID);
        customerEntity.setCrmSync("1");
        customerEntity.setOceanDate(new Date());
        customerEntity.setIsDelete(0);
        customerEntity.setLastJoinVisitRemark(lastJoinVisitRemark);
        customerEntity.setLastJoinVisitTime(lastJoinVisitTime);
        customerEntity.setLastJoinVisitWorker(lastJoinVisitWorker);
        customerEntity.setCustomerSourceType(HGSConstant.CustomerSourceType.NORMAL.getType());
        return customerEntity;
    }

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param defaultValue 默认值
     * @return value
     */
    private static String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

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

    @Override
    public void commit() {

    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CustomerResponse> response = new House365RestResponse<>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map, Constant.AddCustomerParams);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<CustomerEntity> data = doBusiness(map);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

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

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

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

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<CustomerEntity> doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();
        CustomerEntity customerEntity = getCustomer(map);

        String lastJoinVisitTime = customerEntity.getLastJoinVisitTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date lastjoinvisittime = sdf.parse(lastJoinVisitTime);
        Date newdate = new Date();

        //重置客户绑定置业顾问时间
        customerEntity.setBindTime(newdate);
        // 设置最后回访时间
        customerEntity.setLastCallTime(lastjoinvisittime);
        //客户经理
        String userId = getMapValueByKey(Constant.USER_ID, map, "");
        if (StringUtils.isNotBlank(userId)) {
            UserEntity user = userService.getById(Integer.valueOf(userId));
            if (user != null) {
                customerEntity.setManagerId(user.getId());
            }
        }
        CustomerEntity newCustomerEntity = customerService.createCustomer(customerEntity, Constant.CustomerSourceEnum.CRM.getMsg(), "CRM导入接口");
        LOGGER.warn("CRMADDCUSTOMER --- [{}]", customerEntity.toString());

        //回访记录
        CustomerCallbackLogEntity customercallbacklogentity = new CustomerCallbackLogEntity();
        if (customerEntity.getLastJoinVisitWorker() == null || "".equals(customerEntity.getLastJoinVisitWorker())) {
            customercallbacklogentity.setManagerName("CRM用户");
        } else {
            customercallbacklogentity.setManagerName("CRM用户:" + customerEntity.getLastJoinVisitWorker());
        }

        //如果传了userid，绑定客户经理
        if (!Strings.isNullOrEmpty(userId)) {
            UserEntity user = userService.getById(Integer.valueOf(userId));
            if (user != null) {
                customerService.bindCustomer(customerEntity, user);
            } else {
                LOGGER.error("绑定客户经理失败，ID不存在：" + userId);
            }
            customercallbacklogentity.setManagerId(Integer.valueOf(userId));
//            customercallbacklogentity.setManagerName(user.getRealName());
            //校验客户合并
            CustomerEntity oldEntity = customer.getCustomerMerge(customerEntity.getPhone(), Integer.valueOf(userId));
            if (oldEntity == null) {
                customerEntity.setId(newCustomerEntity.getId());
                handleCustomerMerge(newCustomerEntity);
                customer.saveCustomerMerge(customerEntity);
                //公海客户查询
                List<CustomerEntity> seaCustomers = customer.getSeaCustomerByPhone(customerEntity, user);
                //没有私客，将公海该客户数据同步更新到该顾问名下
                if (seaCustomers != null && seaCustomers.size() > 0) {
                    customer.updateSeaCustomerByPhone(customerEntity, user);
                }
            } else {
                mergeCustomerUtil.checkMergeCustomer(customerEntity, oldEntity, 0, "CRM导入接口");
                // 意向等级、跟踪状态更新
                oldEntity.setUpdater(user.getName());
                oldEntity.setUpdateTime(newdate);
                oldEntity.setCreateTime(customerEntity.getCreateTime());
                oldEntity.setBindTime(newdate);
//                oldEntity.setLastCallTime(customerEntity.getLastCallTime());
                oldEntity.setIsActive(0);
                oldEntity.setIsHandover(0);
                handleCustomerMerge(oldEntity, lastjoinvisittime);
                customer.updateCustomerMerge(oldEntity);
            }
        }
        //保存客户回访记录
        customercallbacklogentity.setCustomerId(newCustomerEntity.getId());
        customercallbacklogentity.setContent("CRM已备注:" + customerEntity.getLastJoinVisitRemark());
        customercallbacklogentity.setCreateTime(lastjoinvisittime);
        customercallbacklogentity.setCreater(customerEntity.getLastJoinVisitWorker());
        customercallbacklog.saveCallBackLog(customercallbacklogentity);
        restObject.setEntity(customerEntity);
        return restObject;
    }

    /**
     * 非客户转移-处理合并最新回访时间
     * @param currentCustomer
     * @return
     */
    public CustomerEntity handleCustomerMerge(CustomerEntity currentCustomer){
        //先去查询该客户的所有id
        List<CustomerEntity> customerIdList = customer.getCustomerIds(currentCustomer.getId(), currentCustomer.getCityCode());
        //再获取所有id的回访记录
        List<Integer> ids = new ArrayList<>();
        for (CustomerEntity entity : customerIdList) {
            ids.add(entity.getId());
        }
        Map<String, Object> idsMap = new HashMap<>(10);
        idsMap.put("ids", ids);
        if (ids.size() > 0) {
            List<CustomerCallbackLogEntity> callbacklist = customer.getCallBackList(idsMap);
            if(callbacklist != null && callbacklist.size()>0){
                currentCustomer.setLastCallTime(callbacklist.get(0).getCreateTime());
            }
        }else{
            currentCustomer.setLastCallTime(null);
        }
        return  currentCustomer;
    }


    /**
     * 客户转移-处理合并客户最近回访时间
     * @param currentCustomer
     * @param
     * @return
     */
    public CustomerEntity handleCustomerMerge(CustomerEntity currentCustomer, Date lastjoinvisittime){
        //先去查询该客户的所有id
        List<CustomerEntity> customerIdList = customer.getCustomerIds(currentCustomer.getId(), currentCustomer.getCityCode());
        //再获取所有id的回访记录
        List<Integer> ids = new ArrayList<>();
        for (CustomerEntity entity : customerIdList) {
            ids.add(entity.getId());
        }
        Map<String, Object> idsMap = new HashMap<>(10);
        idsMap.put("ids", ids);
        if (ids.size() > 0) {
            List<CustomerCallbackLogEntity> callbacklist = customer.getCallBackList(idsMap);
            if(callbacklist != null && callbacklist.size()>0 && lastjoinvisittime.before(callbacklist.get(0).getCreateTime())){
                currentCustomer.setLastCallTime(callbacklist.get(0).getCreateTime());
            }else{
                currentCustomer.setLastCallTime(lastjoinvisittime);
            }
        }
        return  currentCustomer;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(Map<String, Object> map, String[] checkParams) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

}
