/**
 * Description: 客户项目信息业务实现类
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-15 下午 15:36:18
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-15   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.service.impl;

import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.common.json.JSONObject;
import com.google.common.base.Strings;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.entity.CustomerProjectEntity;
import com.house365.beans.entity.ProjectEntity;
import com.house365.beans.system.QueryParams;
import com.house365.commons.system.HttpClientUtil;
import com.house365.dao.system.interfaces.Dao;
import com.house365.service.system.impl.DefaultServiceImpl;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.dao.interfaces.ICustomerProjectDao;
import com.house365.ws.service.interfaces.ICustomerProjectService;
import com.house365.ws.service.interfaces.ICustomerService;
import com.house365.ws.service.interfaces.ICustomerStatusLogService;
import com.house365.ws.service.interfaces.IProjectService;
import com.house365.ws.util.Constant;
import org.apache.commons.codec.digest.DigestUtils;
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.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * 客户项目信息业务实现类<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-15
 * @see
 * @since 1.0
 */
@Service("customerProjectService")
public class CustomerProjectServiceImpl<T extends CustomerProjectEntity> extends DefaultServiceImpl<T> implements ICustomerProjectService<T> {
    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入的数据访问对象
     */
    @Autowired
    private ICustomerProjectDao<T> customerProjectDao;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private ICustomerStatusLogService customerStatusLogService;

    @Autowired
    private ICustomerService customerService;

    @Override
    protected Dao<T> getDao() {
        return customerProjectDao;
    }

    @Override
    public void updateStatus(CustomerProjectEntity customerProjectEntity, Integer status, String updater) throws Exception {
        if (customerProjectEntity.getStatus() > status) {
            throw new Exception("状态变更无效");
        }

        Integer oldStatus = customerProjectEntity.getStatus();

        Date date = new Date();
        customerProjectEntity.setStatus(status);
        customerProjectEntity.setUpdater(updater);
        customerProjectEntity.setUpdateTime(date);
        update((T) customerProjectEntity);

        //状态不变，不更新客户项目状态纪录，添加状态日志。 统计时应过滤重复数据。 如果是到访 更新到访次数
        //相同状态，标记是否参与统计为否
        Integer statisticFlag = (oldStatus.compareTo(status) != 0) ? 1 : 0;

        //变更客户项目状态
        customerStatusLogService.addStatusLogWithProject(customerProjectEntity.getCustomerId(), oldStatus, status,
                "客户项目状态变更", updater, null,customerProjectEntity.getProjectId(),
                null, statisticFlag);

        ProjectEntity project = (ProjectEntity) projectService.getById(customerProjectEntity.getProjectId());

        CustomerEntity customer = (CustomerEntity) customerService.getById(customerProjectEntity.getCustomerId());

        String response = postToCRM(customerProjectEntity, date, project, customer);

        logger.info("response is {}", response);
    }

    /**
     * 更新CRM客户项目状态
     *
     * @param customerProjectEntity
     * @param date
     * @param project
     * @param customer
     * @return
     * @throws IOException
     */
    @Override
    public String postToCRM(CustomerProjectEntity customerProjectEntity, Date date, ProjectEntity project, CustomerEntity customer)
            throws IOException {
        String crmUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("CRM.CUSTOMERPROJECT.UPDATESTATUS.URL");

        String shaKey = DigestUtils.sha256Hex("1.0" + date.getTime() / 1000 + "singleTHISISTHEKEY");
        crmUrl += "&timestamp=" + (date.getTime() / 1000);
        crmUrl += "&transType=single";
        crmUrl += "&apiKey=" + shaKey;
        StringBuilder ps = new StringBuilder("{");
        JSONObject jsonObject = new JSONObject();
        if (!Strings.isNullOrEmpty(customer.getCrmId())) {
            ps.append("\"crm_id\":\"").append(customer.getCrmId()).append("\",");
            jsonObject.put("crm_id", customer.getCrmId());
        }
        if (!Strings.isNullOrEmpty(customer.getCityCode())) {
            ps.append("\"city\":\"").append(customer.getCityCode()).append("\",");
            jsonObject.put("city", customer.getCityCode());
        }
        if (!Strings.isNullOrEmpty(customer.getBuyIntention())) {
            ps.append("\"buy_intention\":\"").append(customer.getBuyIntention()).append("\",");
            jsonObject.put("buy_intention", customer.getBuyIntention());
        }
        if (!Strings.isNullOrEmpty(customer.getPhone())) {
            ps.append("\"phone\":\"").append(customer.getPhone()).append("\",");
            jsonObject.put("phone", customer.getPhone());
        }
        if (!Strings.isNullOrEmpty(project.getProjectName())) {
            ps.append("\"building_name\":\"").append(project.getBuildingName()).append("\",");
            jsonObject.put("building_name", project.getBuildingName());
        }
        if (!Strings.isNullOrEmpty(project.getProjectName())) {
            ps.append("\"project_name\":\"").append(project.getProjectName()).append("\",");
            jsonObject.put("project_name", project.getProjectName());
        }
        if (null != customerProjectEntity.getStatus()) {
            ps.append("\"client_status\":\"").append(
                    Constant.CustomerStatusEnum.getMsgByStatus(customerProjectEntity.getStatus())).append("\",");
            jsonObject.put("client_status",
                    Constant.CustomerStatusEnum.getMsgByStatus(customerProjectEntity.getStatus()));
        }
        if (!Strings.isNullOrEmpty(customer.getCityCode())) {
            ps.append("\"update_time\":\"").append(customerProjectEntity.getOccurTimeToCrm()).append("\",");
            jsonObject.put("update_time", (customerProjectEntity.getOccurTimeToCrm()));
        }
        if (!Strings.isNullOrEmpty(customerProjectEntity.getRequireHouseType())) {
            ps.append("\"building_layout\":\"").append(customerProjectEntity.getRequireHouseType()).append("\",");
            jsonObject.put("building_layout", customerProjectEntity.getRequireHouseType());
        }
        if (!Strings.isNullOrEmpty(customerProjectEntity.getRequireArea())) {
            ps.append("\"building_area\":\"").append(customerProjectEntity.getRequireArea()).append("\",");
            jsonObject.put("building_area", customerProjectEntity.getRequireArea());
        }
        if (!Strings.isNullOrEmpty(customerProjectEntity.getRequirePrice())) {
            ps.append("\"building_budget\":\"").append(customerProjectEntity.getRequirePrice()).append("\"");
            jsonObject.put("building_budget", customerProjectEntity.getRequirePrice());
        }
        ps.append("}");
        //        crmUrl += "&data=\"" + ps.toString() + "\"";
        String pas = JSON.json(jsonObject);
        logger.debug("postToCRM_parameter: {}", pas);
        List<NameValuePair> pairs = new ArrayList<>();
        pairs.add(new BasicNameValuePair("data", pas));
        URLEncoder.encode(crmUrl, "utf8");
        return HttpClientUtil.doPostWithCharset(crmUrl, pairs, "utf8", "utf8");
    }


    String getUnicode(String s) {
        String s1 = "";
        for (int i = 0; i < s.length(); i++) {
            s1 += "\\u" + Integer.toHexString(s.charAt(i) & 0xffff);
        }
        return s1;
    }

    /**
     * 约看时检查是否为重客，指定项目中相同手机号存在到访及以后状态的纪录，约看时记录为重客
     *
     * @param phone 客户电话
     * @param pid   项目ID
     * @return
     */
    @Override
    public int checkRepeat(String phone, String pid) {
        QueryParams queryParams = new QueryParams();
        Map<String, Object> searchMap = new HashMap<>();
        searchMap.put("GT_status", Constant.CustomerStatusEnum.RECORDED.getStatus());
        searchMap.put("LTE_status", Constant.CustomerStatusEnum.SING.getStatus());
        searchMap.put("EQ_customerPhone", phone);
        searchMap.put("EQ_projectId", pid);
        queryParams.setSearchParams(searchMap);
        return getTotalCount(queryParams);
    }

    @Override
    public void updateName(Integer id, String projectName) {
        customerProjectDao.updateName(id, projectName);
    }
}
