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

import com.house365.beans.entity.ProjectEntity;
import com.house365.beans.entity.ProjectUserEntity;
import com.house365.beans.entity.UserEntity;
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.ws.beans.request.ProjectListRequest;
import com.house365.ws.beans.request.ProjectRequest;
import com.house365.ws.beans.response.ProjectListResponse;
import com.house365.ws.beans.response.ProjectResponse;
import com.house365.ws.dao.mapper.ProjectMapper;
import com.house365.ws.interfaces.server.IProject;
import com.house365.ws.service.interfaces.IProjectService;
import com.house365.ws.service.interfaces.IProjectUserService;
import com.house365.ws.system.ReturnResult;
import com.house365.ws.util.OperateLogUtils;
import org.apache.commons.collections4.CollectionUtils;
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.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

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

    /**
     * Project服务对象
     */
    @Autowired
    private IProjectService<ProjectEntity> projectService;
    @Autowired
    private IProjectUserService<ProjectUserEntity> projectUserService;
    @Autowired
    private OperateLogUtils logUtils;
    @Autowired
    private ProjectMapper projectMapper;

    @Override
    public List<ProjectEntity> getProjectListByUserId(Integer userId, String cityCode) {
        List<ProjectEntity> projects = projectUserService.getProjectByUserId(userId, cityCode);
        if (CollectionUtils.isNotEmpty(projects)) {
            return projects;
        }
        return Collections.emptyList();
    }

    @Override
    public List<ProjectEntity> getProjectListByUserId(Integer userId, String cityCode, String showStatus) {
        List<ProjectEntity> projects = projectUserService.getProjectByUserId(userId, cityCode, showStatus);
        if (CollectionUtils.isNotEmpty(projects)) {
            return projects;
        }
        return Collections.emptyList();
    }

    /**
     * Project列表查询
     *
     * @param request Project列表查询请求
     * @return Project列表查询响应
     */
    @Override
    public ProjectListResponse getProjectList(ProjectListRequest request) {
        ProjectListResponse response = new ProjectListResponse();
        try {
            QueryParams<ProjectEntity> queryParams = new QueryParams<>(request.getSearchParams());
            Page page = request.getPaging();
            queryParams.setPaging(page);
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<ProjectEntity> projects = projectService.queryByPage(queryParams);
            if (CollectionUtils.isNotEmpty(projects)) {
                List<Integer> projectIds = new LinkedList<>();
                for (ProjectEntity projectEntity : projects) {
                    projectIds.add(projectEntity.getId());
                }
                List<UserEntity> projectUsers = projectUserService.getProjectUser(projectIds);
                for (UserEntity userEntity : projectUsers) {
                    for (ProjectEntity projectEntity : projects) {
                        if (userEntity.getProjectId().intValue() == projectEntity.getId()) {
                            projectEntity.setUserName(
                                    (projectEntity.getUserName() == null ? "" : (projectEntity.getUserName() + ",")) + userEntity.getRealName());
                        }
                    }
                }
            }
            response.setPaging(queryParams.getPaging());
            response.setObjectList(projects);
            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;
    }

    /**
     * 保存Project
     *
     * @param request Project请求
     * @return 保存Project响应
     */
    @Override
    public ProjectResponse addProject(ProjectRequest request, int userId, String userName) {
        ProjectResponse response = new ProjectResponse();
        try {
            ProjectEntity entity = request.getEntity();
            int id = projectService.save(entity);
            //新增项目日志（type 1 新增）
            logUtils.saveProjectLog(id, 1, userId, userName);
            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;
    }

    /**
     * 删除Project通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除Project响应
     */
    @Override
    public ProjectResponse deleteProjectById(Integer id) {
        ProjectResponse response = new ProjectResponse();
        try {
            projectService.delete(id);
            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;
    }

    /**
     * 修改Project
     *
     * @param request 修改Project请求
     * @return 修改Project响应
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public ProjectResponse updateProject(ProjectRequest request, int userId, String userName) {
        ProjectResponse response = new ProjectResponse();
        try {
            //记录项目更新日志
            int id = request.getEntity().getId();
            ProjectEntity oldEntity = projectService.getById(id);
            projectService.update(request.getEntity());
            ProjectEntity newEntity = projectService.getById(id);
            logUtils.recordOperateLog(oldEntity, newEntity, id, userId, userName);
            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;
    }

    /**
     * 每次修改project表时根据type字段同步刷新project_saler表channel字段
     * by wenjiaxin
     */
    @Override
    public void updateSaler() {
        projectService.updateSaler();
    }

    /**
     * 通过ID获取Project
     *
     * @param id 唯一标识
     * @return 通过ID获取Project响应
     */
    @Override
    public ProjectResponse getProjectById(Integer id) {
        ProjectResponse response = new ProjectResponse();
        try {
            ProjectEntity entity = projectService.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 ProjectListResponse queryCustomerProject(Integer customerId) {
        ProjectListResponse projectListResponse = new ProjectListResponse();
        List<ProjectEntity> projectEntities = projectService.queryCustomerProject(customerId);
        projectListResponse.setObjectList(projectEntities);
        return projectListResponse;
    }

    @Override
    public void updateHotline(String buildingId, String shorttel) {
        projectService.updateHotline(buildingId, shorttel);
    }

    @Override
    public List<ProjectEntity> queryByConditions(Map<String, Object> map) {
        return projectService.queryByConditions(map);
    }

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

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

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