package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.common.HGSConstant;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.MessageLogEntity;
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.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.beans.response.DepartmentResponse;
import com.house365.ws.dao.mapper.MessageLogMapper;
import com.house365.ws.interfaces.server.IDepartment;
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.PathUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
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 java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

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

/**
 * <p>Title: 400新增客户信息</p>
 * <p>Description: </p>
 * <p>Date: 16/9/15</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("addHotlineCustomer")
public class AddHotlineCustomerInfoImpl implements IAddHotlineCustomer {
    /**
     * 跟踪状态：有效
     */
    private static final int TRACE_STATUS_INVALID = 1;
    private final Logger logger = LoggerFactory.getLogger(AddHotlineCustomerInfoImpl.class);
    @Autowired
    private ICustomerService<CustomerEntity> customerService;
    @Autowired
    private IUserService<UserEntity> userService;
    @Autowired
    private IDepartment department;
    @Autowired
    private MessageLogMapper messageLogMapper;

    @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.AddHotlineCustomerParams);
            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;
            String type = getMapValueByKey("type", map, "");
            logger.debug("****400新增客户信息 type****:" + type);
            if (map.containsKey("type") && "batch".equalsIgnoreCase(type)) {
                logger.debug("****doBatchBiz****:");
                data = doBatchBiz(map);
            } else {
                logger.debug("****doBusiness****:");
                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()));
        }
        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> doBatchBiz(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, "");

        String customers = getMapValueByKey("customers", map, "");
        logger.debug("cityCode:" + cityCode + ",,cityName:" + cityName + ",,userPhone:" + userPhone + ",,shortNum:" + shortNum + ",,shortNumType:" + shortNumType + ",,customers:" + customers);

        if (!Strings.isNullOrEmpty(customers)) {

            boolean bindSuccess = false;
            UserEntity user = getUser(bindSuccess, userPhone, shortNum, shortNumType, cityCode);

            if (user == null) {
                logger.warn("绑定客户经理失败，没有匹配记录" + userPhone);
                throw new Exception("绑定客户经理失败，没有匹配记录" + userPhone);
            }
            //判断用户是否是安家顾问，不是则不新增
            if ("1".equals(user.getIdentityType())) {
                JSONObject customerJO = JSONObject.fromObject(customers);

                JSONArray customerList = customerJO.getJSONArray("list");
                for (Object customer : customerList) {
                    JSONObject json = (JSONObject) customer;

                    String crmId = getJsonValueByKey(Constant.CRMID, json, "");
                    String name = getJsonValueByKey(Constant.CUSTOMER_NAME, json, "");
                    String phone = getJsonValueByKey(Constant.CUSTOMER_PHONE, json, "");
                    String sex = getJsonValueByKey(Constant.CUSTOMER_SEX, json,
                            String.valueOf(Constant.CustomerSexEnum.NOTSURE.getMsg()));
                    String actSource = getJsonValueByKey(Constant.CUSTOMER_ACTSOURCE, json, "");
                    String firstSource = getJsonValueByKey(Constant.CUSTOMER_FIRSTSOURCE, json, "");
                    String latestSource = getJsonValueByKey(Constant.CUSTOMER_LATESTSOURCE, json, "");
                    String latestCall = getJsonValueByKey(Constant.CUSTOMER_CRM_LATESTSCALL, json, "");
                    String latestCallResult = getJsonValueByKey(Constant.CUSTOMER_CRM_LATESTSCALL_RESULT, json, "");
                    String bizPort = getJsonValueByKey("bizPort", json, "");
                    String hotlineCallTime = getJsonValueByKey("callTime", json, "");
                    String hotlineCallSpend = getJsonValueByKey("callSpend", json, "");

                    actSource = StringUtils.StringFilter(actSource);
                    CustomerEntity customerEntity = new CustomerEntity();
                    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.setCustomerType(Constant.CustomerTypeEnum.ONLINE.getMsg());
                    customerEntity.setLatestSource(latestSource);
                    customerEntity.setCrmLatestCall(latestCall);
                    customerEntity.setCrmLatestCallResult(latestCallResult);
                    customerEntity.setCreateTime(new Date());
                    customerEntity.setUpdateTime(new Date());
                    if (!Strings.isNullOrEmpty(shortNum)) {
                        customerEntity.setCreateSource(Constant.CustomerSourceEnum.SYSTEM.getMsg());
                        customerEntity.setCreater(Constant.CustomerSourceEnum.SYSTEM.getMsg());
                        customerEntity.setUpdater(Constant.CustomerSourceEnum.SYSTEM.getMsg());
                        customerEntity.setStatus(Constant.HotLineStatusEnum.NORECORD.getMsg());
                    } else if (!Strings.isNullOrEmpty(userPhone)) {
                        customerEntity.setCreateSource(Constant.CustomerSourceEnum.HOTLINE.getMsg());
                        customerEntity.setCreater(Constant.CustomerSourceEnum.HOTLINE.getMsg());
                        customerEntity.setUpdater(Constant.CustomerSourceEnum.HOTLINE.getMsg());
                        customerEntity.setStatus(Constant.HotLineStatusEnum.INIT.getMsg());
                    }
                    //新房固定传A:5
                    customerEntity.setBuyIntention(Constant.BUYINTENTION);
                    customerEntity.setTraceStatus(TRACE_STATUS_INVALID);
                    customerEntity.setCrmSync("1");
                    customerEntity.setIsDelete(0);
                    customerEntity.setIsWaitCall(0);
                    customerEntity.setCustomerSourceType(HGSConstant.CustomerSourceType.NORMAL.getType());

                    //重置客户绑定置业顾问时间
                    customerEntity.setBindTime(new Date());
                    if (!Strings.isNullOrEmpty(hotlineCallTime)) {
                        customerEntity.setHotlineCallTime(new Date(Long.parseLong(hotlineCallTime)));
                    }
                    customerEntity.setHotlineCallSpend(hotlineCallSpend);
                    customerEntity.setManagerId(user.getId());
                    if (!Strings.isNullOrEmpty(shortNum)) {
                        customerService.createCustomer(customerEntity, Constant.CustomerSourceEnum.SYSTEM.getMsg(), "400新增接口");
                    } else if (!Strings.isNullOrEmpty(userPhone)) {
                        customerService.createCustomer(customerEntity, Constant.CustomerSourceEnum.CRM.getMsg(), "400新增接口");
                    }

                    customerService.bindCustomer(customerEntity, user);

                    Map<String, String> param = new HashMap<>(10);
                    param.put("customerId", String.valueOf(customerEntity.getId()));
                    if (!Strings.isNullOrEmpty(shortNum)) {
                        customerService.sendMessageToWechat(NEWCUSTOMER, String.valueOf(user.getId()), param);
                    } else if (!Strings.isNullOrEmpty(userPhone)) {
                        customerService.sendMessageToWechat(NEWHOTLINE, String.valueOf(user.getId()), param);
                    }
                    //4.1版本增加短信通知
                    sendMessage(user, phone);
                }
            }else{
                throw new Exception("置业顾问不是安家顾问，不能添加" + userPhone);
            }
        }

        return restObject;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<CustomerEntity> doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<CustomerEntity> restObject = new House365RestObject<>();
        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 userPhone = getMapValueByKey(Constant.USER_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 hotlineCallTime = getMapValueByKey("callTime", map, "");
        String hotlineCallSpend = getMapValueByKey("callSpend", map, "");

        //楼盘400短号
        String shortNum = getMapValueByKey(Constant.SHORT, map, "");
        String shortNumType = getMapValueByKey("shortNumType", map, "");

        boolean bindSuccess = false;
        UserEntity user = getUser(bindSuccess, userPhone, shortNum, shortNumType, cityCode);

        if (null == user) {
            logger.warn("绑定客户经理失败，没有匹配记录" + userPhone);
            throw new Exception("绑定客户经理失败，没有匹配记录" + userPhone);
        }
        //判断用户是否是安家顾问，不是则不新增
        if ("1".equals(user.getIdentityType())) {

            actSource = StringUtils.StringFilter(actSource);
            CustomerEntity customerEntity = new CustomerEntity();
            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.setCreateSource(Constant.CustomerSourceEnum.HOTLINE.getMsg());
            customerEntity.setCustomerType(Constant.CustomerTypeEnum.ONLINE.getMsg());
            customerEntity.setLatestSource(latestSource);
            customerEntity.setCrmLatestCall(latestCall);
            customerEntity.setCrmLatestCallResult(latestCallResult);
            customerEntity.setCreateTime(new Date());
            customerEntity.setCreater(Constant.CustomerSourceEnum.HOTLINE.getMsg());
            customerEntity.setUpdater(Constant.CustomerSourceEnum.HOTLINE.getMsg());
            customerEntity.setUpdateTime(new Date());
            customerEntity.setStatus(Constant.HotLineStatusEnum.INIT.getMsg());
            //新房固定传A:5
            customerEntity.setBuyIntention(Constant.BUYINTENTION);
            customerEntity.setTraceStatus(TRACE_STATUS_INVALID);
            customerEntity.setCrmSync("1");
            customerEntity.setIsDelete(0);
            customerEntity.setIsWaitCall(0);
            customerEntity.setCustomerSourceType(HGSConstant.CustomerSourceType.NORMAL.getType());

            //重置客户绑定置业顾问时间
            customerEntity.setBindTime(new Date());
            if (!Strings.isNullOrEmpty(hotlineCallTime)) {
                customerEntity.setHotlineCallTime(new Date(Long.parseLong(hotlineCallTime)));
            }
            customerEntity.setHotlineCallSpend(hotlineCallSpend);
            customerEntity.setManagerId(user.getId());
            customerService.createCustomer(customerEntity, Constant.CustomerSourceEnum.CRM.getMsg(), "400新增接口");

            customerService.bindCustomer(customerEntity, user);

            Map<String, String> param = new HashMap<>(10);
            customerService.sendMessageToWechat(NEWHOTLINE, String.valueOf(user.getId()), param);
            //4.1版本增加短信通知
            sendMessage(user, phone);
            restObject.setEntity(customerEntity);
        }else{
            throw new Exception("置业顾问不是安家顾问，不能添加" + userPhone);
        }
        return restObject;
    }

    private void sendMessage(UserEntity entity, String phone) {
        try {
            String mobile = entity.getMobile();
            DepartmentResponse departmentResponse = department.getDepartmentById(entity.getDeptId());
            DepartmentEntity dept = departmentResponse.getEntity();
            Integer realDept = PathUtil.extractDept(dept.getUrlPath());
            if (!entity.getDeptId().equals(realDept)) {
                dept = department.getDepartmentById(realDept).getEntity();
            }
            String cityId = dept.getCityID();
            DepartmentResponse departmentResponse2 = department.getDepartmentById(Integer.valueOf(cityId));
            String cityCode = departmentResponse2.getEntity().getDescripition();
            entity.setCity(cityCode);
            String city = entity.getCity();
            Date now = new Date();
            SimpleDateFormat f = new SimpleDateFormat("yyyy年MM月dd日kk点mm分");
            String date = f.format(now);
            String msg = "客户";
            msg += phone + "于" + date + "给您来电，" + "请在\"全链条-我的400来电中\"跟踪记录！";
            String message = msg;
            msg = URLEncoder.encode(msg, "GBK");
            String smUrl = "http://mysms.house365.com:81/index.php/Interface/apiSendMobil/jid/104/depart/1/city/";
            smUrl = smUrl + city + "/" + "mobileno/" + mobile;
            List<NameValuePair> params = new ArrayList<>();
            params.add(new BasicNameValuePair("msg", msg));
            String result = HttpClientUtil.doGet(smUrl, params, null);
            //记录短信发送日志
            MessageLogEntity logEntity = new MessageLogEntity();
            if (result != null) {
                logEntity.setSendStatus(0);
                logger.info("发送400新增客户提醒短信成功");
            } else {
                logEntity.setSendStatus(1);
                logger.error("发送400新增客户提醒短信失败");
            }
            logEntity.setRelateId(0);
            logEntity.setSender(phone);
            logEntity.setReceiver(mobile);
            logEntity.setMessageTime(new Date());
            logEntity.setMobile(mobile);
            logEntity.setSendTime(new Date());
            logEntity.setMessageInfo(message);
            messageLogMapper.save(logEntity);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送400新增客户提醒短信失败");
        }
    }

    /**
     * 获取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;
    }

    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;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    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 + "参数为空!");
                }
            }
        }
    }

    private UserEntity getUser(boolean bindSuccess, String userPhone, String shortNum, String shortNumType, 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);
                QueryParams queryParams = new QueryParams(qm);
                List<UserEntity> userEntities = userService.queryAll(queryParams);
                if(CollectionUtils.isNotEmpty(userEntities)){
                    user = userEntities.get(0);
                }
                if (user != null) {
                    bindSuccess = true;
                    break;
                }
            }

        } else if (!Strings.isNullOrEmpty(shortNum) && !",".equalsIgnoreCase(shortNum)) {
            if ("1".equalsIgnoreCase(shortNumType)) {
                //绑定直销人员短号，多个短号，只绑定一个
                for (String phonesplit : shortNum.split(",")) {
                    Map<String, Object> qm = new HashMap<>(10);
                    qm.put("EQ_hotlinephone", phonesplit);
                    QueryParams queryParams = new QueryParams(qm);
                    List<UserEntity> userEntities = userService.queryAll(queryParams);
                    if(CollectionUtils.isNotEmpty(userEntities)){
                        user = userEntities.get(0);
                    }
                    if (user != null) {
                        bindSuccess = true;
                        break;
                    }
                }
            } else {
                //绑定楼盘短号，与系统自建客户相同。不同步到CRM。
                //根据楼盘短号查询直销人员
                Map<String, Object> queryMap = new HashMap<>(10);
                queryMap.put("city", cityCode);
                queryMap.put("short", shortNum);
                List<UserEntity> userEntities = userService.getUserByPorjectShort(queryMap);

                if (userEntities != null && !userEntities.isEmpty()) {
                    bindSuccess = true;
                    user = userEntities.get(0);
                }

                //楼盘短号没有匹配，查找直销人员短号
                if (!bindSuccess) {
                    //多个短号，只绑定一个
                    for (String phonesplit : shortNum.split(",")) {
                        Map<String, Object> qm = new HashMap<>(10);
                        qm.put("EQ_hotlinephone", phonesplit);
                        QueryParams queryParams = new QueryParams(qm);
                        userEntities = userService.queryAll(queryParams);
                        if (userEntities != null && !userEntities.isEmpty()) {
                            user = userEntities.get(0);
                        }
                        if (user != null) {
                            bindSuccess = true;
                            break;
                        }
                    }
                }
            }
        }
        return user;
    }

}
