package com.house365.ws.interfaces.impl;

import com.house365.beans.entity.CloudActivityEntity;
import com.house365.beans.entity.CloudCountEntity;
import com.house365.beans.entity.CloudCustomerEntity;
import com.house365.web.util.DateTimeUtils;
import com.house365.ws.beans.request.MapListRequest;
import com.house365.ws.beans.response.MapListResponse;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.dao.mapper.CloudActivityMapper;
import com.house365.ws.dao.mapper.CloudCountMapper;
import com.house365.ws.dao.mapper.CloudCustomerMapper;
import com.house365.ws.dao.mapper.UserMapper;
import com.house365.ws.interfaces.server.ICloudActivityInterface;
import com.house365.ws.service.interfaces.ICheckNoCallCustomerNoLimit;
import com.house365.ws.service.interfaces.IStaffDuty;
import com.house365.ws.system.ReturnResult;
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 java.text.DecimalFormat;
import java.util.*;

import static com.house365.ws.service.impl.StaffDuty.getMonthDate;

/**
 * @author Created by Administrator on 2020/3/26.
 */
@Service("CloudActivity")
public class CloudActivityImpl implements ICloudActivityInterface {

    private static final Logger logger = LoggerFactory.getLogger(CloudActivityImpl.class);

    @Autowired
    private CloudActivityMapper mapper;
    @Autowired
    private CloudCustomerMapper cloudCustomerMapper;
    @Autowired
    private RedisUtilsInterface redisUtil;
    @Autowired
    private IStaffDuty staffDuty;
    @Autowired
    private ICheckNoCallCustomerNoLimit checkNoCallCustomerNoLimit;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CloudCountMapper cloudCountMapper;

    @Override
    public MapListResponse list(MapListRequest request) {
        MapListResponse response = new MapListResponse();
        try {
            Map<String, Object> map = new HashMap<>(10);
            Map<String, Object> searchParams = request.getSearchParams();
            int start = 50 * (request.getPaging().getCurrentPage() - 1);
            map.put("city", searchParams.get("city"));
            map.put("start", start);
            map.put("limit", 50);
            map.put("name", searchParams.get("name"));
            int userId = Integer.parseInt(searchParams.get("userId").toString());
            if (userId != 1) {
                map.put("createId", userId);
            }

            List<Map<String, Object>> list = mapper.queryList(map);
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> m : list) {
                    int activeId = Integer.parseInt(m.get("id").toString());
                    Map<String, Object> searchMap = new HashMap<>(10);
                    searchMap.put("activeId", activeId);
                    List<CloudCustomerEntity> count = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("customerCount", count.size());
                    searchMap.put("type", 1);
                    List<CloudCustomerEntity> waitCountList = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("waitCount", waitCountList.size());
                    searchMap.put("type", 2);
                    List<CloudCustomerEntity> sentCountList = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("sentCount", sentCountList.size());
                    //置业顾问为空，则为公海客户
                    searchMap.put("isSea", 1);
                    List<CloudCustomerEntity> seaList = cloudCustomerMapper.queryByConditions(searchMap);
                    m.put("seaCount", seaList.size());

                    if (CollectionUtils.isNotEmpty(sentCountList)) {
                        //设置统计数目 已跟进  回公海  A/B意向数 约看数 到访数 认购数 签约数
                        String backKey = "cloud_back_count" + activeId;
                        String abKey = "cloud_ab_count" + activeId;
                        String seeKey = "cloud_see_count" + activeId;
                        String daoKey = "cloud_dao_count" + activeId;
                        String buyKey = "cloud_buy_count" + activeId;
                        String signKey = "cloud_sign_count" + activeId;
                        int backCount;
                        int abCount;
                        int seeCount;
                        int daoCount;
                        int buyCount;
                        int signCount;
                        if (!"null".equals(redisUtil.getValByKeyNew(backKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(backKey))) {
                            backCount = Integer.valueOf(redisUtil.getValByKeyNew(backKey));
                        } else {
                            backCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(abKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(abKey))) {
                            abCount = Integer.valueOf(redisUtil.getValByKeyNew(abKey));
                        } else {
                            abCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(seeKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(seeKey))) {
                            seeCount = Integer.valueOf(redisUtil.getValByKeyNew(seeKey));
                        } else {
                            seeCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(daoKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(daoKey))) {
                            daoCount = Integer.valueOf(redisUtil.getValByKeyNew(daoKey));
                        } else {
                            daoCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(buyKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(buyKey))) {
                            buyCount = Integer.valueOf(redisUtil.getValByKeyNew(buyKey));
                        } else {
                            buyCount = 0;
                        }
                        if (!"null".equals(redisUtil.getValByKeyNew(signKey)) && StringUtils.isNotBlank(redisUtil.getValByKeyNew(signKey))) {
                            signCount = Integer.valueOf(redisUtil.getValByKeyNew(signKey));
                        } else {
                            signCount = 0;
                        }
                        m.put("backCount", backCount);
                        m.put("abCount", abCount);
                        m.put("seeCount", seeCount);
                        m.put("daoCount", daoCount);
                        m.put("buyCount", buyCount);
                        m.put("signCount", signCount);
                    } else {
                        m.put("backCount", "0");
                        m.put("abCount", "0");
                        m.put("seeCount", "0");
                        m.put("daoCount", "0");
                        m.put("buyCount", "0");
                        m.put("signCount", "0");
                    }
                }
            }

            int count = mapper.queryCount(map);
            request.getPaging().setRecords(count);
            response.setPaging(request.getPaging());
            response.setObjectList(list);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(e.getMessage());
        }
        return response;
    }

//    @Override
//    public List<CloudCountEntity> reportList(Map<String, Object> searchParams) {
//        List<CloudCountEntity> list = new ArrayList<>();
//        try {
//            Date date = new Date();
//            String startTime = "";
//            String endTime = "";
//            String timeStart = "";
//            if(null != searchParams.get("startTime")){
//                timeStart = searchParams.get("startTime").toString();
//            }
//            if (StringUtils.isNotBlank(timeStart)) {
//                StringBuilder str = new StringBuilder().append(timeStart).append("-15").append(" 00:00:00");
//                String time = str.toString();
//                Date newDate = DateTimeUtils.getDateByString(time);
//                newDate =  DateTimeUtils.getUpdateDateTime(newDate,Calendar.MONTH,1);
//                Map<String, String> monthMap = getMonthDate(newDate);
//                startTime = monthMap.get("first");
//                endTime = monthMap.get("last");
//            } else {
//                Map<String, String> monthMap = getMonthDate(date);
//                startTime = monthMap.get("first");
//                endTime = monthMap.get("last");
//            }
//            Map<String, Object> map = new HashMap<>(10);
//            map.put("city", searchParams.get("city"));
//            map.put("name", searchParams.get("name"));
//            map.put("startTime", startTime);
//            map.put("endTime", endTime);
//            list = cloudCountMapper.queryByConditions(map);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return list;
//    }

    @Override
    public List<CloudCountEntity> reportList(Map<String, Object> searchParams) {
        List<CloudCountEntity> list = new ArrayList<>();
        try {
            Date date = new Date();
            String startTime = "";
            String endTime = "";
            if (null != searchParams.get("time")) {
                String time = searchParams.get("time").toString();
                startTime = time.split(",")[0];
                endTime = time.split(",")[1];
            }
            if (StringUtils.isBlank(startTime)) {
//                Map<String, String> monthMap = getMonthDate(date);
//                startTime = monthMap.get("first");
//                endTime = monthMap.get("last");
                return list;
            }
            Map<String, Object> map = new HashMap<>(10);
            if (null != searchParams.get("degree")) {
                String degree = searchParams.get("degree").toString();
                if ("y".equals(degree)) {
                    map.put("type", 3);
                } else if ("bn".equals(degree)) {
                    map.put("type", 2);
                } else if ("s".equals(degree)) {
                    map.put("type", 1);
                } else if ("m".equals(degree)) {
                    map.put("type", 0);
                }
            }
            map.put("city", searchParams.get("city"));
            map.put("name", searchParams.get("name"));
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            list = cloudCountMapper.queryByConditions(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public MapListResponse reportDetailList(MapListRequest request, int countId) {
        CloudCountEntity cloudCountEntity = cloudCountMapper.getById(countId);
        int type = cloudCountEntity.getType();
        MapListResponse response = new MapListResponse();
        Map<String, Object> map = new HashMap<>(10);
        Date date = cloudCountEntity.getCreateTime();
        date = DateTimeUtils.getUpdateDateTime(date, Calendar.MONTH, 1);
        Map<String, String> monthMap = getMonthDate(date);
        String startTime = "";
        String endTime = "";
        Date endDate;
        if (type == 0) {
            startTime = monthMap.get("first");
            endTime = monthMap.get("last");
        } else {
            Date createTime = cloudCountEntity.getCreateTime();
            createTime = DateTimeUtils.getUpdateDateTime(createTime, Calendar.DAY_OF_MONTH, -1);
            if (type == 1) {
                endDate = DateTimeUtils.getUpdateDateTime(createTime, Calendar.MONTH, 3);
            } else if (type == 2) {
                endDate = DateTimeUtils.getUpdateDateTime(createTime, Calendar.MONTH, 6);
            } else {
                endDate = DateTimeUtils.getUpdateDateTime(createTime, Calendar.MONTH, 12);
            }
            startTime = DateTimeUtils.getDateString(createTime, DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_FULL);
            endTime = DateTimeUtils.getDateString(endDate, DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_FULL);
        }
        Map<String, Object> searchParams = request.getSearchParams();
        map.put("city", searchParams.get("city"));
        int status = Integer.parseInt(searchParams.get("status").toString());
        int createId = Integer.parseInt(searchParams.get("createId").toString());
        map.put("createId", createId);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        List<CloudActivityEntity> activeListNew = mapper.queryByConditions(map);
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> subList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(activeListNew)) {
            List<Integer> actIdList = new ArrayList<>();
            for (CloudActivityEntity l : activeListNew) {
                actIdList.add(l.getId());
            }

            Map<String, Object> searchMap = new HashMap<>(10);
            searchMap.put("actIdList", actIdList);
            searchMap.put("type", 2);
            List<CloudCustomerEntity> sendList = cloudCustomerMapper.queryByConditions(searchMap);

            if (CollectionUtils.isNotEmpty(sendList)) {
                Map<String, Object> queryMap = new HashMap<>(10);
                queryMap.put("status", status);
                queryMap.put("createId", createId);
                queryMap.put("startTime", startTime);
                queryMap.put("endTime", endTime);
                list = staffDuty.queryListByStatus(sendList, queryMap);
                int total = list.size();

                //手动分页，需要先查出全部然后筛选重新分页
                for (int i = 0; i <= total; i++) {
                    // 开始索引
                    int currentPage = request.getPaging().getCurrentPage();
                    int fromIndex = (currentPage - 1) * request.getPaging().getPageSize();
                    // 结束索引
                    int toIndex = fromIndex + request.getPaging().getPageSize();
                    // 如果结束索引大于集合的最大索引，那么规定结束索引=集合大小
                    if (toIndex > total) {
                        toIndex = total;
                    }
                    if (fromIndex <= total) {
                        subList = list.subList(fromIndex, toIndex);
                        if (toIndex >= fromIndex) {
                            break;
                        }
                    }
                }
            }
        }
        int count = list.size();
        request.getPaging().setRecords(count);
        response.setPaging(request.getPaging());
        response.setObjectList(subList);
        response.setResultCode(ReturnResult.SUCCESS.getResultCode());
        response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        return response;
    }

    @Override
    public List<CloudActivityEntity> queryByConditions(Map<String, Object> map) {
        List<CloudActivityEntity> list = mapper.queryByConditions(map);
        if (CollectionUtils.isNotEmpty(list)) {
            return list;
        }
        return Collections.emptyList();
    }

    @Override
    public void setCloudCount() {
        staffDuty.setCloudCount();
    }

    @Override
    public void startBackNoVisitToSea() {
        checkNoCallCustomerNoLimit.backNoVisitToSea();
    }

    @Override
    public void putExterCusToCrm() {
        staffDuty.putExterCusToCrm();
    }

    @Override
    public void setCloudReportCount(int type) {
        if (type == 0) {
            staffDuty.setCloudReportCount();
        } else if (type == 1) {
            staffDuty.setCloudReportCountJi();
        } else if (type == 2) {
            staffDuty.setCloudReportCountBn();
        } else if (type == 3) {
            staffDuty.setCloudReportCountYear();
        }
    }

    @Override
    public void addCloudActivityNew() {
        staffDuty.addCloudActivityNew();
    }

    @Override
    public void updateStatus() {
        staffDuty.updateJgStatus();
    }

    @Override
    public void updateDutyStaff() {
        staffDuty.updateDutyStaff();
    }

    @Override
    public void addMarketActivity() {
        staffDuty.addMarketActivity();
    }

    private String dealRate(int count1, int count2) {
        String rate = "";
        if (count1 > 0 && count2 > 0) {
            double d = (double) count1 / count2;
            DecimalFormat df = new DecimalFormat("0.00%");
            rate = df.format(d);
        }
        return rate;
    }

    private void setPutMap(Map<String, Object> putMap) {
        putMap.put("backCount", 0);
        putMap.put("backRate", "");
        putMap.put("abCount", 0);
        putMap.put("abRate", "");
        putMap.put("seeCount", 0);
        putMap.put("seeRate", "");
        putMap.put("daoCount", 0);
        putMap.put("daoRate", "");
        putMap.put("buyCount", 0);
        putMap.put("signCount", 0);
        putMap.put("successCount", 0);
        putMap.put("successRate", "");
    }
}
