package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.HouseInfoEntity;
import com.house365.beans.entity.RushCustomerEntity;
import com.house365.beans.entity.RushCustomerProjectRelEntity;
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.service.interfaces.IRushCustomerProjectRelService;
import com.house365.ws.service.interfaces.IRushCustomerService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.Constant;
import com.house365.ws.util.PhpInterfaceUtils;
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.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: 新增客户信息</p>
 * <p>Description: </p>
 * <p>Date: 16/9/15</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("addRushCustomer")
public class AddRushCustomerInfoImpl implements IAddRushCustomer {

    private final Logger LOGGER = LoggerFactory.getLogger(AddRushCustomerInfoImpl.class);
    @Autowired
    private IRushCustomerService<RushCustomerEntity> rushCustomerService;
    @Autowired
    private IRushCustomerProjectRelService<RushCustomerProjectRelEntity> relService;

    @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<CustomerResponse>();
        // 业务校验统一入口
        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<RushCustomerEntity> 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<RushCustomerEntity> doBusiness(Map<String, Object> map) throws Exception {
        LOGGER.info("===================add rush customer start===================");
        LOGGER.info("rush customer info:[{}]", JSONObject.fromObject(map).toString());

        // 返回Json对象
        House365RestObject<RushCustomerEntity> 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 sex = getMapValueByKey(Constant.CUSTOMER_SEX, map, String.valueOf(Constant.CustomerSexEnum.NOTSURE.getMsg()));
        String actSource = getMapValueByKey(Constant.CUSTOMER_ACTSOURCE, map, "");
        String actSourceId = getMapValueByKey("actSourceId", map, "");

        String bizPort = getMapValueByKey("bizPort", map, "");
        String buyIntention = getMapValueByKey("buyIntention", map, "");

        String projectIds = getMapValueByKey("projectIds", map, "");

        actSource = StringUtils.StringFilter(actSource);
        RushCustomerEntity rushCustomerEntity = new RushCustomerEntity();
        rushCustomerEntity.setName(name);
        rushCustomerEntity.setPhone(phone);
        rushCustomerEntity.setCityCode(cityCode);
        rushCustomerEntity.setCityName(cityName);
        rushCustomerEntity.setCrmId(crmId);
        rushCustomerEntity.setSex(Integer.valueOf(sex));
        rushCustomerEntity.setBizPort(bizPort);
        rushCustomerEntity.setActSource(actSource);
//        rushCustomerEntity.setCreateSource(Constant.CustomerSourceEnum.CRM.getMsg());
        rushCustomerEntity.setCreateSource("CRM导入-抢客");
        rushCustomerEntity.setCustomerType(Constant.CustomerTypeEnum.ONLINE.getMsg());
        rushCustomerEntity.setCreateTime(new Date());
        rushCustomerEntity.setCreater(Constant.CustomerSourceEnum.CRM.getMsg());
        rushCustomerEntity.setUpdater(Constant.CustomerSourceEnum.CRM.getMsg());
        rushCustomerEntity.setUpdateTime(new Date());
        rushCustomerEntity.setStatus(Constant.CustomerStatusEnum.NORECORD.getStatus());
        if (!"0".equals(buyIntention)) {
            rushCustomerEntity.setBuyIntention(buyIntention);
        }
        rushCustomerEntity.setActSourceId(Integer.valueOf(actSourceId));

        rushCustomerEntity.setRushStatus(0);
        rushCustomerEntity.setIsDeleted(0);

        Integer rushCustomerId = rushCustomerService.createRushCustomer(rushCustomerEntity);

        StringBuilder projectNames = new StringBuilder();
        if (StringUtils.isNotBlank(projectIds)) {
            String[] projectIdArray = projectIds.split(",");
            for (String projectId : projectIdArray) {
                List<HouseInfoEntity> houseInfoEntities = PhpInterfaceUtils.getHouseByIds(projectId, cityCode, null);
                String projectName = "";
                if (houseInfoEntities != null && houseInfoEntities.size() != 0) {
                    projectName = houseInfoEntities.get(0).getHouseName();
                }
                projectNames.append(projectName);

                RushCustomerProjectRelEntity rushCustomerProjectRelEntity = new RushCustomerProjectRelEntity();
                rushCustomerProjectRelEntity.setProjectId(Integer.valueOf(projectId));
                rushCustomerProjectRelEntity.setRushCustomerId(rushCustomerId);
                rushCustomerProjectRelEntity.setProjectName(projectName);
                relService.save(rushCustomerProjectRelEntity);
            }
            rushCustomerEntity.setProjectId(projectIds);
            rushCustomerEntity.setProjectName(projectNames.toString());
        }

        LOGGER.info("===================add rush customer end===================");
        restObject.setEntity(rushCustomerEntity);
        rushCustomerService.update(rushCustomerEntity);
        return restObject;
    }

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

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

}
