package com.house365.web.util;

import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.web.cached.RedisUtilsInterface;
import com.house365.ws.beans.request.DictionaryListRequest;
import com.house365.ws.interfaces.server.IDictionary;
import net.sf.json.JSONArray;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.house365.beans.common.HGSConstant.CACHE_DICT;
import static com.house365.beans.common.HGSConstant.CACHE_DICT_LIST;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 2017/11/29</p>
 *
 * @author XN
 * @version 1.0
 */
@Component("dictUtil")
@Scope("prototype")
public class DictUtil {

    private static RedisUtilsInterface redisUtil = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");

    private static IDictionary dictionary = (IDictionary) SpringContextUtil.getBean("dictionary");

    public static String getDictValue(String key, String defaultValue) {
        if (!Strings.isNullOrEmpty(key)) {
            final String cacheKey = CACHE_DICT + key;

            String cache = (String) redisUtil.getObjectByKey(cacheKey);
            if (!Strings.isNullOrEmpty(cache)) {
                return cache;
            }

            for (DictionaryEntity dict : getDictList(key)) {
                if (key.equals(dict.getDicKey())) {
                    redisUtil.addKeyObjectExpire(cacheKey, dict.getDicValue(), TimeUnit.DAYS.toSeconds(1));
                    return dict.getDicValue();
                }
            }

        }
        return defaultValue;
    }

    public static List<DictionaryEntity> getDictList(String key) {
        List<DictionaryEntity> list = new ArrayList<>();
        if (!Strings.isNullOrEmpty(key)) {
            final String cacheKey = CACHE_DICT_LIST + key;

            JSONArray cache = (JSONArray) redisUtil.getObjectByKey(cacheKey);
            if (cache != null && !cache.isEmpty()) {
                list = (List<DictionaryEntity>) JSONArray.toCollection(JSONArray.fromObject(cache),
                        DictionaryEntity.class);
                for(DictionaryEntity de: list){
                    if("5".equals(de.getDicValue()) && "crm_visit_result".equals(key)){
                        de.setDicName("E(丢入公海)");
                    }
                }
                return list;
            }

            DictionaryListRequest listRequest = new DictionaryListRequest();
            Map<String, Object> searchMap = new HashMap<>();
            searchMap.put("EQ_dicKey", key);
            listRequest.setSearchParams(searchMap);
            listRequest.setOrderColumn(" dic_name ");
            listRequest.setOrderMode(" asc ");
            list = dictionary.getDictionaryList(listRequest).getObjectList();
            redisUtil.addKeyObjectExpire(cacheKey, JSONArray.fromObject(list), TimeUnit.DAYS.toSeconds(1));
        }
        return list;
    }

    /**
     * 就近原则-回公海时间取值
     * @param customerEntity
     * @param userEntity
     * @param cpList
     * @param backToSeaCal
     * @param visitCount
     * @param backLogList
     * @param displayBackToSeaDate
     * @return
     */
    public static boolean getBackToSeaTime(CustomerEntity customerEntity, UserEntity userEntity, List<CustomerProjectEntity> cpList, Calendar backToSeaCal, int visitCount, List<CustomerCallbackLogEntity> backLogList
            , boolean displayBackToSeaDate){
        // 当前客户处于待回访状态以外时显示退回公海时间提示
        if (null == customerEntity.getIsWaitCall() || 0 == customerEntity.getIsWaitCall()) {
            // 当前客户存在约看项目
            if (CollectionUtils.isNotEmpty(cpList)) {
                // 约看项目个数
                int countRecorded = 0;
                // 到访项目个数
                int countVisited = 0;
                // status=2:到访的customer_project的最大id
                int maxVisitedId = 0;
                // id最大的status=2:到访的customer_project的last_change_status_time
                Date maxIdVisitedLastChangeStatusTime = null;

                for (CustomerProjectEntity cp : cpList) {
                    // 1:约看
                    if (cp.getStatus() == 1) {
                        countRecorded++;
                    } else if (cp.getStatus() > 1) {
                        // 2:到访
                        countVisited++;
                        if (cp.getId() > maxVisitedId) {
                            maxVisitedId = cp.getId();
                            maxIdVisitedLastChangeStatusTime = cp.getLastChangeStatusTime();
                        }
                    }
                }
                visitCount = countVisited;

                // 当前客户只有处于1:约看状态的customer_project时根据customer.remove.days.order显示退回公海时间提示
                if (countRecorded == cpList.size()) {
                    // 新增>>>到访
                    List<DictionaryEntity> orderDictionaries = dictionary.getListByKey("customer.remove.days.order");
                    for (DictionaryEntity dictionary : orderDictionaries) {
                        if ("0".equals(dictionary.getDicValue())) {
                            continue;
                        }
                        if (userEntity.getCity().equals(dictionary.getCity())) {
                            int orderOvertimeDays = Integer.valueOf(dictionary.getDicValue());
                            Date bindTime = customerEntity.getBindTime();
                            if(bindTime != null) {
                                backToSeaCal.setTime(bindTime);
                            }
                            backToSeaCal.add(Calendar.DATE, orderOvertimeDays);
                            displayBackToSeaDate = true;
                        }
                    }
                } else if (countVisited > 0) {
                    // 当前客户存在处于2:到访状态的customer_project时根据customer.remove.days.visit显示退回公海时间提示

                    // 到访>>>认筹
                    List<DictionaryEntity> visitDictionaries = dictionary.getListByKey("customer.remove.days.visit");
                    for (DictionaryEntity dictionary : visitDictionaries) {
                        if ("0".equals(dictionary.getDicValue())) {
                            continue;
                        }
                        if (userEntity.getCity().equals(dictionary.getCity())) {
                            int visitOvertimeDays = Integer.valueOf(dictionary.getDicValue());
                            backToSeaCal.setTime(maxIdVisitedLastChangeStatusTime);
                            backToSeaCal.add(Calendar.DATE, visitOvertimeDays);
                            displayBackToSeaDate = true;
                        }
                    }
                }
            } else {
                // 无约看楼盘记录
                // X天无回访客户
                List<DictionaryEntity> orderDictionaries = dictionary.getListByKey("customer.remove.days.nocallrecord");
                for (DictionaryEntity dictionary : orderDictionaries) {
                    if (userEntity.getCity().equals(dictionary.getCity())) {
                        int nocallOvertimeDays = Integer.valueOf(dictionary.getDicValue());

                        // 有回访记录
                        if (backLogList != null && !backLogList.isEmpty()) {

                            Date latestCallbackTime = null;
                            // 当前日期-最新的回访日期
                            for (CustomerCallbackLogEntity callbackLog : backLogList) {
                                Date callbackTime = callbackLog.getCreateTime();
                                if (latestCallbackTime == null || latestCallbackTime.before(callbackTime)) {
                                    latestCallbackTime = callbackTime;
                                }
                            }
                            backToSeaCal.setTime(latestCallbackTime);
                            backToSeaCal.add(Calendar.DATE, nocallOvertimeDays);
                        } else {
                            // 无回访记录
                            // 当前日期-绑定日期
                            Date bindTime = customerEntity.getBindTime();
                            if(bindTime != null) {
                                backToSeaCal.setTime(bindTime);
                            }
                            backToSeaCal.add(Calendar.DATE, nocallOvertimeDays);
                        }
                        displayBackToSeaDate = true;
                    }
                }
            }
        }
        //不限约看记录
        Date oldpicktime = backToSeaCal.getTime();
        List<DictionaryEntity> orderDictionaries = dictionary.getListByKey("customer.remove.days.nolimit");
        for (DictionaryEntity dictionary : orderDictionaries) {
            if (userEntity.getCity().equals(dictionary.getCity())) {
                int nocallOvertimeDays = Integer.valueOf(dictionary.getDicValue());
                // 有回访记录
                if (backLogList != null && !backLogList.isEmpty()) {
                    Date latestCallbackTime = null;
                    // 当前日期-最新的回访日期
                    for (CustomerCallbackLogEntity callbackLog : backLogList) {
                        Date callbackTime = callbackLog.getCreateTime();
                        if (latestCallbackTime == null || latestCallbackTime.before(callbackTime)) {
                            latestCallbackTime = callbackTime;
                        }
                    }
                    backToSeaCal.setTime(latestCallbackTime);
                    backToSeaCal.add(Calendar.DATE, nocallOvertimeDays);
                } else {
                    // 无回访记录
                    // 当前日期-绑定日期
                    Date bindTime = customerEntity.getBindTime();
                    if(bindTime != null) {
                        backToSeaCal.setTime(bindTime);
                    }
                    backToSeaCal.add(Calendar.DATE, nocallOvertimeDays);
                }
                if (displayBackToSeaDate) {
                    Date newpicktime = backToSeaCal.getTime();
                    if (oldpicktime.before(newpicktime)) {
                        backToSeaCal.setTime(oldpicktime);
                    }
                }
                displayBackToSeaDate = true;
            }
        }

        //新增N天无回访（且未到访）判断
        Date pickTime = backToSeaCal.getTime();
        List<DictionaryEntity> newList = dictionary.getListByKey("customer.remove.days.noVisit");
        if (CollectionUtils.isNotEmpty(newList) && visitCount == 0) {
            for (DictionaryEntity dictionary : newList) {
                if (userEntity.getCity().equals(dictionary.getCity())) {
                    int overtimeDays = Integer.valueOf(dictionary.getDicValue());
                    if (CollectionUtils.isNotEmpty(backLogList)) {
                        Date latestCallbackTime = null;
                        // 当前日期-最新的回访日期
                        for (CustomerCallbackLogEntity callbackLog : backLogList) {
                            Date callbackTime = callbackLog.getCreateTime();
                            if (latestCallbackTime == null || latestCallbackTime.before(callbackTime)) {
                                latestCallbackTime = callbackTime;
                            }
                        }
                        backToSeaCal.setTime(latestCallbackTime);
                        backToSeaCal.add(Calendar.DATE, overtimeDays);
                    } else {
                        // 无回访记录
                        // 当前日期-绑定日期
                        Date bindTime = customerEntity.getBindTime();
                        if(bindTime != null) {
                            backToSeaCal.setTime(bindTime);
                        }
                        backToSeaCal.add(Calendar.DATE, overtimeDays);
                    }

                    if (displayBackToSeaDate) {
                        Date newPickTime = backToSeaCal.getTime();
                        if (pickTime.before(newPickTime)) {
                            backToSeaCal.setTime(pickTime);
                        }
                    }
                    displayBackToSeaDate = true;
                }
            }
        }
        return displayBackToSeaDate;
    }


}
