/**
 * Description: CrmSourceWS接口
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-12-09 下午 16:02:32
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-12-09   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.google.common.base.Joiner;
import com.house365.beans.entity.BaseTreeEntity;
import com.house365.beans.entity.CrmSourceEntity;
import com.house365.beans.entity.DictionaryEntity;
import com.house365.beans.system.QueryParams;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.StringUtils;
import com.house365.ws.beans.request.CrmSourceListRequest;
import com.house365.ws.beans.request.CrmSourceRequest;
import com.house365.ws.beans.response.CrmSourceListResponse;
import com.house365.ws.beans.response.CrmSourceResponse;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.interfaces.server.IBaseTree;
import com.house365.ws.interfaces.server.ICrmSource;
import com.house365.ws.service.interfaces.IBaseTreeService;
import com.house365.ws.service.interfaces.ICrmSourceService;
import com.house365.ws.service.interfaces.IDictionaryService;
import com.house365.ws.system.ReturnResult;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.ListOrderedMap;
import org.apache.http.NameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * CrmSourceWS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-12-09
 * @see
 * @since 1.0
 */
@Service("crmSource")
public class CrmSourceImpl implements ICrmSource {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CrmSourceImpl.class);

    /**
     * CrmSource服务对象
     */
    @Autowired
    private ICrmSourceService<CrmSourceEntity> crmSourceService;
    @Autowired
    private IBaseTreeService baseTreeService;
    @Autowired
    private IBaseTree baseTree;
    @Autowired
    private IDictionaryService dictionaryService;
    @Value("${CRM.CONFIG.URL}")
    private String crmConfigUrl;
    @Autowired
    private RedisUtilsInterface redisUtil;

    /**
     * CrmSource列表查询
     *
     * @param request CrmSource列表查询请求
     * @return CrmSource列表查询响应
     */
    @Override
    public CrmSourceListResponse getCrmSourceList(CrmSourceListRequest request) {
        CrmSourceListResponse response = new CrmSourceListResponse();
        try {
            QueryParams<CrmSourceEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<CrmSourceEntity> crmSources = crmSourceService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(crmSources);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 保存CrmSource
     *
     * @param request CrmSource请求
     * @return 保存CrmSource响应
     */
    @Override
    public CrmSourceResponse addCrmSource(CrmSourceRequest request) {
        CrmSourceResponse response = new CrmSourceResponse();
        try {
            CrmSourceEntity entity = request.getEntity();
            crmSourceService.save(entity);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除CrmSource通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除CrmSource响应
     */
    @Override
    public CrmSourceResponse deleteCrmSourceById(Integer id) {
        CrmSourceResponse response = new CrmSourceResponse();
        try {
            crmSourceService.delete(id);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改CrmSource
     *
     * @param request 修改CrmSource请求
     * @return 修改CrmSource响应
     */
    @Override
    public CrmSourceResponse updateCrmSource(CrmSourceRequest request) {
        CrmSourceResponse response = new CrmSourceResponse();
        try {
            crmSourceService.update(request.getEntity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 通过ID获取CrmSource
     *
     * @param id 唯一标识
     * @return 通过ID获取CrmSource响应
     */
    @Override
    public CrmSourceResponse getCrmSourceById(Integer id) {
        CrmSourceResponse response = new CrmSourceResponse();
        try {
            CrmSourceEntity entity = crmSourceService.getById(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public void refreshCrmConfig() {
        try {
            String redisKey = "crm_update_job";
            String value = "crmUpdate";
            long seconds = 100;
            if (redisUtil.setNX(redisKey, value, seconds)) {
                List<NameValuePair> params = new ArrayList<>();
                String configStr = HttpClientUtil.doGet(crmConfigUrl, params);
                LOGGER.debug("refreshCrmConfig configstr[{}]", configStr);

                JSONObject config = JSONObject.fromObject(configStr);
                Date createDate = new Date();

                String activityTypeKey = "crm_activity_type";
                String phoneTypeKey = "crm_phone_type";
                String visitStatusKey = "crm_visit_status";
                String visitResultKey = "crm_visit_result";
                String targetSourcesKey = "crm_target_sources";
                String propertyTypeKey = "crm_property_type";

                if (config.containsKey("activity_type")) {
                    JSONObject activityType = (JSONObject) config.get("activity_type");
                    saveDict(activityTypeKey, activityType);
                }

                if (config.containsKey("property_type")) {
                    JSONObject activityType = (JSONObject) config.get("property_type");
                    saveDict(propertyTypeKey, activityType);
                }

                if (config.containsKey("phone_type")) {
                    JSONObject phoneType = (JSONObject) config.get("phone_type");
                    saveDict(phoneTypeKey, phoneType);
                }

                if (config.containsKey("visit_status")) {
                    JSONObject visitStatus = (JSONObject) config.get("visit_status");
                    saveDict(visitStatusKey, visitStatus);
                }

                if (config.containsKey("visit_result")) {
                    JSONObject visitStatus = (JSONObject) config.get("visit_result");
                    saveDict(visitResultKey, visitStatus);
                }

                if (config.containsKey("hierarchical_sources")) {
                    baseTreeService.clean("crmSource");
                    crmSourceService.truncateTable();
                    JSONArray cates = (JSONArray) config.get("hierarchical_sources");
                    for (Object obj : cates) {
                        JSONObject cate = (JSONObject) obj;
                        saveNode(createDate, cate);
                        if (cate.containsKey("sub_categories")) {
                            JSONArray subCates = (JSONArray) cate.get("sub_categories");
                            for (Object source : subCates) {
                                JSONObject sourceCate = (JSONObject) source;
                                //保存分类节点到basetree，来源节点到crmsource，
                                saveNode(createDate, sourceCate);
                                saveSource(createDate, sourceCate);
                            }
                        }
                    }

                    baseTree.updateUrlPath(0);
                }

                if (config.containsKey("target_sources")) {
                    JSONObject jsource = (JSONObject) config.get("target_sources");
                    dictionaryService.deleteByKey(targetSourcesKey);
                    Set<String> keys = jsource.keySet();
                    for (String key : keys) {
                        if (jsource.containsKey(key) && null != jsource.get(key)) {
                            JSONArray city = (JSONArray) jsource.get(key);
                            if (!city.isEmpty()) {
                                List<String> sourceList = new ArrayList<>();
                                for (int i = 0, sourceSize = city.size(); i < sourceSize; i++) {
                                    sourceList.add(String.valueOf(city.get(i)));
                                }
                                DictionaryEntity dictionaryEntity = new DictionaryEntity();
                                dictionaryEntity.setDicKey(targetSourcesKey);
                                dictionaryEntity.setDicValue(Joiner.on(",").join(sourceList));
                                dictionaryEntity.setDicName("抢客客户来源");
                                dictionaryEntity.setCity(key);
                                dictionaryService.save(dictionaryEntity);
                            }
                        }
                    }

                }
            }

        } catch (IOException ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
    }

    @Override
    public CrmSourceListResponse getRushCrmSourceList(String cityCode) {
        CrmSourceListResponse response = new CrmSourceListResponse();
        try {
            DictionaryEntity dictionaryEntity = dictionaryService.getByKeyAndCity("crm_target_sources", cityCode);
            List<CrmSourceEntity> sources = new ArrayList<>();
            if (dictionaryEntity != null && StringUtils.isNotBlank(dictionaryEntity.getDicValue())) {
                String[] sourceIds = dictionaryEntity.getDicValue().split(",");
                for (String sourceId : sourceIds) {
                    CrmSourceEntity crmSourceEntity = crmSourceService.getBySourceId(Integer.valueOf(sourceId));
                    sources.add(crmSourceEntity);
                }
            }
            response.setObjectList(sources);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }


    @Override
    public List<CrmSourceEntity> getListByCategory(String categoryId) {
        return crmSourceService.getListByCategory(categoryId);
    }


    private void saveDict(String dictTypeKey, JSONObject activityType) {
        dictionaryService.deleteByKey(dictTypeKey);
        for (Object obj : activityType.entrySet()) {
            DictionaryEntity dictionaryEntity = new DictionaryEntity();
            dictionaryEntity.setDicKey(dictTypeKey);
            dictionaryEntity.setDicValue(String.valueOf(((ListOrderedMap.Entry) obj).getKey()));
            dictionaryEntity.setDicName((String) ((ListOrderedMap.Entry) obj).getValue());
            dictionaryEntity.setCity("nj");
            dictionaryService.save(dictionaryEntity);
        }
    }

    private void saveSource(Date createDate, JSONObject sourceCate) {
        if (sourceCate.containsKey("sources")) {
            JSONArray subCates = (JSONArray) sourceCate.get("sources");
            for (Object source : subCates) {
                CrmSourceEntity crmSourceEntity = new CrmSourceEntity();
                JSONObject sourceNode = (JSONObject) source;
                if (sourceNode.containsKey("id") && sourceNode.get("id") != null) {
                    crmSourceEntity.setSourceId((Integer) sourceNode.get("id"));
                }
                if (sourceCate.containsKey("category_id") && sourceCate.get("category_id") != null) {
                    crmSourceEntity.setCategoryId(Integer.valueOf((Integer) sourceCate.get("category_id")));
                }
                if (sourceNode.containsKey("name") && sourceNode.get("name") != null) {
                    crmSourceEntity.setSourceName(String.valueOf(sourceNode.get("name")));
                }
                crmSourceEntity.setCategoryPid((Integer) sourceCate.get("category_pid"));
                crmSourceEntity.setCategoryName((String) sourceCate.get("category_name"));
                crmSourceEntity.setCreateTime(createDate);
                crmSourceEntity.setCreater("system");
                crmSourceEntity.setStatus(1);
                crmSourceService.save(crmSourceEntity);
            }
        }

    }

    private void saveNode(Date createDate, JSONObject cate) {
        BaseTreeEntity baseTreeEntity = new BaseTreeEntity();
        baseTreeEntity.setParentId((Integer) cate.get("category_pid"));
        baseTreeEntity.setSourceId(String.valueOf(cate.get("category_id")));
        baseTreeEntity.setName((String) cate.get("category_name"));
        baseTreeEntity.setCreateTime(createDate);
        baseTreeEntity.setCreator("Admin");
        baseTreeEntity.setStatus("1");
        baseTreeEntity.setSourceType("crmSource");
        baseTreeService.save(baseTreeEntity);
    }


    /**
     * 以下均为自动生成
     */

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // TODO Auto-generated method stub
        return null;
    }

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

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

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

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

    @Override
    public void commit() {
    }
}
