/**
 * Description: 公告WS接口
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-14 下午 17:27:17
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-14   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.NoticeEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.DomainObject;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.SpringContextUtil;
import com.house365.ws.beans.request.NoticeListRequest;
import com.house365.ws.beans.request.NoticeRequest;
import com.house365.ws.beans.request.UserListRequest;
import com.house365.ws.beans.response.NoticeListResponse;
import com.house365.ws.beans.response.NoticeResponse;
import com.house365.ws.beans.response.UserListResponse;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.interfaces.server.INotice;
import com.house365.ws.interfaces.server.IUser;
import com.house365.ws.service.interfaces.ICustomerService;
import com.house365.ws.service.interfaces.IDepartmentService;
import com.house365.ws.service.interfaces.INoticeService;
import com.house365.ws.system.ReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.house365.beans.common.MessageTypeEnum.NEWNOTICE;

/**
 * 公告WS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-14
 * @see
 * @since 1.0
 */
@Service("notice")
public class NoticeImpl implements INotice {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(NoticeImpl.class);

    private static final String CACHE_PRE = "notice_";

    /**
     * 公告服务对象
     */
    @Autowired
    INoticeService<NoticeEntity> noticeService;

    @Autowired
    IDepartmentService departmentService;

    @Autowired
    IUser userService;
    @Autowired
    ICustomerService customerService;


    /**
     * 公告列表查询
     *
     * @param request 公告列表查询请求
     * @return 公告列表查询响应
     */
    @Override
    public NoticeListResponse getNoticeList(NoticeListRequest request) {
        NoticeListResponse response = new NoticeListResponse();
        try {
            QueryParams<NoticeEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            queryParams.setOrderColumn("top desc ");
            queryParams.setOrderMode(" ,id desc");
            List<NoticeEntity> notices = noticeService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(notices);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 首页公告展示
     *
     * @param cityID
     * @return
     */
    @Override
    public NoticeListResponse getNoticeListForIndexPage(String cityID) {
        NoticeListResponse response = new NoticeListResponse();
        try {
            NoticeListRequest noticeListRequest = new NoticeListRequest();
            Map<String, Object> searchMap = new HashMap<>();
            searchMap.put("EQ_city", cityID);

            Page page = new Page(10);
            page.setCurrentPage(1);
            noticeListRequest.setParamMap(searchMap);
            noticeListRequest.setPaging(page);

            QueryParams<NoticeEntity> queryParams = new QueryParams<>();
            queryParams.setSearchParams(searchMap);
            queryParams.setPaging(page);
            queryParams.setOrderColumn("top desc ");
            queryParams.setOrderMode(" ,id desc");
            List<NoticeEntity> notices = noticeService.queryByPage(queryParams);

            Date threeDaysAgo = DateTimeUtils.getDaysAgo(new Date(), 3);
            for (NoticeEntity notice : notices) {
                if (notice.getTitle().length() > 12) {
                    notice.setTitle(notice.getTitle().substring(0, 12) + "...");
                }
                if (notice.getCreateTime().after(threeDaysAgo)) {
                    notice.setCity("new");
                }
            }

            response.setPaging(queryParams.getPaging());
            response.setObjectList(notices);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());

        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 保存公告
     *
     * @param request 公告请求
     * @return 保存公告响应
     */
    @Override
    public NoticeResponse addNotice(NoticeRequest request) {
        NoticeResponse response = new NoticeResponse();
        try {
            RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
            NoticeEntity entity = request.getEntity();
            noticeService.save(entity);
            redisUtils.deleteByKeyNew(CACHE_PRE + entity.getCity());
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());

            if (!Strings.isNullOrEmpty(entity.getCity())) {
                DomainObject o = departmentService.getById(Integer.valueOf(entity.getCity()));

                if (o != null) {
                    DepartmentEntity department = (DepartmentEntity) o;

                    //send wechat message
                    Map<String, Object> searchParams = new HashMap<>();
                    searchParams.put("LIKE_deptUrlPath", department.getUrlPath());
                    Page page = new Page(Integer.MAX_VALUE);
                    UserListRequest listRequest = new UserListRequest();
                    listRequest.setPaging(page);
                    listRequest.setOrderColumn("name");
                    listRequest.setOrderMode("asc");
                    listRequest.setSearchParams(searchParams);
                    UserListResponse userListResponse = userService.getUserList(listRequest);
                    List<UserEntity> userList = userListResponse.getObjectList();
                    List<String> userIds = new ArrayList<>();
                    for (UserEntity userEntity : userList) {
                        userIds.add(String.valueOf(userEntity.getId()));
                    }
                    if (!userIds.isEmpty()) {
                        Map<String, String> params = new HashMap<>();
                        params.put("noticeId", String.valueOf(entity.getId()));
                        String toUser = Joiner.on("|").join(userIds);
                        customerService.sendMessageToWechat(NEWNOTICE, toUser, params);
                    }
                }

            }

        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除公告通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除公告响应
     */
    @Override
    public NoticeResponse deleteNoticeById(Integer id) {
        NoticeResponse response = new NoticeResponse();
        try {
            RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
            NoticeEntity entity = noticeService.getById(id);
            noticeService.delete(id);
            redisUtils.deleteByKeyNew(CACHE_PRE + entity.getCity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改公告
     *
     * @param request 修改公告请求
     * @return 修改公告响应
     */
    @Override
    public NoticeResponse updateNotice(NoticeRequest request) {
        NoticeResponse response = new NoticeResponse();
        try {
            RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
            noticeService.update(request.getEntity());
            redisUtils.deleteByKeyNew(CACHE_PRE + request.getEntity().getCity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 通过ID获取公告
     *
     * @param id 唯一标识
     * @return 通过ID获取公告响应
     */
    @Override
    public NoticeResponse getNoticeById(Integer id) {
        NoticeResponse response = new NoticeResponse();
        try {
            NoticeEntity entity = noticeService.getById(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }


    /**
     * 以下均为自动生成
     */

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // TODO Auto-generated method stub
        return null;
    }

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