package com.house365.wechat.rest;

import com.google.common.base.Strings;
import com.house365.beans.dto.AgentDTO;
import com.house365.beans.dto.DepartmentDTO;
import com.house365.beans.dto.TagDTO;
import com.house365.beans.dto.UserDTO;
import com.house365.beans.vo.Company;
import com.house365.beans.vo.Department;
import com.house365.common.util.RestTemplateBean;
import com.house365.service.impl.CompanyService;
import com.house365.service.impl.DepartmentService;
import com.house365.service.impl.UserService;
import com.house365.wechat.WeChatConstant;
import com.house365.wechat.service.RemoteCallService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.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.web.bind.annotation.*;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Description
 * <p>
 * Created by 365 on 2016/12/27 0027.
 */
@RestController
@RequestMapping("enterprise")
public class EnterpriseController {
    private Logger logger = LoggerFactory.getLogger(EnterpriseController.class);

    @Autowired
    private RemoteCallService remoteCallService;

    @Autowired
    private CompanyService companyService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserService userService;

    /**
     * get:     获取企业号应用
     * <p>  agentid 企业应用的id</p>
     * <p>
     * set:     设置企业号应用
     * <p>  agentid 企业应用的id</p>
     * <p>  report_location_flag 企业应用是否打开地理位置上报 0：不上报；1：进入会话上报；2：持续上报</p>
     * <p>  logo_mediaid 企业应用头像的mediaid，通过多媒体接口上传图片获得mediaid，上传后会自动裁剪成方形和圆形两个头像</p>
     * <p>  name 企业应用名称</p>
     * <p>  description 企业应用详情</p>
     * <p>  redirect_domain 企业应用可信域名</p>
     * <p>  isreportuser 是否接收用户变更通知。0：不接收；1：接收。</p>
     * <p>  isreportenter 是否上报用户进入应用事件。0：不接收；1：接收。</p>
     * <p>  home_url 主页型应用url。url必须以http或者https开头。消息型应用无需该参数</p>
     * <p>  chat_extension_url 关联会话url。设置该字段后，企业会话"+"号将出现该应用，点击应用可直接跳转到此url，支持jsapi向当前会话发送消息。</p>
     * <p>
     * list:    获取应用概况列表
     */
    @RequestMapping(value = "agent/{method}", method = RequestMethod.POST)
    public String agent(
            @PathVariable("method") String method, @RequestParam(value = "corpId") String corpId,
            @RequestParam(value = "secret") String secret, @RequestBody AgentDTO agentDTO
    ) {
        List<NameValuePair> params = new ArrayList<>();
        //获取access_token
        String accessToken = remoteCallService.getAccessToken(corpId, secret);
        params.add(new BasicNameValuePair(WeChatConstant.WE_CHAT_ACCESS_TOKEN, accessToken));

        String result = "";
        try {
            switch (method) {
                case "get":
                    params.add(new BasicNameValuePair(WeChatConstant.AGENT_ID, agentDTO.getAgentid()));
                    result = RestTemplateBean.doGet(WeChatConstant.AGENT_GET, params);
                    break;
                case "set":
                    result = RestTemplateBean.doPost(WeChatConstant.getWeChatPostUrl(WeChatConstant.AGENT_SET, params),
                            JSONObject.fromObject(agentDTO));
                    break;
                case "list":
                    result = RestTemplateBean.doGet(WeChatConstant.AGENT_LIST, params);
                    break;
                default:
                    throw new Exception("url 调用方法缺失");
            }
            logger.info("=============result:{}", result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }


    /**
     * create:  创建应用菜单
     * <p>  agentid 企业应用号</p>
     * <p>  botton 自定义菜单json</p>
     * <p>
     * delete:  删除菜单
     * <p>  agentid 企业应用号</p>
     * <p>
     * get:     获取菜单列表
     * <p>  agentid 企业应用号</p>
     */
    @RequestMapping(value = "menu/{method}", method = RequestMethod.POST)
    public String menu(
            @PathVariable("method") String method, @RequestParam(value = "corpId") String corpId,
            @RequestParam(value = "secret") String secret, @RequestParam(value = "agentid") String agentId,
            @RequestParam(value = "button", required = false) String button
    ) {
        List<NameValuePair> params = new ArrayList<>();
        //获取access_token
        String accessToken = remoteCallService.getAccessToken(corpId, secret);
        params.add(new BasicNameValuePair(WeChatConstant.WE_CHAT_ACCESS_TOKEN, accessToken));
        params.add(new BasicNameValuePair(WeChatConstant.AGENT_ID, agentId));

        String result = "";
        try {
            switch (method) {
                case "create":
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.MENU_CREATE, params),
                            JSONObject.fromObject(button));
                    //                    result = HttpClientUtil.doPost(WeChatConstant.getWeChatPostUrl(WeChatConstant.MENU_CREATE, accessToken), menu);
                    break;
                case "delete":
                    result = RestTemplateBean.doGet(WeChatConstant.MENU_DELETE, params);
                    break;
                case "get":
                    result = RestTemplateBean.doGet(WeChatConstant.MENU_GET, params);
                    break;
                default:
                    throw new Exception("url 调用方法缺失");
            }
            logger.info("=============result:{}", result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * authsucc:    成员关注企业号二次验证
     * <p>  userid 成员UserID</p>
     * <p>
     * create:      创建成员
     * <p>  userid 成员UserID。对应管理端的帐号，企业内必须唯一。不区分大小写，长度为1~64个字节</p>
     * <p>  name 成员名称。长度为1~64个字节</p>
     * <p>  department 成员所属部门id列表,不超过20个</p>
     * <p>  position 职位信息。长度为0~64个字节</p>
     * <p>  mobile 手机号码。企业内必须唯一，mobile/weixinid/email三者不能同时为空</p>
     * <p>  gender 性别。1表示男性，2表示女性</p>
     * <p>  email 邮箱。长度为0~64个字节。企业内必须唯一</p>
     * <p>  weixinid 微信号。企业内必须唯一。（注意：是微信号，不是微信的名字）</p>
     * <p>  avatar_mediaid 成员头像的mediaid，通过多媒体接口上传图片获得的mediaid</p>
     * <p>  extattr 扩展属性。扩展属性需要在WEB管理端创建后才生效，否则忽略未知属性的赋值</p>
     * <p>
     * update:      更新成员
     * <p>  userid 成员UserID。对应管理端的帐号，企业内必须唯一。不区分大小写，长度为1~64个字节</p>
     * <p>  name 成员名称。长度为1~64个字节</p>
     * <p>  department 成员所属部门id列表,不超过20个</p>
     * <p>  position 职位信息。长度为0~64个字节</p>
     * <p>  mobile 手机号码。企业内必须唯一，mobile/weixinid/email三者不能同时为空</p>
     * <p>  gender 性别。1表示男性，2表示女性</p>
     * <p>  email 邮箱。长度为0~64个字节。企业内必须唯一</p>
     * <p>  weixinid 微信号。企业内必须唯一。（注意：是微信号，不是微信的名字）</p>
     * <p>  avatar_mediaid 成员头像的mediaid，通过多媒体接口上传图片获得的mediaid</p>
     * <p>  extattr 扩展属性。扩展属性需要在WEB管理端创建后才生效，否则忽略未知属性的赋值</p>
     * <p>
     * delete:      删除成员
     * <p>  userid 成员UserID。对应管理端的帐号</p>
     * <p>
     * batchdelete: 批量删除成员
     * <p>  useridlist 成员UserID列表。对应管理端的帐号。（最多支持200个）</p>
     * <p>
     * get:         获取成员
     * <p>  userid 成员UserID。对应管理端的帐号</p>
     * <p>
     * simplelist:  获取部门成员
     * <p>  department_id 获取的部门id</p>
     * <p>  fetch_child: 1/0 是否递归获取子部门下面的成员</p>
     * <p>  status 0获取全部成员，1获取已关注成员列表，2获取禁用成员列表，4获取未关注成员列表。status可叠加，未填写则默认为4</p>
     * <p>
     * list:        获取部门成员(详情)
     * <p>  department_id 获取的部门id</p>
     * <p>  1/0：是否递归获取子部门下面的成员</p>
     * <p>  status 0获取全部成员，1获取已关注成员列表，2获取禁用成员列表，4获取未关注成员列表。status可叠加，未填写则默认为4</p>
     */
    @RequestMapping(value = "user/{method}", method = RequestMethod.POST)
    public String user(
            @PathVariable("method") String method, @RequestParam(value = "corpId") String corpId,
            @RequestParam(value = "secret") String secret, @RequestBody UserDTO user
    ) {
        List<NameValuePair> params = new ArrayList<>();
        //获取access_token
        String accessToken = remoteCallService.getAccessToken(corpId, secret);
        if (Strings.isNullOrEmpty(accessToken)) {
            return "accessToken empty";
        }

        logger.info("user call [{}]", method + corpId + secret + user);
        params.add(new BasicNameValuePair(WeChatConstant.WE_CHAT_ACCESS_TOKEN, accessToken));

        String result = "";
        try {
            Department department = departmentService.selectByCompanyIdAndDepartmentId(user.getCompanyid(), String.valueOf(user.getDepartment().get(0)));
            List<Integer> departments = new ArrayList<>();
            departments.add(department.getWechatDepartmentId());
            switch (method) {
                case "authsucc":
                    params.add(new BasicNameValuePair("userid", user.getUserid()));
                    result = RestTemplateBean.doGet(WeChatConstant.USER_AUTHSUCC, params);
                    break;
                case "create":
                    user.setDepartment(departments);
                    if (method.equals("create")) {
                        result = RestTemplateBean.doPost(
                                WeChatConstant.getWeChatPostUrl(WeChatConstant.USER_CREATE, params),
                                JSONObject.fromObject(user));
                    } else if (method.equals("update")) {
                        result = RestTemplateBean.doPost(
                                WeChatConstant.getWeChatPostUrl(WeChatConstant.USER_UPDATE, params),
                                JSONObject.fromObject(user));
                    }
                    break;
                case "update":
                    user.setDepartment(departments);
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.USER_UPDATE, params),
                            JSONObject.fromObject(user));
                    break;
                case "delete":
                    params.add(new BasicNameValuePair("userid", user.getUserid()));
                    result = RestTemplateBean.doGet(WeChatConstant.USER_DELETE, params);
                    break;
                case "batchdelete":
                    JSONObject userIds = new JSONObject();
                    userIds.put("useridlist", user.getUseridlist());
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.USER_BATCH_DELETE, params), userIds);
                    break;
                case "get":
                    params.add(new BasicNameValuePair("department_id", user.getDepartment_id()));
                    params.add(new BasicNameValuePair("fetch_child", user.getFetch_child()));
                    params.add(new BasicNameValuePair("status", user.getStatus()));
                    result = RestTemplateBean.doGet(WeChatConstant.USER_GET, params);
                    break;
                case "simplelist":
                    params.add(new BasicNameValuePair("department_id", user.getDepartment_id()));
                    params.add(new BasicNameValuePair("fetch_child", user.getFetch_child()));
                    params.add(new BasicNameValuePair("status", user.getStatus()));
                    result = RestTemplateBean.doGet(WeChatConstant.USER_SIMPLE_LIST, params);
                    break;
                case "list":
                    params.add(new BasicNameValuePair("department_id", user.getDepartment_id()));
                    params.add(new BasicNameValuePair("fetch_child", user.getFetch_child()));
                    params.add(new BasicNameValuePair("status", user.getStatus()));
                    result = RestTemplateBean.doGet(WeChatConstant.USER_LIST, params);
                    break;
                default:
                    throw new Exception("url 调用方法缺失");
            }
            logger.info("=============result:{}", result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    //    private String saveUser(UserDTO user) {
    //        String method = "";
    //        User userEntity = userService.selectByCompanyIdAndUserId(user.getCompanyid(), user.getUserid());
    //        if (userEntity == null) {
    //            method = "create";
    //            userEntity = new User();
    //            Integer userId = userService.nextId(user.getCompanyid());
    //            Department department = departmentService.selectByCompanyIdAndDepartmentId(user.getCompanyid(), user.getDepartment());
    //            userEntity.setId(userId);
    //            userEntity.setWechatDepartmentId(department.getWechatDepartmentId());
    //            userEntity.setCompanyDepartmentId(user.getDepartment());
    //            userEntity.setCompanyId(user.getCompanyid());
    //            userEntity.setPosition(user.getPosition());
    //            userEntity.setMobile(user.getMobile());
    //            userEntity.setGender(user.getGender());
    //            userEntity.setEmail(user.getEmail());
    //            userEntity.setWeixinid(user.getWeixinid());
    //            userEntity.setAvatarMediaid(user.getAvatar_mediaid());
    //            userEntity.setExtattr(user.getExtattr());
    //            userEntity.setCreateTime(new Date());
    //            userService.save(userEntity);
    //
    //            user.setUserid(String.valueOf(userId));
    //        } else {
    //            method = "update";
    //            Department department = departmentService.selectByCompanyIdAndDepartmentId(user.getCompanyid(), user.getDepartment());
    //            userEntity.setWechatDepartmentId(department.getWechatDepartmentId());
    //            userEntity.setCompanyDepartmentId(user.getDepartment());
    //            userEntity.setCompanyId(user.getCompanyid());
    //            userEntity.setPosition(user.getPosition());
    //            userEntity.setMobile(user.getMobile());
    //            userEntity.setGender(user.getGender());
    //            userEntity.setEmail(user.getEmail());
    //            userEntity.setWeixinid(user.getWeixinid());
    //            userEntity.setAvatarMediaid(user.getAvatar_mediaid());
    //            userEntity.setExtattr(user.getExtattr());
    //            userEntity.setCreateTime(new Date());
    //            userService.updateByPrimaryKey(userEntity);
    //        }
    //        return method;
    //    }

    /**
     * create:      创建部门
     * <p>  id 部门id，整型。指定时必须大于1，不指定时则自动生成</p>
     * <p>  name 部门名称。长度限制为32个字（汉字或英文字母），字符不能包括\:*?"<>｜</p>
     * <p>  parentid 父亲部门id。根部门id为null</p>
     * <p>  order 在父部门中的次序值。order值小的排序靠前。</p>
     * <p>
     * update:      更新部门
     * <p>  id 部门id，整型。指定时必须大于1，不指定时则自动生成</p>
     * <p>  name 部门名称。长度限制为32个字（汉字或英文字母），字符不能包括\:*?"<>｜</p>
     * <p>  parentid 父亲部门id。根部门id为1</p>
     * <p>  order 在父部门中的次序值。order值小的排序靠前。</p>
     * <p>
     * delete:      删除部门
     * <p>  id 部门id。（注：不能删除根部门；不能删除含有子部门、成员的部门）</p>
     * <p>
     * list:        获取部门列表
     * <p>  id 部门id。获取指定部门及其下的子部门</p>
     */
    @RequestMapping(value = "department/{method}", method = RequestMethod.POST)
    public String department(
            @PathVariable("method") String method, @RequestParam(value = "corpId") String corpId,
            @RequestParam(value = "secret") String secret, @RequestBody DepartmentDTO department
    ) {
        List<NameValuePair> params = new ArrayList<>();
        //获取access_token
        String accessToken = remoteCallService.getAccessToken(corpId, secret);
        params.add(new BasicNameValuePair(WeChatConstant.WE_CHAT_ACCESS_TOKEN, accessToken));
        String result = "";
        try {
            switch (method) {
                case "create":
                    //下跳至update一起处理
                    method = saveDepartment(department);
                    if (method.equals("create")) {
                        result = RestTemplateBean.doPost(
                                WeChatConstant.getWeChatPostUrl(WeChatConstant.DEPARTMENT_CREATE, params),
                                JSONObject.fromObject(department));
                        JSONObject res = JSONObject.fromObject(result);
                        if (res.getString("errcode").equals("60008")) {
                            result = RestTemplateBean.doPost(
                                    WeChatConstant.getWeChatPostUrl(WeChatConstant.DEPARTMENT_UPDATE, params),
                                    JSONObject.fromObject(department));
                            res = JSONObject.fromObject(result);
                            if (!res.getString("errcode").equals("0")) {
                                result = rePushDepartment(department, params);
                            }
                            logger.debug("=============result:{}", result);
                        }
                    } else if (method.equals("update")) {
                        result = RestTemplateBean.doPost(
                                WeChatConstant.getWeChatPostUrl(WeChatConstant.DEPARTMENT_UPDATE, params),
                                JSONObject.fromObject(department));
                        logger.debug("=============result:{}", result);
                        JSONObject res = JSONObject.fromObject(result);
                        if (res.getString("errcode").equals("60003")) {
                            result = RestTemplateBean.doPost(
                                    WeChatConstant.getWeChatPostUrl(WeChatConstant.DEPARTMENT_CREATE, params),
                                    JSONObject.fromObject(department));
                            logger.debug("=============result:{}", result);
                        }
                    }
                    break;
                case "update":
                    //保存至关联表
                    saveDepartment(department);
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.DEPARTMENT_UPDATE, params),
                            JSONObject.fromObject(department));
                    JSONObject res = JSONObject.fromObject(result);
                    if (res.getString("errcode").equals("60003")) {//department not found 重新调用创建方法
                        result = RestTemplateBean.doPost(
                                WeChatConstant.getWeChatPostUrl(WeChatConstant.DEPARTMENT_CREATE, params),
                                JSONObject.fromObject(department));
                        logger.debug("=============result:{}", result);
                    }
                    logger.debug("=============result:{}", result);
                    break;
                case "delete":
                    Department departmentEntity = departmentService.selectByCompanyIdAndDepartmentId(
                            department.getCompanyid(), department.getId());
                    params.add(new BasicNameValuePair("id", String.valueOf(departmentEntity.getWechatDepartmentId())));
                    result = RestTemplateBean.doGet(WeChatConstant.DEPARTMENT_DELETE, params);

                    departmentService.deleteByPrimaryKey(departmentEntity.getId());
                    break;
                case "list":
                    params.add(new BasicNameValuePair("id", department.getId()));
                    result = RestTemplateBean.doGet(WeChatConstant.DEPARTMENT_LIST, params);
                    break;
                default:
                    throw new Exception("url 调用方法缺失");
            }
            logger.debug("=============result:{}", result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 部门推送重试
     *
     * @param department 部门 weChatDepartmentId 加1
     * @param params     企业号参数
     * @return
     * @throws URISyntaxException
     */
    private String rePushDepartment(DepartmentDTO department, List<NameValuePair> params) throws URISyntaxException {
        Department departmentEntity = departmentService.selectByCompanyIdAndWeChatDepartmentId(department.getCompanyid(), department.getId());
        departmentEntity.setWechatDepartmentId(departmentEntity.getWechatDepartmentId() + 1);
        department.setId(department.getId() + 1);
        departmentService.updateByPrimaryKey(departmentEntity);
        String result = RestTemplateBean.doPost(
                WeChatConstant.getWeChatPostUrl(WeChatConstant.DEPARTMENT_CREATE, params),
                JSONObject.fromObject(department));
        JSONObject res = JSONObject.fromObject(result);
        if (!res.getString("errcode").equals("0")) {
            rePushDepartment(department, params);
        }
        return result;
    }

    private String saveDepartment(DepartmentDTO department) {
        String method = "";
        Department departmentEntity = departmentService.selectByCompanyIdAndDepartmentId(department.getCompanyid(),
                department.getId());
        if (departmentEntity == null) {
            method = "create";
            departmentEntity = new Department();
            //获取父部门的微信关联关系
            Department parentDepartment = departmentService.selectByCompanyIdAndDepartmentId(department.getCompanyid(),
                    department.getParentid());
            Integer departmentId = departmentService.nextId(department.getCompanyid());
            departmentEntity.setWechatDepartmentId(departmentId);
            departmentEntity.setCompanyDepartmentId(department.getId());
            departmentEntity.setCompanyId(department.getCompanyid());
            Company company = companyService.selectByPrimaryKey(Integer.valueOf(department.getCompanyid()));
            departmentEntity.setCompanyName(company.getCompanyName());
            departmentEntity.setDepartmentName(department.getName());
            departmentEntity.setWechatParentId(parentDepartment.getWechatDepartmentId());
            departmentEntity.setCompanyParentId(
                    StringUtils.isBlank(department.getParentid()) ? null : department.getParentid());
            departmentEntity.setHasChildren("0");
            departmentEntity.setSort(department.getOrder());
            departmentEntity.setCreateTime(new Date());
            departmentService.save(departmentEntity);

            department.setId(String.valueOf(departmentId));
            department.setParentid(String.valueOf(parentDepartment.getWechatDepartmentId()));
        } else {
            method = "update";
            departmentEntity.setDepartmentName(department.getName());
            departmentEntity.setSort(department.getOrder());
            departmentService.updateByPrimaryKey(departmentEntity);

            //获取父部门的微信关联关系
            Department parentDepartment = departmentService.selectByCompanyIdAndDepartmentId(department.getCompanyid(),
                    department.getParentid());

            department.setId(String.valueOf(departmentEntity.getWechatDepartmentId()));
            department.setParentid(String.valueOf(parentDepartment.getWechatDepartmentId()));
        }
        return method;
    }

    /**
     * create:      创建标签
     * <p>  tagname 标签名称，长度限制为32个字（汉字或英文字母），标签名不可与其他标签重名。</p>
     * <p>  tagid 标签id，整型，指定此参数时新增的标签会生成对应的标签id，不指定时则以目前最大的id自增。</p>
     * <p>
     * update:      更新标签名字
     * <p>  tagname 标签名称，长度限制为32个字（汉字或英文字母），标签名不可与其他标签重名。</p>
     * <p>  tagid 标签id，整型，指定此参数时新增的标签会生成对应的标签id，不指定时则以目前最大的id自增。</p>
     * <p>
     * delete:      删除标签
     * <p>  tagid 标签ID</p>
     * <p>
     * get:         获取标签成员
     * <p>  tagid 标签id</p>
     * <p>
     * addtagusers: 增加标签成员
     * <p>  tagid 标签id</p>
     * <p>  userlist 企业成员ID列表，注意：userlist、partylist不能同时为空，单次请求长度不超过1000</p>
     * <p>  partylist 企业部门ID列表，注意：userlist、partylist不能同时为空，单次请求长度不超过100</p>
     * <p>
     * deltagusers: 删除标签成员
     * <p>  tagid 标签id</p>
     * <p>  userlist 企业成员ID列表，注意：userlist、partylist不能同时为空，单次请求长度不超过1000</p>
     * <p>  partylist 企业部门ID列表，注意：userlist、partylist不能同时为空，单次请求长度不超过100</p>
     * <p>
     * list:        获取标签列表
     */
    @RequestMapping(value = "tag/{method}", method = RequestMethod.POST)
    public String tag(
            @PathVariable("method") String method, @RequestParam(value = "corpId") String corpId,
            @RequestParam(value = "secret") String secret, @RequestBody TagDTO tag
    ) {
        List<NameValuePair> params = new ArrayList<>();
        //获取access_token
        String accessToken = remoteCallService.getAccessToken(corpId, secret);
        params.add(new BasicNameValuePair(WeChatConstant.WE_CHAT_ACCESS_TOKEN, accessToken));

        String result = "";
        try {
            switch (method) {
                case "create":
                    result = RestTemplateBean.doPost(WeChatConstant.getWeChatPostUrl(WeChatConstant.TAG_CREATE, params),
                            JSONObject.fromObject(tag));
                    break;
                case "update":
                    result = RestTemplateBean.doPost(WeChatConstant.getWeChatPostUrl(WeChatConstant.TAG_UPDATE, params),
                            JSONObject.fromObject(tag));
                    break;
                case "delete":
                    params.add(new BasicNameValuePair("tagid", tag.getTagid()));
                    result = RestTemplateBean.doGet(WeChatConstant.TAG_DELETE, params);
                    break;
                case "get":
                    params.add(new BasicNameValuePair("tagid", tag.getTagid()));
                    result = RestTemplateBean.doGet(WeChatConstant.TAG_GET, params);
                    break;
                case "addtagusers":
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.TAG_ADD_TAG_USERS, params),
                            JSONObject.fromObject(tag));
                    break;
                case "deltagusers":
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.TAG_DEL_TAG_USERS, params),
                            JSONObject.fromObject(tag));
                    break;
                case "list":
                    params.add(new BasicNameValuePair("tagid", tag.getTagid()));
                    result = RestTemplateBean.doGet(WeChatConstant.TAG_LIST, params);
                    break;
                default:
                    throw new Exception("url 调用方法缺失");
            }
            logger.info("=============result:{}", result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * syncuser:      增量更新成员
     * <p>  media_id 上传的csv文件的media_id</p>
     * <p>  callback 回调信息。如填写该项则任务完成后，通过callback推送事件给企业。具体请参考应用回调模式中的相应选项</p>
     * <p>
     * replaceuser:      全量覆盖成员
     * <p>  media_id 上传的csv文件的media_id</p>
     * <p>  callback 回调信息。如填写该项则任务完成后，通过callback推送事件给企业。具体请参考应用回调模式中的相应选项</p>
     * <p>
     * replaceparty:      全量覆盖部门
     * <p>  media_id 上传的csv文件的media_id</p>
     * <p>  callback 回调信息。如填写该项则任务完成后，通过callback推送事件给企业。具体请参考应用回调模式中的相应选项</p>
     * <p>
     * getresult:        获取异步任务结果
     * <p>  jobid 异步任务id，最大长度为64字节</p>
     */
    @RequestMapping(value = "batch/{method}", method = RequestMethod.POST)
    public String batch(
            @PathVariable("method") String method, @RequestParam(value = "corpId") String corpId,
            @RequestParam(value = "secret") String secret, @RequestParam(value = "media_id") String mediaId,
            @RequestParam(value = "callback") String callback, @RequestParam(value = "jobid") String jobId
    ) {
        List<NameValuePair> params = new ArrayList<>();
        //获取access_token
        String accessToken = remoteCallService.getAccessToken(corpId, secret);
        params.add(new BasicNameValuePair(WeChatConstant.WE_CHAT_ACCESS_TOKEN, accessToken));

        String result = "";
        try {
            JSONObject batch = new JSONObject();
            switch (method) {
                case "syncuser":
                    batch.put("media_id", mediaId);
                    batch.put("callback", callback);
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.BATCH_SYNC_USER, params), batch);
                    break;
                case "replaceuser":
                    batch.put("media_id", mediaId);
                    batch.put("callback", callback);
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.BATCH_REPLACE_USER, params), batch);
                    break;
                case "replaceparty":
                    batch.put("media_id", mediaId);
                    batch.put("callback", callback);
                    result = RestTemplateBean.doPost(
                            WeChatConstant.getWeChatPostUrl(WeChatConstant.BATCH_REPLACE_PARTY, params), batch);
                    break;
                case "getresult":
                    params.add(new BasicNameValuePair("jobid", jobId));
                    result = RestTemplateBean.doGet(WeChatConstant.BATCH_GET_RESULT, params);
                    break;
                default:
                    throw new Exception("url 调用方法缺失");
            }
            logger.info("=============result:{}", result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    //    /**
    //     * upload:      上传临时素材文件
    //     * <p>  type 媒体文件类型，分别有图片（image）、语音（voice）、视频（video），普通文件(file)</p>
    //     * <p>  media form-data中媒体文件标识，有filename、filelength、content-type等信息</p>
    //     * <p>
    //     * replaceuser:      全量覆盖成员
    //     * <p>  media_id 上传的csv文件的media_id</p>
    //     * <p>  callback 回调信息。如填写该项则任务完成后，通过callback推送事件给企业。具体请参考应用回调模式中的相应选项</p>
    //     * <p>
    //     * replaceparty:      全量覆盖部门
    //     * <p>  media_id 上传的csv文件的media_id</p>
    //     * <p>  callback 回调信息。如填写该项则任务完成后，通过callback推送事件给企业。具体请参考应用回调模式中的相应选项</p>
    //     * <p>
    //     * getresult:        获取异步任务结果
    //     * <p>  jobid 异步任务id，最大长度为64字节</p>
    //     */
    //    @RequestMapping(value = "media/{method}", method = RequestMethod.POST)
    //    public String media(HttpServletRequest request, @PathVariable("method") String method) {
    //        String accessToken = (String) request.getSession().getAttribute(WeChatConstant.WE_CHAT_accessToken);
    //        List<NameValuePair> params = new ArrayList<>();
    //        params.add(new BasicNameValuePair(WeChatConstant.WE_CHAT_ACCESS_TOKEN, accessToken));
    //
    //        String result = "";
    //        try {
    //            switch (method) {
    //                case "upload":
    //                    params.add(new BasicNameValuePair("type", request.getParameter("type")));
    //                    params.add(new BasicNameValuePair("callback", request.getParameter("callback")));
    //                    result = HttpClientUtil.doPost(WeChatConstant.BATCH_SYNC_USER, params);
    //                    break;
    //                case "replaceuser":
    //                    params.add(new BasicNameValuePair("media_id", request.getParameter("media_id")));
    //                    params.add(new BasicNameValuePair("callback", request.getParameter("callback")));
    //                    result = HttpClientUtil.doPost(WeChatConstant.BATCH_REPLACE_USER, params);
    //                    break;
    //                case "replaceparty":
    //                    params.add(new BasicNameValuePair("media_id", request.getParameter("media_id")));
    //                    params.add(new BasicNameValuePair("callback", request.getParameter("callback")));
    //                    result = HttpClientUtil.doPost(WeChatConstant.BATCH_REPLACE_PARTY, params);
    //                    break;
    //                case "getresult":
    //                    params.add(new BasicNameValuePair("jobid", request.getParameter("jobid")));
    //                    result = RestTemplateBean.doGet(WeChatConstant.BATCH_GET_RESULT, params);
    //                    break;
    //                default:
    //                    throw new Exception("url 调用方法缺失");
    //            }
    //      } catch (Exception e) {
    //          logger.error(e.getMessage(), e);
    //      }
    //        return result;
    //    }
}
