package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerCallbackLogEntity;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.QueryParams;
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.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.*;

@Service("addProgramCustomer")
public class AddProgramCustomerImpl implements IAddProgramCustomer {

    private final Logger logger = LoggerFactory.getLogger(AddProgramCustomerImpl.class);
    @Autowired
    private ICustomerService<CustomerEntity> customerService;

    @Autowired
    private IUserService<UserEntity> userService;

    @Autowired
    private ICustomer customer;
    @Autowired
    private MergeCustomerUtil mergeCustomerUtil;
    @Autowired
    private ICustomerCallbackLog customercallbacklog;

    @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.AddProgramCustomerParams);
            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 = null;
            logger.info("****小程序新增客户信息 type****:");
            data = doBusiness(map);
            String msg = ReturnAppResult.APP_SUCCESS.getResultMessage();
            if (data.getParaMap() != null && data.getParaMap().containsKey("msg")) {
                msg = ReturnAppResult.APP_SUCCESS.getResultMessage() + "[" + String.valueOf(
                        data.getParaMap().get("msg") + "]");
            }

            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(msg);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    @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<>();
        String cityCode = getMapValueByKey(Constant.CITY_CODE, map, "");
        String cityName = getMapValueByKey(Constant.CITY_NAME, map, "");
        //客户经理
        String userPhone = getMapValueByKey(Constant.USER_PHONE, map, "");
        //楼盘400短号
        String shortNum = getMapValueByKey(Constant.SHORT, map, "");
//        String shortNumType = getMapValueByKey("shortNumType", map, "");
        logger.info("cityCode:" + cityCode + ",,cityName:" + cityName + ",,userPhone:" + userPhone + ",,shortNum:" + shortNum);
        boolean bindSuccess = false;
        UserEntity user = getUser(bindSuccess, userPhone, cityCode);

        String crmId = getMapValueByKey(Constant.CRMID, map, "");
        String name = getMapValueByKey(Constant.CUSTOMER_NAME, map, "");
        String phone = getMapValueByKey(Constant.CUSTOMER_PHONE, 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 lastjoinvisittime = getMapValueByKey("lastjoinVisitTime", map, "");
        Date newdate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date lastcalltime = sdf.parse(lastjoinvisittime);
        String lastJoinVisitRemark = getMapValueByKey("lastJoinVisitRemark", map, "");
        String traceStatus = getMapValueByKey("traceStatus", map, "");
        String lastJoinVisitWorker = getMapValueByKey("lastJoinVisitWorker", map, "");
        actSource = StringUtils.StringFilter(actSource);
        CustomerEntity customerEntity = new CustomerEntity();
        customerEntity.setName(name);
        customerEntity.setLastJoinVisitWorker(lastJoinVisitWorker);
        customerEntity.setLastJoinVisitTime(lastjoinvisittime);
        customerEntity.setLastJoinVisitRemark(lastJoinVisitRemark);
        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.setCustomerType(Constant.CustomerTypeEnum.ONLINE.getMsg());
        customerEntity.setLatestSource(latestSource);
        customerEntity.setCrmLatestCall(latestCall);
        customerEntity.setCrmLatestCallResult(latestCallResult);
        customerEntity.setLastCallTime(lastcalltime);
        customerEntity.setCreateTime(newdate);
        customerEntity.setUpdateTime(newdate);
        customerEntity.setCreateSource("xcx");
        customerEntity.setCreater("xcx");
        customerEntity.setUpdater("xcx");
        customerEntity.setStatus(0);
        //
        customerEntity.setBuyIntention(buyIntention);
        customerEntity.setTraceStatus(Integer.valueOf(traceStatus));
        customerEntity.setCrmSync("1");
        customerEntity.setIsDelete(0);
        customerEntity.setIsWaitCall(0);
        customerEntity.setCustomerSourceType(4);//4:小程序

        //重置客户绑定置业顾问时间
        customerEntity.setBindTime(newdate);
        if (user != null) {
            customerEntity.setManagerId(user.getId());
        } else {
            throw new IllegalServiceParameterException("所传安家顾问手机号查询不到相关人员信息");//todo:后期整改日志处理
        }
        CustomerEntity newcustomerentity = customerService.createCustomer(customerEntity, "XCX", "推广宝导入");
        customerService.bindCustomer(customerEntity, user);
        //合并客户
        if (user != null) {
            CustomerEntity oldentity = customer.getCustomerMerge(customerEntity.getPhone(), user.getId());
            if (oldentity == null) {
                customerEntity.setId(newcustomerentity.getId());
                handleCustomerMerge(customerEntity);
                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, "推广宝导入");
                // 意向等级、跟踪状态更新
                oldentity.setUpdater(user.getName());
                oldentity.setUpdateTime(newdate);
                oldentity.setCreateTime(customerEntity.getCreateTime());
                oldentity.setBindTime(newdate);
                handleCustomerMerge(oldentity, customerEntity.getLastCallTime());
//                oldentity.setLastCallTime(customerEntity.getLastCallTime());
                customer.updateCustomerMerge(oldentity);
            }
        }
        //保存客户回访记录
//        String lastJoinVisitTime = customerEntity.getLastJoinVisitTime();
        CustomerCallbackLogEntity customercallbacklogentity = new CustomerCallbackLogEntity();
        customercallbacklogentity.setCustomerId(newcustomerentity.getId());
        customercallbacklogentity.setContent("推广宝:" + customerEntity.getLastJoinVisitRemark());
        customercallbacklogentity.setManagerName("CRM用户:" + customerEntity.getLastJoinVisitWorker());
        customercallbacklogentity.setCreateTime(lastcalltime);
        customercallbacklogentity.setCreater(customerEntity.getLastJoinVisitWorker());
        customercallbacklogentity.setManagerId(user.getId());
        customercallbacklog.saveCallBackLog(customercallbacklogentity);

        return restObject;
    }


    /**
     * 客户转移-处理合并客户最近回访时间
     *
     * @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;
    }

    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());
            }
        }
        return currentCustomer;
    }

    private UserEntity getUser(boolean bindSuccess, String userPhone, String cityCode) {
        //有电话绑电话
        UserEntity user = null;
        if (!Strings.isNullOrEmpty(userPhone) && !",".equalsIgnoreCase(userPhone)) {
            //多个号码，只绑定一个
            for (String phonesplit : userPhone.split(",")) {
                Map<String, Object> qm = new HashMap<>(10);
                qm.put("EQ_mobile", phonesplit);
                qm.put("EQ_cityCode", cityCode);
                QueryParams queryParams = new QueryParams(qm);
                List<UserEntity> userEntities = userService.queryAll(queryParams);
                if (userEntities != null && !userEntities.isEmpty()) {
                    user = userEntities.get(0);
                }
                if (user != null) {
                    bindSuccess = true;
                    break;
                }
            }

        }

        return user;
    }

    private String getJsonValueByKey(String key, JSONObject obj, String defaultValue) {
        String value = "";
        if (obj.containsKey(key) && obj.get(key) != null && !Strings.isNullOrEmpty(String.valueOf(obj.get(key)))) {
            value = String.valueOf(obj.get(key));
        }

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

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param defaultValue 默认值
     * @return value
     */
    private 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;
    }

    protected void checkInterfaceParameter(Map<String, Object> map, String[] checkParams) throws IllegalServiceParameterException {
        if (map.containsKey("type") && "batch".equalsIgnoreCase(((String[]) map.get("type"))[0])) {

        } else {
            // 方法所需参数
            for (String str : checkParams) {
                // 如果不存在跳出 同时抛出相应异常
                if (!map.containsKey(str)) {
                    throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
                }
            }
        }
    }
}
