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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.house365.beans.entity.BaseAttachment;
import com.house365.beans.entity.ProjectEntity;
import com.house365.beans.entity.ProjectSalerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.system.QueryParams;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.beans.request.ProjectSalerListRequest;
import com.house365.ws.beans.request.ProjectSalerRequest;
import com.house365.ws.beans.response.ProjectSalerListResponse;
import com.house365.ws.beans.response.ProjectSalerResponse;
import com.house365.ws.beans.response.UserResponse;
import com.house365.ws.dao.interfaces.IProjectSalerDao;
import com.house365.ws.interfaces.server.IProjectSaler;
import com.house365.ws.interfaces.server.IUser;
import com.house365.ws.service.interfaces.IAttachmentService;
import com.house365.ws.service.interfaces.IProjectSalerService;
import com.house365.ws.service.interfaces.IProjectService;
import com.house365.ws.service.interfaces.IUserService;
import com.house365.ws.system.ReturnResult;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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.text.SimpleDateFormat;
import java.util.*;


/**
 * ProjectSalerWS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2018-01-23
 * @see
 * @since 1.0
 */
@Service("projectSaler")
public class ProjectSalerImpl implements IProjectSaler {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(ProjectSalerImpl.class);

    /**
     * ProjectSaler服务对象
     */
    @Autowired
    IProjectSalerService<ProjectSalerEntity> projectSalerService;

    @Autowired
    IProjectService projectService;

    @Autowired
    IUserService userService;

    @Autowired
    IAttachmentService attachmentService;

    @Autowired
    private IUser user;

    @Autowired
    private IProjectSalerDao saleDao;

    /**
     * ProjectSaler列表查询
     *
     * @param request ProjectSaler列表查询请求
     * @return ProjectSaler列表查询响应
     */
    @Override
    public ProjectSalerListResponse getProjectSalerList(ProjectSalerListRequest request) {
        ProjectSalerListResponse response = new ProjectSalerListResponse();
        try {
            QueryParams<ProjectSalerEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<ProjectSalerEntity> projectSalers = projectSalerService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(projectSalers);
            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;
    }

    /**
     * 保存ProjectSaler
     *
     * @param request ProjectSaler请求
     * @return 保存ProjectSaler响应
     */
    @Override
    public ProjectSalerResponse addProjectSaler(ProjectSalerRequest request) {
        ProjectSalerResponse response = new ProjectSalerResponse();
        try {
            ProjectSalerEntity entity = request.getEntity();
            projectSalerService.save(entity);
            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;
    }

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

    /**
     * 修改ProjectSaler
     *
     * @param request 修改ProjectSaler请求
     * @return 修改ProjectSaler响应
     */
    @Override
    public ProjectSalerResponse updateProjectSaler(ProjectSalerRequest request) {
        ProjectSalerResponse response = new ProjectSalerResponse();
        try {
            projectSalerService.update(request.getEntity());
            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获取ProjectSaler
     *
     * @param id 唯一标识
     * @return 通过ID获取ProjectSaler响应
     */
    @Override
    public ProjectSalerResponse getProjectSalerById(Integer id) {
        ProjectSalerResponse response = new ProjectSalerResponse();
        try {
            ProjectSalerEntity entity = projectSalerService.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 List<UserEntity> queryUserByPrjId(Integer projectId, String city) {
        return projectSalerService.queryUserByPrjId(projectId, city);
    }

    @Override
    public void deleteByProjectId(Integer projectId) {
        projectSalerService.deleteByProjectId(projectId);
    }

    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @Override
    public void doBindSaler(UserEntity userEntity, String userIds, String projectIds) throws ServiceException {

        if (Strings.isNullOrEmpty(userIds) || Strings.isNullOrEmpty(projectIds)) {
            throw new ServiceException("参数错误");
        }

        String[] split = projectIds.split(",");
        Map<String, ProjectEntity> projectMap = new HashMap<>();
        ProjectEntity projectEntity = null;
        Integer projectId;
        if (",".equals(userIds)) {
            //delete all
            for (String tmp : split) {
                projectId = Integer.valueOf(tmp);
                deleteByProjectId(projectId);
            }
        } else {
            //delete and create
            String[] userIdArray = userIds.split(",");
            List<String> userIdList = Arrays.asList(userIdArray);
            for (String tmp : split) {
                projectId = Integer.valueOf(tmp);
                deleteByProjectId(projectId);
                ProjectSalerEntity entity = null;

                //get project and cache
                if (projectMap.containsKey(tmp) && null != projectMap.get(tmp)) {
                    projectEntity = projectMap.get(tmp);
                } else {
                    projectEntity = (ProjectEntity) projectService.getById(projectId);
                    if (projectEntity != null) {
                        projectMap.put(tmp, projectEntity);
                    }
                }

                if (null != projectEntity) {
                    for (String userId : userIdList) {
                        if (!Strings.isNullOrEmpty(userId)) {
                            UserEntity ue = (UserEntity) userService.getById(Integer.valueOf(userId));
                            if (null != ue) {
                                List<BaseAttachment> headImg = attachmentService.queryByResourceIdAndResouceType(
                                        String.valueOf(ue.getId()), "hgs_user_headImg");
                                List<BaseAttachment> fullImg = attachmentService.queryByResourceIdAndResouceType(
                                        String.valueOf(ue.getId()), "hgs_user_fullImg");

                                if (Strings.isNullOrEmpty(ue.getHotlinephone()) || Strings.isNullOrEmpty(
                                        ue.getGoodat()) || Strings.isNullOrEmpty(
                                        ue.getDescription()) || headImg == null || headImg.isEmpty() || null == fullImg || fullImg.isEmpty()) {
                                    throw new ServiceException("请先完善该直销人员信息");
                                }

                                //头像路径同步到user表，方便查询
                                if (Strings.isNullOrEmpty(ue.getHeadImgURL()) || Strings.isNullOrEmpty(
                                        ue.getFullImgURL())) {
                                    ue.setHeadImgURL(headImg.get(0).getRemotePath());
                                    ue.setFullImgURL(fullImg.get(0).getRemotePath());
                                    userService.update(ue);
                                }

                                entity = newProjectSalerEntity(projectEntity, ue, userEntity);
                                projectSalerService.save(entity);

                            } else {
                                throw new ServiceException("用户不存在");
                            }
                        }
                    }
                } else {
                    throw new ServiceException("项目不存在");
                }

            }
        }
    }

    private ProjectSalerEntity newProjectSalerEntity(ProjectEntity projectEntity, UserEntity bindUser, UserEntity createUser) {
        ProjectSalerEntity entity = new ProjectSalerEntity();
        entity.setUserId(bindUser.getId());
        entity.setUserName(bindUser.getRealName());
        entity.setProjectId(projectEntity.getBuildingId());
        entity.setProjectName(projectEntity.getBuildingName());
        entity.setProjectCode(projectEntity.getContractCode());
        entity.setChannel(projectEntity.getType());
        entity.setCity(projectEntity.getCity());

        Date date = new Date();
        entity.setCreateTime(date);
        entity.setUpdateTime(date);
        entity.setCreateUserid(createUser.getId());
        entity.setCreateUsername(createUser.getRealName());
        entity.setUpdateUserid(createUser.getId());
        entity.setUpdateUsername(createUser.getRealName());
        return entity;
    }

    @Override
    public List<ProjectSalerEntity> queryAllList() {
        return projectSalerService.queryAllList();
    }

    @Override
    @Transactional
    public String syncData(List<ProjectSalerEntity> list) {
        if (CollectionUtils.isNotEmpty(list)) {
            for (ProjectSalerEntity l : list) {
//            list.forEach(l -> {
                UserResponse response = user.getUserById(l.getUserId());
                if (response != null) {
                    UserEntity userEntity = response.getEntity();
                    String telephone = userEntity.getMobile();
                    if (StringUtils.isBlank(l.getProjectCode())) {
                        l.setProjectCode("test");
                    }
                    List<NameValuePair> directParams = new ArrayList<>();
                    directParams.add(new BasicNameValuePair("serviceCode", "TaoFangHui"));
                    directParams.add(new BasicNameValuePair("serviceName", "syncData"));
                    directParams.add(new BasicNameValuePair("telephone", telephone));
                    directParams.add(new BasicNameValuePair("userId", l.getUserId().toString()));
                    directParams.add(new BasicNameValuePair("userName", l.getUserName()));

                    directParams.add(new BasicNameValuePair("projectId", l.getProjectId().toString()));
                    directParams.add(new BasicNameValuePair("projectName", l.getProjectName()));
                    directParams.add(new BasicNameValuePair("projectCode", l.getProjectCode()));
                    directParams.add(new BasicNameValuePair("channel", l.getChannel()));
                    directParams.add(new BasicNameValuePair("city", l.getCity()));

                    directParams.add(new BasicNameValuePair("createUserId", l.getCreateUserid().toString()));
                    directParams.add(new BasicNameValuePair("createUserName", l.getCreateUsername()));
                    directParams.add(new BasicNameValuePair("updateUserId", l.getUpdateUserid().toString()));
                    directParams.add(new BasicNameValuePair("updateUserName", l.getUpdateUsername()));
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String createTime = formatter.format(l.getCreateTime());
                    String updateTime = formatter.format(l.getUpdateTime());
                    directParams.add(new BasicNameValuePair("createTime", createTime));
                    directParams.add(new BasicNameValuePair("updateTime", updateTime));
                    try {
                        String result = HttpClientUtil.doGet(MemoryPropertyPlaceholderConfigurer.getContextProperty("tangfanghui.server.url"), directParams);
                        if (result != null) {
                            ObjectMapper objectMapper = new ObjectMapper();
                            Map<String, Object> map1 = objectMapper.readValue(result, Map.class);
                            String code = (String) map1.get("result");
                            if (code.equals("1")) {
                                saleDao.updateStatus(l.getId());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        LOGGER.error("调取淘房汇同步数据接口失败");
                    }
                }

            }
        }
        return null;
    }

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

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