package com.malk.service.dingtalk.impl;

import com.malk.server.dingtalk.DDConf;
import com.malk.server.dingtalk.DDR;
import com.malk.service.dingtalk.DDClient;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilToken;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class DDImplClient implements DDClient {

    @Autowired
    private DDConf ddConf;

    /**
     * 获取访问授权
     *
     * @apiNote https://open.dingtalk.com/document/personalapp-service/obtain-user-token
     */
    @Synchronized
    @Override
    public String getAccessToken() {
        String accessToken = UtilToken.get("invalid-token-dingtalk");
        if (StringUtils.isNotBlank(accessToken)) return accessToken;
        Map param = new HashMap();
        param.put("appkey", ddConf.getAppKey());
        param.put("appsecret", ddConf.getAppSecret());
        DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
        log.info("响应token, {}", r.getAccessToken());
        accessToken = r.getAccessToken();
        // token失效自动重置: DD重新调用会重置过期时间
        UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);
        return accessToken;
    }

    public String getAccessToken_PJSS() {
        //浦江基石
        String accessToken = UtilToken.get("invalid-token-dingtalk");
        if (StringUtils.isNotBlank(accessToken)) return accessToken;
        Map param = new HashMap();
        param.put("appkey", "dingraobfxqulra4mp9r");
        param.put("appsecret", "KN28UwWycxxCkKkug1x61lsWWAhEaNpQbc8efrgMKyNUXayw-O2sRxDkhh9LTh8y");
        DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
        log.info("响应token, {}", r.getAccessToken());
        accessToken = r.getAccessToken();
        // token失效自动重置: DD重新调用会重置过期时间
        UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);
        return accessToken;
    }


    @Override
    public String getAccessToken(String appKey, String appSecret) {
        Map param = UtilMap.map("appkey, appsecret", appKey, appSecret);
        DDR r = DDR.doGet("https://oapi.dingtalk.com/gettoken", null, param);
        log.info("响应token, {}", r.getAccessToken());
        return r.getAccessToken();
    }

    /**
     * token授权参数: 旧版本
     */
    @Override
    public Map initTokenParams() {
        return DDConf.initTokenParams(getAccessToken());
    }

    /**
     * token授权参数: 新版本
     */
    @Override
    public Map initTokenHeader() {
        return DDConf.initTokenHeader(getAccessToken());
    }

    public Map initTokenHeader_PJSS() {
        return DDConf.initTokenHeader(getAccessToken_PJSS());
    }

    /**
     * 获取jsapi_ticket
     *
     * @apiNote https://open.dingtalk.com/document/orgapp/obtain-jsapi_ticket
     */
    @Synchronized
    @Override
    public String getJsApiTicket(String accessToken) {
        String ticket = UtilToken.get("invalid-ticket-dingtalk");
        if (StringUtils.isNotBlank(ticket)) return ticket;
        DDR r = DDR.doGet("https://oapi.dingtalk.com/get_jsapi_ticket", null, UtilMap.map("access_token", accessToken));
        log.info("响应ticket, {}", r.getAccessToken());
        ticket = r.getTicket();
        // token失效自动重置: DD重新调用会重置过期时间
        UtilToken.put("invalid-ticket-dingtalk", ticket, r.getExpiresIn() * 1000L);
        return ticket;
    }

    /**
     * 通过免登码获取用户信息
     */
    @Override
    public Map getUserInfoByCode(String accessToken, String code) {
        return (Map) DDR.doPost("https://oapi.dingtalk.com/topapi/v2/user/getuserinfo", null, DDConf.initTokenParams(accessToken), UtilMap.map("code", code)).getResult();
    }


    public Map getusergroup( String userid) {

        Map param = new HashMap();
        param.put("appkey", "dingapqprcbwk5bvahc1");
        param.put("appsecret", "V_YgI8ZYx3lSf_Fw3qNH6k-U9umKhxglpPrnPkdb73CVrXWFme_SwUCdQxR2poFi");
        DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
        log.info("响应token, {}", r.getAccessToken());
       String accessToken = r.getAccessToken();
        // token失效自动重置: DD重新调用会重置过期时间
        UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);

        return (Map) DDR.doPost("https://oapi.dingtalk.com/topapi/attendance/getusergroup", null, DDConf.initTokenParams(accessToken), UtilMap.map("userid", userid)).getResult();
    }

    public  Map inset_hr_group(String type,String UserId,String grupid){
        Map  vlsumap= new HashMap();
        Map param = new HashMap();
        param.put("appkey", "dingapqprcbwk5bvahc1");
        param.put("appsecret", "V_YgI8ZYx3lSf_Fw3qNH6k-U9umKhxglpPrnPkdb73CVrXWFme_SwUCdQxR2poFi");
        DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
        log.info("响应token, {}", r.getAccessToken());
        String accessToken = r.getAccessToken();
        // token失效自动重置: DD重新调用会重置过期时间
        UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);

        Map param_post = new HashMap();

        param_post.put("op_user_id","683135622237866009");//操作人userId。
        param_post.put("group_id",grupid);//考勤组ID
        param_post.put("schedule_flag",0);//从哪天开始排班。0：从今天开始排班1：从明天开始排班
        if (type.equals("新增")){
            Map param_post_upda = new HashMap();
            String[] arr = {UserId};
            param_post_upda.put("add_users",UserId);
            param_post.put("update_param",param_post_upda);
        }else  if (type.equals("删除")){
            Map param_post_upda = new HashMap();
            String[] arr = {UserId};
            param_post_upda.put("remove_users",UserId);
            param_post.put("update_param",param_post_upda);
        }
        System.out.println("param_post:"+param_post);

        vlsumap= (Map) DDR.doPost("https://oapi.dingtalk.com/topapi/attendance/group/member/update", null, DDConf.initTokenParams(accessToken), param_post ).getResult();

       return  vlsumap;
    }

    public Map getleavestatus(String userid_list,long start_time,long end_time){
        Map param = new HashMap();
        param.put("appkey", "dingapqprcbwk5bvahc1");
        param.put("appsecret", "V_YgI8ZYx3lSf_Fw3qNH6k-U9umKhxglpPrnPkdb73CVrXWFme_SwUCdQxR2poFi");
        DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
        log.info("响应token, {}", r.getAccessToken());
        String accessToken = r.getAccessToken();
        // token失效自动重置: DD重新调用会重置过期时间
        UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);
        Map param_post = new HashMap();
        param_post.put("userid_list",userid_list);//操作人userId。
        param_post.put("start_time",start_time);//考勤组ID
        param_post.put("end_time",end_time);//从哪天开始排班。0：从今天开始排班1：从明天开始排班
        param_post.put("offset",0);//支持分页查询，与size参数同时设置时才生效，此参数代表偏移量，偏移量从0开始
        param_post.put("size",10);//支持分页查询，与offset参数同时设置时才生效，此参数代表分页大小，最大20。
        return  (Map) DDR.doPost("https://oapi.dingtalk.com/topapi/attendance/getleavestatus", null, DDConf.initTokenParams(accessToken), param_post ).getResult();
    };

   public Map getgroupquery(String op_user_id,String  group_id ){//考勤组部分信息如下图所示。调用本接口，可获取考勤组名称、考勤组主负责人和考勤类型等信息。
       op_user_id="683135622237866009";
       Map param = new HashMap();
       param.put("appkey", "dingapqprcbwk5bvahc1");
       param.put("appsecret", "V_YgI8ZYx3lSf_Fw3qNH6k-U9umKhxglpPrnPkdb73CVrXWFme_SwUCdQxR2poFi");
       DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
       log.info("响应token, {}", r.getAccessToken());
       String accessToken = r.getAccessToken();
       // token失效自动重置: DD重新调用会重置过期时间
       UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);
       Map param_post = new HashMap();
       param_post.put("op_user_id",op_user_id);//操作人userId。
       param_post.put("group_id",group_id);//考勤组ID
       return  (Map) DDR.doPost("https://oapi.dingtalk.com/topapi/attendance/group/query", null, DDConf.initTokenParams(accessToken), param_post ).getResult();
   };

    @Override
    public Map updateuploadss(String userid, String device_name, String device_id, String user_check_time) {
        Map param = new HashMap();
        param.put("appkey", "dingapqprcbwk5bvahc1");
        param.put("appsecret", "V_YgI8ZYx3lSf_Fw3qNH6k-U9umKhxglpPrnPkdb73CVrXWFme_SwUCdQxR2poFi");
        DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
        log.info("响应token, {}", r.getAccessToken());
        String accessToken = r.getAccessToken();
        // token失效自动重置: DD重新调用会重置过期时间
        UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);
        Map param_post = new HashMap();
        param_post.put("userid",userid);//需要上传打卡记录的员工userId
        param_post.put("device_name",device_name);//考勤机名称
        param_post.put("device_id",device_id);//考勤机ID
        param_post.put("user_check_time",user_check_time);//员工打卡的时间
        return  (Map) DDR.doPost("https://oapi.dingtalk.com/topapi/attendance/record/upload", null, DDConf.initTokenParams(accessToken), param_post ).getResult();

    }

    public Map  getupdatedata(String userid, LocalDate  work_date){
        Map param = new HashMap();
        param.put("appkey", "dingapqprcbwk5bvahc1");
        param.put("appsecret", "V_YgI8ZYx3lSf_Fw3qNH6k-U9umKhxglpPrnPkdb73CVrXWFme_SwUCdQxR2poFi");
        DDR r = (DDR) UtilHttp.doGet("https://oapi.dingtalk.com/gettoken", param, DDR.class);
        log.info("响应token, {}", r.getAccessToken());
        String accessToken = r.getAccessToken();
        // token失效自动重置: DD重新调用会重置过期时间
        UtilToken.put("invalid-token-dingtalk", accessToken, r.getExpiresIn() * 1000L);
        Map param_post = new HashMap();
        param_post.put("userid",userid);//获取考勤信息的员工userId
    param_post.put("work_date",work_date);//查询日期
        return  (Map)  DDR.doPost("https://oapi.dingtalk.com/topapi/attendance/getupdatedata", null, DDConf.initTokenParams(accessToken), param_post ).getResult();
    }

}