/**
 * Description: 角色控制器
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-09-14 下午 17:27:20
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-09-14   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.house365.beans.entity.*;
import com.house365.beans.system.Page;
import com.house365.beans.vo.RoleVo;
import com.house365.beans.vo.UserVo;
import com.house365.rest.exception.ServiceException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.*;
import com.house365.ws.beans.request.*;
import com.house365.ws.beans.response.*;
import com.house365.ws.interfaces.server.*;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
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.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;


/**
 * 角色控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-09-14
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 自动注入角色WS实现
     */
    @Autowired
    private IRole role;

    @Autowired
    private IPermission permission;

    @Autowired
    private IWeChatPermission weChatPermission;

    @Autowired
    private IRolePermission rolePermission;

    @Autowired
    private IDepartment department;

    @Autowired
    private IUserRole userRole;

    @Autowired
    private IUser user;

    @Autowired
    private ICustomer customer;

    @Autowired
    private IAttachmentInterface attachmentInterface;


    /**
     * 去新增角色
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增角色
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createRole(
            @Valid RoleVo vo, BindingResult result, RedirectAttributes redirectAttributes, HttpServletRequest httpRequest,
            Model model
    ) {
        UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        DepartmentEntity currDept = (DepartmentEntity) httpRequest.getSession().getAttribute(
                SessionConstants.SESSION_CURRNET_DEPT_KEY);

        RoleEntity entity = vo.getEntity();
        Date date = new Date();
        entity.setDeptId(currDept.getId());
        entity.setDeptUrlPath(PathUtil.extractDeptPath(currDept.getUrlPath()));
        entity.setCreateUserid(userEntity.getId());
        entity.setCreateUsername(userEntity.getName());
        entity.setCreateTime(date);
        entity.setUpdateUserid(userEntity.getId());
        entity.setUpdateUsername(userEntity.getName());
        entity.setUpdateTime(date);
        entity.setEnabled(true);
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                RoleRequest request = new RoleRequest();
                request.setEntity(entity);
                RoleResponse response = role.addRole(request);
                Integer id = response.getEntity().getId();
                return "redirect:/role/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除角色
     *
     * @param id 角色页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id, HttpServletResponse httpResponse) {
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                if (checkRoleUserExists(Arrays.asList(ids))) {
                    try {
                        httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "权限组下面存在关联用户，不可删除！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                for (int i = 0; i < ids.length; i++) {
                    role.deleteRoleById(Integer.valueOf(ids[i]));
                }
            } else {
                if (checkRoleUserExists(id)) {
                    try {
                        httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "权限组下面存在关联用户，不可删除！");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return;
                }
                role.deleteRoleById(Integer.valueOf(id));
            }
        }
    }

    private boolean checkRoleUserExists(List<String> roleId) {
        for (String rid : roleId) {
            if (checkRoleUserExists(rid)) {
                return true;
            }
        }
        return false;
    }

    private boolean checkRoleUserExists(String roleId) {
        UserRoleListRequest req = new UserRoleListRequest();
        req.setPaging(new Page(1));
        Map<String, Object> paraMap = new HashMap<>(5);
        paraMap.put("EQ_roleId", roleId);
        req.setSearchParams(paraMap);
        UserRoleListResponse userRoleList = userRole.getUserRoleList(req);
        if (userRoleList.getObjectList().size() > 0) {
            return true;
        }
        return false;

    }

    /**
     * 去查看角色
     *
     * @param id 角色页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        RoleResponse response = role.getRoleById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改角色
     *
     * @param id 角色页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        RoleResponse response = role.getRoleById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改角色
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateRole(
            @Valid RoleVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            HttpServletRequest httpRequest, Model model
    ) {
        RoleEntity entity = vo.getEntity();

        UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        entity.setUpdateUserid(userEntity.getId());
        entity.setUpdateUsername(userEntity.getName());
        entity.setUpdateTime(new Date());

        model.addAttribute("entity", entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                RoleRequest request = new RoleRequest();
                request.setEntity(entity);
                role.updateRole(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/role/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询角色
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        DepartmentEntity dept = (DepartmentEntity) request.getSession().getAttribute(SessionConstants.SESSION_CURRNET_DEPT_KEY);

        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        searchParams.put("EQ_deptId", dept.getId());
        Page page = new Page(20);
        if (null != number) {
            page.setCurrentPage(number);
        }
        RoleListRequest listRequest = new RoleListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        RoleListResponse response = role.getRoleList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("roles", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = "authorize/{id}", method = RequestMethod.GET)
    public String authorize(
            @PathVariable Integer id, HttpServletRequest httpRequest, Model model
    ) {
        RoleEntity roleEntity = role.getRoleById(id).getEntity();
        PermissionListRequest permissionListRequest = new PermissionListRequest();
        permissionListRequest.setPaging(new Page(Integer.MAX_VALUE));
        Map<String, Object> searchMap = new HashMap<>(10);
        if (!PathUtil.isAdminDept(roleEntity.getDeptUrlPath())) {
            searchMap.put("EQ_special", false);
        }
        permissionListRequest.setSearchParams(searchMap);
        permissionListRequest.setOrderColumn("parentId asc,orderNum");
        permissionListRequest.setOrderMode("asc");
        PermissionListResponse permissionList = permission.getPermissionList(permissionListRequest);

        WeChatPermissionListRequest weChatPermissionListRequest = new WeChatPermissionListRequest();
        weChatPermissionListRequest.setPaging(new Page(Integer.MAX_VALUE));
        weChatPermissionListRequest.setOrderColumn("parentId");
        weChatPermissionListRequest.setOrderMode("asc");
        WeChatPermissionListResponse wechatPermissionList = weChatPermission.getPermissionList(
                weChatPermissionListRequest);

        RolePermissionListRequest rolePermissionListRequest = new RolePermissionListRequest();
        rolePermissionListRequest.setPaging(new Page(Integer.MAX_VALUE));
        Map<String, Object> paraMap = new HashMap<>(10);
        paraMap.put("EQ_roleId", id);
        rolePermissionListRequest.setSearchParams(paraMap);
        RolePermissionListResponse rolePermissionList = rolePermission.getRolePermissionList(rolePermissionListRequest);

        List<PermissionEntity> permissions = permissionList.getObjectList();
        List<RolePermissionEntity> rolePermissions = rolePermissionList.getObjectList();
        for (PermissionEntity permissionEntity : permissions) {
            permissionEntity.setAuthorized(false);
            for (RolePermissionEntity rolePermissionEntity : rolePermissions) {
                if (rolePermissionEntity.getPermissionId().intValue() == permissionEntity.getId().intValue()) {
                    permissionEntity.setAuthorized(true);
                }
            }
        }

        //menu tree
        PermissionTreeEntity permissionTree = new PermissionTreeEntity(true);
        PermissionEntity root = new PermissionEntity();
        root.setId(0);
        permissionTree.setEntity(root);

        //func tree
        PermissionTreeEntity funcTree = new PermissionTreeEntity(true);
        PermissionEntity funcRoot = new PermissionEntity();
        funcRoot.setId(0);
        funcTree.setEntity(funcRoot);

        for (PermissionEntity permissionEntity : permissions) {
            if (1 == permissionEntity.getType()) {
                permissionTree.add(permissionEntity);
            }
            if (2 == permissionEntity.getType()) {
                funcTree.add(permissionEntity);
            }
        }

        List<PermissionEntity> list = permissionTree.toList();
        List<PermissionEntity> funcList = funcTree.toList();

        //wechat list
        List<WeChatPermissionEntity> weChatPermissions = wechatPermissionList.getObjectList();
        for (WeChatPermissionEntity weChatPermissionEntity : weChatPermissions) {
            weChatPermissionEntity.setAuthorized(false);
            for (RolePermissionEntity rolePermissionEntity : rolePermissions) {
                if (rolePermissionEntity.getPermissionId().intValue() == weChatPermissionEntity.getId().intValue()) {
                    weChatPermissionEntity.setAuthorized(true);
                }
            }
        }

        PermissionTreeEntity wePermissionTree = new PermissionTreeEntity(true);
        WeChatPermissionEntity weroot = new WeChatPermissionEntity();

        weroot.setId(0);
        weroot.setHierarchy(-1);
        wePermissionTree.setWeChatEntity(weroot);
        for (WeChatPermissionEntity wepermissionEntity : weChatPermissions) {
            wePermissionTree.addWeEntity(wepermissionEntity);
        }
        List<WeChatPermissionEntity> welist = wePermissionTree.toWechatShowList();

        model.addAttribute("permissions", list);
        model.addAttribute("wepermissions", welist);
        model.addAttribute("funcList", funcList);
        model.addAttribute("roleId", id);
        return getAutoUrl();
    }

    @RequestMapping(value = "/roleListSection/{userId}")
    public String roleListSection(
            @PathVariable Integer userId, HttpServletRequest request, Model model
    ) {
        UserRoleListRequest userRoleListRequest = new UserRoleListRequest();
        userRoleListRequest.setPaging(new Page(Integer.MAX_VALUE));
        Map<String, Object> paraMap = new HashMap<>(10);
        paraMap.put("EQ_userId", userId);
        userRoleListRequest.setSearchParams(paraMap);

        UserRoleListResponse userRoleResponse = userRole.getUserRoleList(userRoleListRequest);
        model.addAttribute("userRole", userRoleResponse.getObjectList());
        return getAutoUrl();
    }

    @RequestMapping(value = "/edit/{id}", method = {RequestMethod.GET})
    public String editForm(@PathVariable(value = "id") Integer id, Model model) {
        UserResponse response = user.getUserById(id);

        UserRoleListRequest userRoleListRequest = new UserRoleListRequest();
        userRoleListRequest.setPaging(new Page(Integer.MAX_VALUE));
        Map<String, Object> paraMap = new HashMap<>(10);
        paraMap.put("EQ_userId", id);
        userRoleListRequest.setSearchParams(paraMap);
        StringBuilder roles = new StringBuilder("");
        UserRoleListResponse userRoleResponse = userRole.getUserRoleList(userRoleListRequest);
        if (userRoleResponse.getObjectList() != null && !userRoleResponse.getObjectList().isEmpty()) {
            for (UserRoleEntity ur : userRoleResponse.getObjectList()) {
                roles.append(ur.getRoleName()).append(",");
            }
        }
        String deptName = "";
        UserEntity userEntity = response.getEntity();
        if (null != userEntity.getDeptId()) {
            DepartmentResponse dr = department.getDepartmentById(userEntity.getDeptId());
            if (dr.getEntity() != null) {
                deptName = dr.getEntity().getName();
            }
        }

        AttachmentListResponse headImgRes = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id),
                "hgs_user_headImg");
        if (null != headImgRes.getObjectList() && !headImgRes.getObjectList().isEmpty()) {
            BaseAttachment attachment = (BaseAttachment) headImgRes.getObjectList().get(0);
            userEntity.setHeadImgURL(attachment.getRemotePath());
        } else {
            userEntity.setHeadImgURL("");
        }

        AttachmentListResponse fullImgRes = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id),
                "hgs_user_fullImg");
        if (null != fullImgRes.getObjectList() && !fullImgRes.getObjectList().isEmpty()) {
            BaseAttachment attachment = (BaseAttachment) fullImgRes.getObjectList().get(0);
            userEntity.setFullImgURL(attachment.getRemotePath());
        } else {
            userEntity.setFullImgURL("");
        }

        AttachmentListResponse wxImg = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id), "wx_code_imgUrl");
        if (null != wxImg.getObjectList() && CollectionUtils.isNotEmpty(wxImg.getObjectList())) {
            BaseAttachment attachment = (BaseAttachment) wxImg.getObjectList().get(0);
            userEntity.setWxCodeImgUrl(attachment.getRemotePath());
        }else {
            userEntity.setWxCodeImgUrl("");
        }

        model.addAttribute("deptName", deptName);
        model.addAttribute("roleName", roles.toString().endsWith(",") ? roles.toString().substring(0,
                roles.toString().length() - 1) : roles.toString());
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("edit");
    }

    @RequestMapping(value = "/updateInfo/{id}", method = {RequestMethod.POST})
    public String updateInfo(
            @Valid UserVo vo, BindingResult result, @PathVariable Integer id, RedirectAttributes redirectAttributes,
            Model model, HttpServletRequest httpRequest
    ) {
        UserEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                String mobile = Strings.isNullOrEmpty(vo.getEntity().getMobile()) ? "" : vo.getEntity().getMobile();
                String name = Strings.isNullOrEmpty(vo.getEntity().getRealName()) ? "" : vo.getEntity().getRealName();
                String goodAt = Strings.isNullOrEmpty(vo.getEntity().getGoodat()) ? "" : vo.getEntity().getGoodat();
                String description = Strings.isNullOrEmpty(
                        vo.getEntity().getDescription()) ? "" : vo.getEntity().getDescription();
                String position = Strings.isNullOrEmpty(
                        vo.getEntity().getPosition()) ? "" : vo.getEntity().getPosition();

                Integer defaultVisit = vo.getEntity().getDefaultVisit();

                if (defaultVisit == null) {
                    defaultVisit = 0;
                }
                if(org.apache.commons.lang3.StringUtils.isBlank(entity.getWxNumber())){
                    throw new Exception("个人微信不能为空!");
                }

                UserResponse ur = user.getUserById(id);
                if (ur.getEntity() != null) {
                    UserEntity ue = ur.getEntity();
                    if (!Strings.isNullOrEmpty(ue.getGoodat()) && Strings.isNullOrEmpty(entity.getGoodat())) {
                        throw new Exception("业务专长不可为空!");
                    }
                    if (!Strings.isNullOrEmpty(ue.getDescription()) && Strings.isNullOrEmpty(entity.getDescription())) {
                        throw new Exception("个人介绍不可为空!");
                    }
                    AttachmentListResponse wxImg = attachmentInterface.queryByResourceIdAndResouceType(String.valueOf(id), "wx_code_imgUrl");
                    if (null != wxImg.getObjectList() && CollectionUtils.isNotEmpty(wxImg.getObjectList())) {
                        BaseAttachment attachment = (BaseAttachment) wxImg.getObjectList().get(0);
                        ue.setWxCodeImgUrl(attachment.getRemotePath());
                    }else {
                        throw new Exception("微信二维码不能为空!");
                    }

                    ue.setMobile(mobile);
                    ue.setRealName(name);
                    ue.setPosition(position);
                    ue.setGoodat(goodAt);
                    ue.setDescription(description);
                    ue.setDefaultVisit(defaultVisit);
                    UserRequest request = new UserRequest();
                    UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
                    ue.setUpdateUserid(userEntity.getId());
                    ue.setUpdateUsername(userEntity.getName());
                    ue.setUpdateTime(new Date());
                    ue.setWxNumber(entity.getWxNumber());
                    request.setEntity(ue);

                    UserResponse userRsp = user.getUserById(entity.getId());
                    UserEntity tmpEntity = userRsp.getEntity();
                    if (tmpEntity != null && !StringUtils.isEmpty(tmpEntity.getRealName()) && !StringUtils.isEmpty(
                            entity.getRealName()) && !tmpEntity.getRealName().equals(entity.getRealName())) {
                        customer.updateManager(entity.getId(), entity.getRealName());
                    }

                    user.updateUserAndSyncToWechat(request);
                }

                redirectAttributes.addAttribute("message", "更新成功");
                //通知IM头像修改
                String deciceId = com.house365.web.util.StringUtils.getRandomNumber(10);
                String randStr = com.house365.web.util.StringUtils.getRandomChars(13);
                String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
                String signature = HttpUtil.getSignature2(deciceId, randStr, timestamp);
                //获取accesstoken
                HashMap<String, String> accesstokenMap = new HashMap<>(5);
                accesstokenMap.put("version", "v3.0");
                //获取acceToken接口URl
                String getAccessTokenUrl = "http://yunxinim.house365.com/api/5b0cc34464a64";
                List<NameValuePair> tokenInParam = new ArrayList<>();
                tokenInParam.add(new BasicNameValuePair("app_id", "89962055"));
                tokenInParam.add(new BasicNameValuePair("app_secret", "pMHTUWAoOGSjaToIhHKwmQJKWZcAAvjN"));
                tokenInParam.add(new BasicNameValuePair("device_id", deciceId));
                tokenInParam.add(new BasicNameValuePair("rand_str", randStr));
                tokenInParam.add(new BasicNameValuePair("timestamp", timestamp));
                tokenInParam.add(new BasicNameValuePair("signature", signature));

                List<String> newTokenParams = new ArrayList<>();
                for (NameValuePair pair : tokenInParam) {
                    newTokenParams.add(pair.getName() + "=" + pair.getValue());
                }
                String newTokenUrl = getAccessTokenUrl + "?" + Joiner.on("&").join(newTokenParams);
                String tokenResult = "";
                tokenResult = HttpUtil.getHttpRequest(newTokenUrl, accesstokenMap, 100000, "utf-8");
                if (Strings.isNullOrEmpty(tokenResult)) {
                    throw new ServiceException("get token failed");
                }
                JSONObject json = JSONObject.fromObject(tokenResult);
                JSONObject jo = json.getJSONObject("data");
                String accessToken = jo.getString("access_token");
                logger.info("******SYNC_TO_CRM_RESULT ACCESS_TOKEN*******" + accessToken);
                //2.通知IM更新用户
                List<NameValuePair> cornetInParam = new ArrayList<>();
                cornetInParam.add(new BasicNameValuePair("accid", entity.getAccId()));
                cornetInParam.add(new BasicNameValuePair("username", entity.getRealName()));
                cornetInParam.add(new BasicNameValuePair("avatar", entity.getHeadImgURL()));
                String updateResult = HttpUtil.doPostWithHeader("http://yunxinim.house365.com/api/5b9235bea9f88", cornetInParam, accessToken, "");
                logger.info("******SYNC_TO_CRM_RESULT*******" + updateResult);
                return "redirect:/role/edit/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                redirectAttributes.addAttribute("error", ex.getMessage());
                return "redirect:/role/edit/" + entity.getId();
            }
        }

    }


    /**
     * 去新增角色
     *
     * @return 结果视图
     */
    @RequestMapping(value = "bindCornet")
    @ResponseBody
    public House365RestResponse bindCornet(HttpServletRequest httpRequest, String cornet) {
        House365RestResponse response = new House365RestResponse();
        if (StringUtils.isBlank(cornet)) {
            response.setResult("0");
            response.setMsg("请输入短号！");
            return response;
        }
        UserEntity userEntity = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        if (cornet.equals(userEntity.getCornet())) {
            response.setResult("0");
            response.setMsg("该短号已绑定！");
            return response;
        }
        Map<String, Object> searchParams = new HashMap<>(10);
        searchParams.put("EQ_cornet", cornet);

        UserListRequest userListRequest = new UserListRequest();
        userListRequest.setSearchParams(searchParams);
        UserListResponse userListResponse = user.getUserList(userListRequest);
        if (userListResponse.getObjectList() != null && userListResponse.getObjectList().size() != 0) {
            response.setResult("0");
            response.setMsg("当前短号已被他人绑定，请核实后重新操作！");
            return response;
        }

        userEntity.setCornet(cornet);
        UserRequest request = new UserRequest();
        userEntity.setUpdateTime(new Date());
        userEntity.setUpdateUserid(userEntity.getId());
        request.setEntity(userEntity);
        user.updateUser(request);

        response.setResult("1");
        response.setMsg("绑定成功！");
        return response;

    }


    /**
     * 绑定400号码
     *
     * @return 结果视图
     */
    @RequestMapping(value = "bindHotline")
    @ResponseBody
    public House365RestResponse bindHotline(HttpServletRequest httpRequest, String userId) {
        House365RestResponse response = new House365RestResponse();
        if (StringUtils.isBlank(userId)) {
            response.setResult("0");
            response.setMsg("请输入手机号！");
            return response;
        }

        UserEntity userEntity = null;
        UserResponse userResponse = user.getUserById(Integer.valueOf(userId));
        if (userResponse.getEntity() != null) {
            userEntity = userResponse.getEntity();
        }

        if (userEntity == null) {
            response.setResult("0");
            response.setMsg("该号码不存在！");
            return response;
        }

        UserEntity oper = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);
        if (!Strings.isNullOrEmpty(userEntity.getHotlinephone())) {
            response.setResult("0");
            response.setMsg("该号码已绑定！");
            return response;
        }

        //0.获取signature:入参
        String deciceId = com.house365.web.util.StringUtils.getRandomNumber(10);
        String randStr = com.house365.web.util.StringUtils.getRandomChars(13);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String signature = HttpUtil.getSignature(deciceId, randStr, timestamp);
        //1.先获取accesstoken
        HashMap<String, String> tokenMap = new HashMap<>(10);
        tokenMap.put("version", "v3.0");
        String accessToken = HttpUtil.getAccessToken(tokenMap, timestamp, randStr, signature, deciceId, response);
        String cornetResult = "";
        DepartmentResponse dept = department.getDepartmentById(userEntity.getDeptId());
        try {
            //2.获取短号
//            String cornetUrl = "http://api.400.house365.com/api/5a9ea11c04845";//获取短号接口url
            String cornetUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("getcornet.url");
            HashMap<String, String> bindMap = new HashMap<>();
            List<String> newCornetParams = new ArrayList<>();
            bindMap.put("version", "v3.0");
            bindMap.put("access-token", accessToken);
            String bindKey = "";
            String shortTel = "";
            if (dept.getEntity() != null) {
                String cityId = dept.getEntity().getCityID();
                DepartmentResponse departmentResponse = department.getDepartmentById(Integer.valueOf(cityId));
                DepartmentEntity city = departmentResponse.getEntity();
                String cityCode = "zb".equalsIgnoreCase(city.getDescripition()) ? "nj" : city.getDescripition();
                List<NameValuePair> cornetInParam = new ArrayList<>();
                cornetInParam.add(new BasicNameValuePair("city", cityCode));
                //直销人员姓名
                cornetInParam.add(new BasicNameValuePair("name", userEntity.getRealName()));
                for (NameValuePair pair : cornetInParam) {
                    newCornetParams.add(pair.getName() + "=" + pair.getValue());
                }
                String newCornetUrl = cornetUrl + "?" + Joiner.on("&").join(newCornetParams);
                cornetResult = HttpUtil.getHttpRequest(newCornetUrl, bindMap, 100000, "utf-8");
                if (Strings.isNullOrEmpty(cornetResult)) {
                    throw new ServiceException("get cornet failed");
                }
                JSONObject jsonCornet = JSONObject.fromObject(cornetResult);
                JSONObject joCornet = jsonCornet.getJSONObject("data");
                bindKey = joCornet.getString("bind_key");
                shortTel = joCornet.getString("short_tel");
            }
            //3.绑定
            String bindURL = MemoryPropertyPlaceholderConfigurer.getContextProperty("bindcornet.url");
            List<NameValuePair> bindInParam = new ArrayList<>();
            List<String> newBindParams = new ArrayList<>();
            bindInParam.add(new BasicNameValuePair("bind_key", bindKey));
            bindInParam.add(new BasicNameValuePair("telephone", userEntity.getMobile()));
            bindInParam.add(new BasicNameValuePair("prefix", "0"));

            for (NameValuePair pair : bindInParam) {
                newBindParams.add(pair.getName() + "=" + pair.getValue());
            }
            String newBindUrl = bindURL + "?" + Joiner.on("&").join(newBindParams);
            String bindResult = HttpUtil.getHttpRequest(newBindUrl, bindMap, 100000, "utf-8");

            if (Strings.isNullOrEmpty(bindResult)) {
                throw new ServiceException("bind_hotline_fail[{}]");
            }
            userEntity.setHotlinephone(shortTel);
            userEntity.setUpdateTime(new Date());
            userEntity.setUpdateUserid(oper.getId());
            UserRequest request = new UserRequest();
            request.setEntity(userEntity);
            user.updateUser(request);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResult("0");
            response.setMsg(e.getMessage());
            return response;
        }
        response.setMsg("绑定成功！");
        return response;

    }

    /**
     * 解绑400号码
     *
     * @return 结果视图
     */
    @RequestMapping(value = "unbindHotline")
    @ResponseBody
    public House365RestResponse unbindHotline(HttpServletRequest httpRequest, String userId) {
        House365RestResponse response = new House365RestResponse();
        if (StringUtils.isBlank(userId)) {
            response.setResult("0");
            response.setMsg("请输入号码！");
            return response;
        }

        UserEntity userEntity = null;
        UserResponse userResponse = user.getUserById(Integer.valueOf(userId));
        if (userResponse.getEntity() != null) {
            userEntity = userResponse.getEntity();
        }

        if (userEntity == null || Strings.isNullOrEmpty(userEntity.getHotlinephone())) {
            response.setResult("0");
            response.setMsg("该号码不存在！");
            return response;
        }

        UserEntity oper = (UserEntity) httpRequest.getSession().getAttribute(SessionConstants.THREAD_USER_KEY);

        //获取signature
        String deciceId = com.house365.web.util.StringUtils.getRandomNumber(10);
        String randStr = com.house365.web.util.StringUtils.getRandomChars(13);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String signature = HttpUtil.getSignature(deciceId, randStr, timestamp);
        //1.先获取acce_token作为入参
        HashMap<String, String> tokenMap = new HashMap<>(10);
        tokenMap.put("version", "v3.0");
        String accessToken = HttpUtil.getAccessToken(tokenMap, timestamp, randStr, signature, deciceId, response);
        //2.解绑
        String unbindUrl = MemoryPropertyPlaceholderConfigurer.getContextProperty("unbindcornet.url");
        String unbindResult = "";
        HashMap<String, String> unBindMap = new HashMap<>(10);
        unBindMap.put("version", "v3.0");

        try {
            unBindMap.put("access-token", accessToken);
            List<NameValuePair> unbindInParam = new ArrayList<>();
            List<String> newUnbindParams = new ArrayList<>();
            unbindInParam.add(new BasicNameValuePair("short_tel", userEntity.getHotlinephone()));

            for (NameValuePair pair : unbindInParam) {
                newUnbindParams.add(pair.getName() + "=" + pair.getValue());
            }
            String newUnbindUrl = unbindUrl + "?" + Joiner.on("&").join(newUnbindParams);
            unbindResult = HttpUtil.getHttpRequest(newUnbindUrl, unBindMap, 100000, "utf-8");
            logger.warn("user_unbind_hotline_phone , [{}]", userEntity.getRealName());
            JSONObject jo = JSONObject.fromObject(unbindResult);
            if ("1".equals(jo.getString("code"))) {
                saveUnbindLog(oper, userEntity);
                userEntity.setHotlinephone(null);
                userEntity.setUpdateTime(new Date());
                userEntity.setUpdateUserid(oper.getId());
                UserRequest request = new UserRequest();
                request.setEntity(userEntity);
                user.updateUser(request);
            } else if ("-8".equals(jo.getString("code"))) {
                response.setResult("0");
                response.setMsg("记录不存在");
                return response;
            } else {
                response.setResult("0");
                response.setMsg("解绑失败！");
                return response;
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResult("0");
            response.setMsg(e.getMessage());
            return response;
        }
        response.setResult("1");
        response.setMsg("解绑成功！");
        return response;

    }

    /**
     * 记录解绑日志
     *
     * @param loginUserEntity
     * @param delUser
     */
    private void saveUnbindLog(UserEntity loginUserEntity, UserEntity delUser) {
        UserEntity entity = new UserEntity();
        entity.setName(delUser.getName());
        entity.setRealName(delUser.getRealName());
        entity.setMobile(delUser.getMobile());
        entity.setCornet(delUser.getCornet());
        entity.setHotlinephone(delUser.getHotlinephone());
        entity.setCreateTime(new Date());
        entity.setCreateUserid(loginUserEntity.getId());
        entity.setCreateUsername(loginUserEntity.getName());
        entity.setAccId(delUser.getAccId());
        entity.setIdentityType(delUser.getIdentityType());
        user.saveUnbindLog(entity);
    }

    @RequestMapping(value = "cuttingPicture", method = RequestMethod.POST)
    public String cuttingPicture(Model model, HttpServletRequest request) {
        String pictureUrl = request.getParameter("pictureUrl");
        String resourceId = request.getParameter("resourceId");
        String resourceType = request.getParameter("resourceType");
        String bizType = request.getParameter("bizType");
        String imageId = request.getParameter("imageId");

        model.addAttribute("pictureUrl", pictureUrl);
        model.addAttribute("resourceId", resourceId);
        model.addAttribute("resourceType", resourceType);
        model.addAttribute("bizType", bizType);
        model.addAttribute("imageId", imageId);
        return getAutoUrl();
    }


    @RequestMapping(value = "cuttingPictureAction")
    @ResponseBody
    public House365RestResponse cuttingPictureAction(BaseAttachment attachment, Integer x, Integer y, Integer h, Integer w, String pictureUrl, String imageId,
                                                     String resourceId, String bizType) {
        House365RestResponse response = new House365RestResponse();

        try {
            BaseAttachment attachment2 = PicCut.cut(x, y, w, h, pictureUrl, attachment);
            AttachmentRequest req = new AttachmentRequest();
            req.setAttachment(attachment2);
            attachmentInterface.addAttachment(req);
            attachmentInterface.deleteAttachment(Integer.parseInt(imageId));
            //
            if ("1".equals(bizType)) {
                UserEntity userEntity = new UserEntity();
                UserResponse userResponse = user.getUserById(Integer.valueOf(resourceId));
                if (userResponse.getEntity() != null) {
                    userEntity = userResponse.getEntity();
                }
                String mobile = userEntity.getMobile();
                String accId = userEntity.getAccId();
                UserEntity ue = user.getRemotePath(Integer.valueOf(resourceId));
                String remotePath = ue.getRemotePath();
                logger.info("******MOBILE*******" + mobile + "*******RESOURCEID*******" + resourceId + "******ACCID******" + accId + "*****remotePath****" + remotePath);
                //通知IM头像修改
                String deciceId = com.house365.web.util.StringUtils.getRandomNumber(10);
                String randStr = com.house365.web.util.StringUtils.getRandomChars(13);
                String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
                String signature = HttpUtil.getSignature2(deciceId, randStr, timestamp);
                //获取accesstoken
                HashMap<String, String> accesstokenMap = new HashMap<>(10);
                accesstokenMap.put("version", "v3.0");
                //获取acceToken接口URl
                String getAccessTokenUrl = "http://yunxinim.house365.com/api/5b0cc34464a64";
                List<NameValuePair> tokenInParam = new ArrayList<>();
                tokenInParam.add(new BasicNameValuePair("app_id", "89962055"));
                tokenInParam.add(new BasicNameValuePair("app_secret", "pMHTUWAoOGSjaToIhHKwmQJKWZcAAvjN"));
                tokenInParam.add(new BasicNameValuePair("device_id", deciceId));
                tokenInParam.add(new BasicNameValuePair("rand_str", randStr));
                tokenInParam.add(new BasicNameValuePair("timestamp", timestamp));
                tokenInParam.add(new BasicNameValuePair("signature", signature));

                List<String> newTokenParams = new ArrayList<>();
                for (NameValuePair pair : tokenInParam) {
                    newTokenParams.add(pair.getName() + "=" + pair.getValue());
                }
                String newTokenUrl = getAccessTokenUrl + "?" + Joiner.on("&").join(newTokenParams);
                String tokenResult = "";
                tokenResult = HttpUtil.getHttpRequest(newTokenUrl, accesstokenMap, 100000, "utf-8");
                if (Strings.isNullOrEmpty(tokenResult)) {
                    throw new ServiceException("get token failed");
                }
                JSONObject json = JSONObject.fromObject(tokenResult);
                JSONObject jo = json.getJSONObject("data");
                String accessToken = jo.getString("access_token");
                logger.info("******ACCESS_TOKEN*******" + accessToken);
                //2.通知IM更新用户
                List<NameValuePair> cornetInParam = new ArrayList<>();
                cornetInParam.add(new BasicNameValuePair("accid", accId));
                cornetInParam.add(new BasicNameValuePair("avatar", remotePath));
                String updateResult = HttpUtil.doPostWithHeader("http://yunxinim.house365.com/api/5b9235bea9f88", cornetInParam, accessToken, "");
                logger.info("******UPDATE_RESULT*******" + updateResult);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResult("0");
            response.setMsg(e.getMessage());
            return response;
        }
        response.setResult("1");
        response.setMsg("裁剪成功！");
        return response;
    }


}
