package com.house365.ws.interfaces.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.dao.mapper.CustomerCallbackMapper;
import com.house365.ws.dao.mapper.CustomerMergeMapper;
import com.house365.ws.dao.mapper.DictionaryMapper;
import com.house365.ws.dao.mapper.SignUpTrackMapper;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
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 java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Created by Administrator on 2019/11/6.
 *         同步crm报名轨迹数据
 */
@Service("addSignUpTrack")
public class AddSignUpTrackImpl implements IAddSignUpTrackInterface {

    private Logger logger = LoggerFactory.getLogger(AddSignUpTrackImpl.class);

    @Value("${crm.track.url}")
    private String crmTrackUrl;

    @Autowired
    private SignUpTrackMapper trackMapper;
    @Autowired
    private CustomerMergeMapper mergeMapper;
    @Autowired
    private CustomerCallbackMapper callbackMapper;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        House365RestResponse<SignUpTrackEntity> response = new House365RestResponse<>();
        try {
//            List<NameValuePair> params = new ArrayList<>();
//            String result = HttpClientUtil.doGet(crmTrackUrl, params);
//
//            // 业务层统一处理
//            ObjectMapper objectMapper = new ObjectMapper();
//            Map<String, Map> dataMap = objectMapper.readValue(result, Map.class);
//            Number total = (Number) dataMap.get("total");
//            if (total.intValue() > 0) {
//                List<Map<String, Object>> dataList = (List<Map<String, Object>>) dataMap.get("data");
//                if (CollectionUtils.isNotEmpty(dataList)) {
//                    for (Map<String, Object> m : dataList) {
//                        String phone = m.get("phone").toString();
//                        String city = m.get("city").toString();
//                        String time = m.get("join_time").toString();
//                        long longTime = Long.parseLong(time);
//
//                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        time = format.format(longTime * 1000);
//                        Date signUpTime = format.parse(time);
//                        Map<String, Object> searchMap = new HashMap<>(10);
//                        searchMap.put("phone", phone);
//                        searchMap.put("cityCode", city);
//                        List<CustomerEntity> list = mergeMapper.queryByConditions(searchMap);
//                        List<Integer> idList = new ArrayList<>();
//                        if (CollectionUtils.isNotEmpty(list)) {
//                            for (CustomerEntity c : list) {
//                                idList.add(c.getId());
//                            }
//                            Map<String, Object> callBackMap = new HashMap<>(10);
//                            callBackMap.put("idList", idList);
//                            List<CustomerCallbackLogEntity> backList = callbackMapper.queryByConditions(callBackMap);
//                            if (CollectionUtils.isNotEmpty(backList)) {
//                                CustomerCallbackLogEntity logEntity = backList.get(0);
//                                int customerId = logEntity.getCustomerId();
//                                SignUpTrackEntity entity = new SignUpTrackEntity();
//                                entity.setCity(city);
//                                entity.setPhone(phone);
//                                entity.setCustomerId(customerId);
//                                entity.setSignUpTime(signUpTime);
//                                trackMapper.save(entity);
//                                Date callbackTime = logEntity.getCreateTime();
//                                //报名时间大于回访时间，修改客户状态为活跃
//                                if (callbackTime.before(signUpTime)) {
//                                    //添加回访时更新客户是否交接标志(同时更新是否活跃标志)
//                                    Map<String, Object> updateMap = new HashMap<>(10);
//                                    updateMap.put("id", customerId);
//                                    updateMap.put("isActive", 1);
//                                    updateMap.put("updateTime", new Date());
//                                    updateMap.put("activeTime", new Date());
//                                    mergeMapper.update(updateMap);
//                                }
//                            }
//                        }
//                    }
//                }
//            }
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error("同步crm报名轨迹数据失败", e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();

    }

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

    @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() {

    }
}
