package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.OnlineLogEntity;
import com.house365.beans.entity.UserEntity;
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.web.util.DateTimeUtils;
import com.house365.ws.dao.mapper.OnlineLogMapper;
import com.house365.ws.dao.mapper.UserMapper;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections.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.util.*;

/**
 * 查询人员上下线信息
 *
 * @author Created by 365 on 2021/3/24.
 */
@Service("getOnlineLog")
public class GetOnlineLogImpl implements IGetOnlineLog {

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

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OnlineLogMapper logMapper;

    /**
     * 分时间段返回用户上下线信息
     *
     * @param parameter 服务输入，不包含服务配置和控制信息
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map<String, Object>> response = new House365RestResponse<>();
        // 业务层统一处理
        try {
            House365RestObject<Map<String, Object>> data = new House365RestObject<>();
            List<Map<String, Object>> list = new ArrayList<>();
            String time = getMapValueByKey("time", map, "");
            String city = getMapValueByKey("city", map, "");
            if (StringUtils.isBlank(time) || StringUtils.isBlank(city)) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("接口参数不全");
                return JSONObject.fromObject(response).toString();
            }

            Map<String, Object> queryMap = new HashMap<>(5);
            //测试临时新加部门，上线需要调整
            queryMap.put("deptId", 568);
//            queryMap.put("deptId", 557);
            List<UserEntity> userList = userMapper.queryByConditions(queryMap);
            if (CollectionUtils.isNotEmpty(userList)) {
                String patten = DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_FULL;
                userList.forEach(u -> {
                    Map<String, Object> dataMap = new HashMap<>(5);
                    Map<String, Object> searchMap = new HashMap<>(10);
                    String startTime = time + " 00:00:00";
                    String endTime = time + " 23:59:59";
                    searchMap.put("startTime", startTime);
                    searchMap.put("endTime", endTime);
                    searchMap.put("userId", u.getId());
                    List<OnlineLogEntity> logList = logMapper.queryByConditions(searchMap);
                    if (CollectionUtils.isNotEmpty(logList)) {
                        int size = logList.size();
                        int size1 = size / 2;
                        if (size1 >= 1) {
                            dataMap.put("userId", u.getId());
                            dataMap.put("accId", u.getAccId());
                            StringBuilder builder = new StringBuilder();
                            if (logList.get(0).getNewStatus() == 1) {
                                for (int i = 0; i <= size1; i++) {
                                    if (2 * (i + 1) <= size) {
                                        builder.append(DateTimeUtils.getDateString(logList.get(2 * i).getCreateTime(), patten)).append("---").append(DateTimeUtils.getDateString(logList.get(2 * i + 1).getCreateTime(), patten)).append(",");
                                    } else {
                                        if (2 * i != size) {
                                            builder.append(DateTimeUtils.getDateString(logList.get(2 * i).getCreateTime(), patten)).append("---").append(endTime);
                                        }
                                    }
                                }
                            } else {
                                builder.append(startTime).append("---").append(DateTimeUtils.getDateString(logList.get(0).getCreateTime(), patten)).append(",");
                                for (int i = 1; i <= size1; i++) {
                                    String timeEnd;
                                    if (2 * i == size) {
                                        timeEnd = endTime;
                                    } else {
                                        timeEnd = DateTimeUtils.getDateString(logList.get(2 * i).getCreateTime(), patten);
                                    }
                                    builder.append(DateTimeUtils.getDateString(logList.get(2 * i - 1).getCreateTime(), patten)).append("---").append(timeEnd).append(",");
                                }
                            }
                            dataMap.put("time", builder.toString());
                            list.add(dataMap);
                        } else {
                            dataMap.put("userId", u.getId());
                            dataMap.put("accId", u.getAccId());
                            StringBuilder builder = new StringBuilder();
                            if (logList.get(0).getNewStatus() == 1) {
                                builder.append(DateTimeUtils.getDateString(logList.get(0).getCreateTime(), patten)).append("---").append(endTime);
                            } else {
                                builder.append(startTime).append("---").append(DateTimeUtils.getDateString(logList.get(0).getCreateTime(), patten));
                            }
                            dataMap.put("time", builder.toString());
                            list.add(dataMap);
                        }
                    } else {
                        //当天没有日志记录时，往前推一个月查询是否有在线记录
                        Date date = DateTimeUtils.getDateByString(startTime, patten);
                        date = DateTimeUtils.getDaysAgo(date, 30);
                        String startTimeNew = DateTimeUtils.getDateString(date, patten);
                        searchMap.put("startTime", startTimeNew);
                        searchMap.put("endTime", endTime);
                        searchMap.put("userId", u.getId());
                        searchMap.put("order", 1);
                        List<OnlineLogEntity> logListNew = logMapper.queryByConditions(searchMap);
                        if (CollectionUtils.isNotEmpty(logListNew) && logListNew.get(0).getNewStatus() == 1) {
                            dataMap.put("userId", u.getId());
                            dataMap.put("accId", u.getAccId());
                            String timePeriod = startTime + "---" + endTime;
                            dataMap.put("time", timePeriod);
                            list.add(dataMap);
                        }
                    }

                });
            }
            data.setList(list);
            response.setResult("200");
            response.setMsg("查询成功");
            response.setData(data);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询用户上下线时间段失败", e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

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

    }
}
