UserController.java 12.7 KB
package vion.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import vion.Global;
import vion.enums.ResultEnum;
import vion.model.Store;
import vion.model.Task;
import vion.model.User;
import vion.service.IStoreSerrvice;
import vion.service.ITaskSerrvice;
import vion.service.IUserSerrvice;
import vion.utils.ResultUtil;

import java.util.*;


@RestController
@RequestMapping(Global.BASE_URL)
public class UserController {


    @Value("${appkey:}")
    private String appkey;
    @Value("${appsecret:}")
    private String appsecret;
    @Value("${agentid:}")
    private Long agentid;
    @Value("${dingurl:}")
    private String dingurl;
    @Value("${CorpId:}")
    private String CorpId;
    @Value("${SSOsecret:}")
    private String SSOsecret;

    @Autowired
    private IUserSerrvice userSerrvice;
    @Autowired
    private ITaskSerrvice taskSerrvice;
    @Autowired
    private IStoreSerrvice storeSerrvice;

    @GetMapping("/users")
    @ResponseBody
    public Object getUserList(@RequestParam(name = "pageNum")Integer pageNum,
                              @RequestParam(name = "pageSize")Integer pageSize){
        //pageNum当前页,pageSize每页条数
        Page page= PageHelper.startPage(pageNum,pageSize);
        List<User> userList =userSerrvice.list();

        userList.sort(Comparator.comparing(User::getId));
        PageInfo pageInfo=new PageInfo<>(page);
        pageInfo.setList(userList);

        if (pageInfo != null) {
            return ResultUtil.success(pageInfo);
        } else {
            return ResultUtil.error(ResultEnum.SELECT_ERROR);
        }
    }


    @GetMapping("/user")
    @ResponseBody
    public Object getUserByID(@RequestParam(name = "id")Integer id){

        User user=userSerrvice.getById(id);

        if (user != null) {
            return ResultUtil.success(user);
        } else {
            return ResultUtil.error(ResultEnum.SELECT_ERROR);
        }
    }

    @PostMapping("/login")
    @ResponseBody
    public Object getUser(@RequestBody User data){

        try {
            QueryWrapper<User> wrapper=new QueryWrapper<>();
            wrapper.eq("username",data.getUsername());
            wrapper.eq("password",data.getPassword());
            User user=userSerrvice.getOne(wrapper);

            if (user != null) {
                Global.USERNAME_MAP.put(user.getUserid(),user);
                return ResultUtil.success(user);
            } else {
                return ResultUtil.error(ResultEnum.SELECT_ERROR);
            }

        } catch (Exception e) {
        return ResultUtil.error(ResultEnum.SELECT_ERROR);
    }

    }

    @PostMapping("/users")
    @ResponseBody
    public Object getUserByID(@RequestBody User data){
       try {
            if(data.getId()==null){
                userSerrvice.save(data);
                return ResultUtil.success();
            }else{
                data.setModifyTime(new Date());
                User user1=userSerrvice.saveAndReturn(data);
                return ResultUtil.success(user1);
            }

        }catch (Exception e) {
            return ResultUtil.error(ResultEnum.SELECT_ERROR);
        }
    }


    //获取钉钉token
    public String getToken(){

        DingTalkClient client=new DefaultDingTalkClient(dingurl+"/gettoken");
        OapiGettokenRequest req=new OapiGettokenRequest();
        req.setAppkey(appkey);
        req.setAppsecret(appsecret);
        try {
            OapiGettokenResponse rep=client.execute(req);

            return rep.getAccessToken();
        } catch (ApiException e) {
            e.printStackTrace();
            return  null;
        }
    }

    //获取钉钉在职员工列表
    public void getDingUserList(){
        //获取token
        String access_token=getToken();
        String userIds="";

        Long offset=0L;//分页游标,从0开始
        Boolean flag=true;
        //一次最多获取50个。所以多次获取
        while(flag){
            //获取在职员工id集合
            DingTalkClient client=new DefaultDingTalkClient(dingurl+"/topapi/smartwork/hrm/employee/queryonjob");
            OapiSmartworkHrmEmployeeQueryonjobRequest req=new OapiSmartworkHrmEmployeeQueryonjobRequest();
            req.setStatusList("2,3,5,-1");
            req.setOffset(offset);
            req.setSize(50L);

            try {
                OapiSmartworkHrmEmployeeQueryonjobResponse rep=client.execute(req,access_token);
                if(rep.getSuccess()==true){
                   List<String> userList= rep.getResult().getDataList();
                   if(rep.getResult().getNextCursor()!=null){
                       //设置下一页的游标
                       offset=rep.getResult().getNextCursor();
                   }else{
                       flag=false;
                   }
                   //用户ID拼接
                    for(int j=0;j<userList.size();j++){
                        userIds+=userList.get(j)+",";
                    }
                }

            } catch (ApiException e) {
                e.printStackTrace();
            }
        }

        //根据在职员工id获取员工信息
        DingTalkClient client = new DefaultDingTalkClient(dingurl+"/topapi/smartwork/hrm/employee/v2/list");
        OapiSmartworkHrmEmployeeV2ListRequest req = new OapiSmartworkHrmEmployeeV2ListRequest();
        req.setUseridList(userIds.substring(0,userIds.length()-1));
        req.setFieldFilterList("sys00-name,sys00-mobile");//用户名,手机号
        req.setAgentid(agentid);

        try {
            OapiSmartworkHrmEmployeeV2ListResponse rep=client.execute(req,access_token);

            if(rep.getSuccess()==true){
                //用户信息
                User user=new User();

                //钉钉用户集合
               List<OapiSmartworkHrmEmployeeV2ListResponse.EmpRosterFieldVo> empRosterFieldVoList= rep.getResult();

               for(int m=0;m<empRosterFieldVoList.size();m++){
                   OapiSmartworkHrmEmployeeV2ListResponse.EmpRosterFieldVo empRosterFieldVo=empRosterFieldVoList.get(m);
                   user.setUserid(empRosterFieldVo.getUserid());

                   List<OapiSmartworkHrmEmployeeV2ListResponse.EmpFieldDataVo> empFieldDataVoList= empRosterFieldVo.getFieldDataList();
                   for(int n=0;n<empFieldDataVoList.size();n++){
                       OapiSmartworkHrmEmployeeV2ListResponse.EmpFieldDataVo empFieldDataVo=empFieldDataVoList.get(n);
                       //根据fieldcode判断用户属性
                       if(empFieldDataVo.getFieldCode().equals("sys00-name")){
                           user.setUsername(empFieldDataVo.getFieldValueList().get(0).getValue());
                       }
                       else if(empFieldDataVo.getFieldCode().equals("sys00-mobile")){
                           user.setPhone(empFieldDataVo.getFieldValueList().get(0).getValue());
                       }
                   }
                   //判断用户是否已经添加过
                   //User userInfo=userDao.getUserByUserid(empRosterFieldVo.getUserid());
                   User userInfo=userSerrvice.getOne(
                           Wrappers.<User>lambdaQuery()
                                   .eq(User::getUserid,empRosterFieldVo.getUserid()));
                   if(userInfo!=null){
                       user.setModifyTime(new Date());
                      // userDao.updateUserByUserid(user);
                       userSerrvice.saveOrUpdate(user);
                   }else {
                       userSerrvice.save(user);
                   }
               }
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }

    //钉钉消息推送
    public String sendMessage(String userid,Integer task_id){

        DingTalkClient client=new DefaultDingTalkClient(dingurl+"/topapi/message/corpconversation/asyncsend_v2");

        try {

            //获取token
           String access_token= getToken();
            //获取工单信息
           // Task task=taskDao.getTaskByID(task_id);
            Task task=taskSerrvice.getById(task_id);
           // User user=userDao.getUserById(task.getRepair_people());
            User user=userSerrvice.getById(task.getRepairPeople());
            //获取门店信息
            Store store=storeSerrvice.getById(task.getStoreId());

            OapiMessageCorpconversationAsyncsendV2Request request=new OapiMessageCorpconversationAsyncsendV2Request();
            request.setAgentId(agentid);
            request.setUseridList(userid);
            request.setToAllUser(false);

            OapiMessageCorpconversationAsyncsendV2Request.Msg msg=new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("text");
            msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
            msg.setActionCard(new OapiMessageCorpconversationAsyncsendV2Request.ActionCard());
            msg.getActionCard().setTitle("工单派单");
            msg.getActionCard().setMarkdown("门店信息:"+store.getName());//标题
            msg.getActionCard().setSingleTitle(
                    "报修人:"+user.getUsername()+
                    "\\n联系方式:"+task.getRepairPhone()+
                    "\\n故障描述:"+task.getFaultDescription());//工单派件内容
            msg.getActionCard().setSingleUrl("https://www.dingtalk.com");
            msg.setMsgtype("action_card");
            request.setMsg(msg);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, access_token);
            System.out.println(rsp.getBody());

            return  null;
        } catch (ApiException e) {
            e.printStackTrace();
            return  null;
        }
    }

    /**
     * 应用管理后台免登
     * @author openapi@dingtalk
     *
     */


        @RequestMapping(value = "/getAdminInfo", method = RequestMethod.GET)
        public Object getAdminInfo(@RequestParam("code")String requestAuthCode) {

            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sso/gettoken");
            OapiSsoGettokenRequest request = new OapiSsoGettokenRequest();
            // 企业Id
            request.setCorpid(CorpId);
            //秘钥SSOsecret
            //这里必须填写专属的SSOsecret。
            request.setCorpsecret(SSOsecret);
            request.setHttpMethod("GET");
            OapiSsoGettokenResponse response = null;
            try {
                response = client.execute(request);
            } catch (ApiException e) {
                e.printStackTrace();
                return null;
            }
            // 获取企业的access_token
            String access_token = response.getAccessToken();
            // 获取应用管理员的身份信息
            OapiSsoGetuserinfoResponse getAdminInfo = getAdminUserInfo(requestAuthCode, access_token);
            Map<String, Object> returnMap = new HashMap<String, Object>();
            returnMap.put("info", getAdminInfo);
            return returnMap;
        }

        /**
         * 根据保存的code值和获取的access_token,获取应用管理身份信息
         * openapi@dingtalk
         * @param code
         * @param access_token
         * @return
         * OapiSsoGetuserinfoResponse
         * 2020-11-3
         */
        public OapiSsoGetuserinfoResponse getAdminUserInfo(String code,String access_token) {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sso/getuserinfo");
            OapiSsoGetuserinfoRequest request = new OapiSsoGetuserinfoRequest();
            request.setCode(code);
            request.setHttpMethod("GET");
            OapiSsoGetuserinfoResponse response;
            try {
                response = client.execute(request, access_token);
            } catch (ApiException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
            return response;
        }

}