package com.house365.ws.interfaces.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.house365.beans.entity.CloudActivityEntity;
import com.house365.beans.entity.CloudCustomerEntity;
import com.house365.beans.entity.CloudRuleEntity;
import com.house365.beans.entity.CustomerEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.dao.mapper.CloudActivityMapper;
import com.house365.ws.dao.mapper.CloudCustomerMapper;
import com.house365.ws.dao.mapper.CloudRuleMapper;
import com.house365.ws.dao.mapper.CustomerMergeMapper;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定制云迹添加客户
 *
 * @author Created by 365 on 2020/8/13.
 */
@Service("addRuleCloudCus")
public class AddRuleCloudCusImpl implements IAddRuleCloudCus {

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

    @Autowired
    private CloudCustomerMapper mapper;
    @Autowired
    private CloudActivityMapper activityMapper;
    @Autowired
    private CustomerMergeMapper mergeMapper;
    @Autowired
    private CloudRuleMapper ruleMapper;


    @Override
    @Transactional(rollbackFor = {Exception.class})
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map<String, Object>> response = new House365RestResponse<>();
        try {
            // 业务层统一处理
            String data = getMapValueByKey("data", map, "");
            logger.info("同步定制云迹客户数据接口参数： + " + data);
            if (!Strings.isNullOrEmpty(data)) {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Map<String, Map>> webMap = objectMapper.readValue(data, Map.class);
                List<Map<String, Object>> dataList = (List<Map<String, Object>>) webMap.get("list");
                List<Map<String, Object>> backList = new ArrayList<>();
                if (CollectionUtils.isNotEmpty(dataList)) {
                    if (dataList.size() > 1000) {
                        response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                        response.setMsg("请求参数list不能超过1000条");
                        return JSONObject.fromObject(response).toString();
                    } else {
                        House365RestObject<Map<String, Object>> restObject = new House365RestObject<>();
                        for (Map<String, Object> m : dataList) {
                            String phone = m.get("phone").toString();
                            String signupHouseName = m.get("signupHouseName").toString();
                            String projectId = m.get("buildingId").toString();

                            String city = m.get("cityCode").toString();
                            if (StringUtils.isBlank(phone) || StringUtils.isBlank(signupHouseName) || StringUtils.isBlank(city) || StringUtils.isBlank(projectId)) {
                                continue;
                            }
                            Map<String, Object> map1 = new HashMap<>(5);
                            map1.put("projectId", Integer.parseInt(projectId));
                            map1.put("cityCode", city);
                            List<CloudRuleEntity> ruleList = ruleMapper.queryByConditions(map1);
                            if (CollectionUtils.isNotEmpty(ruleList)) {
                                CloudRuleEntity ruleEntity = ruleList.get(0);
                                int createId = ruleEntity.getUserId();

                                Map<String, Object> searchMap = new HashMap<>(5);
                                String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                                String startTime = date + " 00:00:00";
                                String endTime = date + " 23:59:59";
                                searchMap.put("startTime", startTime);
                                searchMap.put("endTime", endTime);
                                searchMap.put("city", city);
                                searchMap.put("likeName", "定制");
                                searchMap.put("createId", createId);
                                List<CloudActivityEntity> list = activityMapper.queryByConditions(searchMap);

                                if (CollectionUtils.isNotEmpty(list)) {
                                    CloudActivityEntity activityEntity = list.get(0);
                                    int activeId = activityEntity.getId();
                                    //不存在需要返回给crm 判断手机号是否已存在
                                    Map<String, Object> queryMap = new HashMap<>(5);
                                    queryMap.put("phone", phone);
                                    List<CustomerEntity> cusList = mergeMapper.queryByConditions(queryMap);
                                    if (CollectionUtils.isEmpty(cusList)) {
                                        CloudCustomerEntity entity = getCloudCustomer(m);
                                        entity.setActiveId(activeId);
                                        entity.setIsOvertime(0);
                                        mapper.save(entity);
                                        Map<String, Object> putMap = new HashMap<>(10);
                                        putMap.put("city", city);
                                        putMap.put("phone", phone);
                                        backList.add(putMap);
                                    }
                                }
                            }
                        }
                        restObject.setList(backList);
                        response.setData(restObject);
                    }
                }
            } else {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("接口参数不全");
                return JSONObject.fromObject(response).toString();
            }
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg(ReturnAppResult.APP_SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error("同步定制云迹客户数据接口失败", e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    private synchronized CloudCustomerEntity getCloudCustomer(Map<String, Object> map) {
        String name = map.get("name").toString();
        String phone = map.get("phone").toString();
        String sex = map.get("sex").toString();
        String actSource = map.get("actSource").toString();
        String firstSource = map.get("firstSource").toString();
        String latestSource = map.get("latestSource").toString();
        String latestCall = map.get("latestCall").toString();
        String latestCallResult = map.get("latestCallResult").toString();
        String signUpHouseName = map.get("signupHouseName").toString();
        String cityCode = map.get("cityCode").toString();
        String cityName = map.get("cityName").toString();
        String crmId = map.get("crmId").toString();
        String bizPort = map.get("bizPort").toString();
        actSource = com.house365.web.util.StringUtils.StringFilter(actSource);

        String signupTime = map.get("signupTime").toString();
        CloudCustomerEntity entity = new CloudCustomerEntity();
        if (StringUtils.isNotBlank(signupTime)) {
            long time = Long.parseLong(signupTime);
            String data = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(time * 1000));
            entity.setSignupTime(data);
        } else {
            entity.setSignupTime("");
        }
        entity.setName(name);
        entity.setPhone(phone);
        entity.setBakPhone1("");
        entity.setBakPhone2("");
        entity.setBakPhone3("");
        if (StringUtils.isNotBlank(sex)) {
            entity.setSex(Integer.valueOf(sex));
        } else {
            entity.setSex(2);
        }
        entity.setCustomerType(1);
        entity.setActSource(actSource);
        entity.setFirstSource(firstSource);
        entity.setLatestSource(latestSource);
        entity.setCrmLatestCall(latestCall);
        entity.setCrmLatestCallResult(latestCallResult);
        entity.setStatus(0);
        entity.setCreateTime(new Date());
        entity.setCreater("云迹");
        entity.setUpdater("云迹");
        entity.setUpdateTime(new Date());
        switch (latestCallResult) {
            case "A":
                entity.setBuyIntention("1");
                break;
            case "B":
                entity.setBuyIntention("2");
                break;
            case "C":
                entity.setBuyIntention("3");
                break;
            case "D":
                entity.setBuyIntention("4");
                break;
            case "E":
                entity.setBuyIntention("5");
                break;
            default:
                entity.setBuyIntention("");
                break;
        }
        entity.setLastCallTime(null);
        entity.setManagerId(0);
        entity.setManagerName("");
        entity.setCityCode(cityCode);
        entity.setCityName(cityName);
        entity.setBizPort(bizPort);
        entity.setCrmId(crmId);
        entity.setActSourceId(0);
        entity.setRemark("");
        entity.setTraceStatus(1);
        entity.setCrmSync("1");
        entity.setHotlineCallTime(null);
        entity.setHotlineCallSpend("");
        entity.setOceanDate(null);
        entity.setIsDelete(0);
        entity.setLastManager("");
        entity.setBindTime(null);
        entity.setCustomerId(0);

        entity.setSignupHouseId("");
        entity.setSignupHouseName(signUpHouseName);
        entity.setSignupSourceId("");
        entity.setSignupSourceName("");
        entity.setOverTimeCount(0);
        entity.setVisitBackCount(0);
        entity.setWaitVisitCount(0);
        entity.setBoughtCount(0);
        entity.setIsabandon(0);
        entity.setAbandonLogId(0);
        entity.setAbandonTime(null);
        entity.setCreateSource("云迹");
        return entity;
    }

    private static 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() {

    }
}
