package com.hotent.uc.manager.impl;

import cn.hutool.json.JSONObject;
import com.aliyun.dingtalkcontact_1_0.models.GetUserHeaders;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetUserTokenResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dingtalk.api.response.CorpReportListResponse;
import com.google.gson.JsonObject;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import com.hotent.base.util.UniqueIdUtil;
import com.hotent.uc.dao.ScanLoginDao;
import com.hotent.uc.dao.UserDao;
import com.hotent.uc.dao.UserUniteDao;
import com.hotent.uc.manager.ScanLoginManager;
import com.hotent.uc.model.ScanLogin;
import com.hotent.uc.model.User;
import com.hotent.uc.model.UserUnite;
import com.hotent.uc.util.QrCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.UUID;

/**
 * 用户与外部通讯录关系表 服务实现类
 *
 * @company 广州宏天软件股份有限公司
 * @author pangquan
 * @since 2020-10-30
 */
@Service
public class ScanLoginManagerImpl extends BaseManagerImpl<ScanLoginDao, ScanLogin> implements ScanLoginManager {

    @Value("${dingSetting.scanUrl}")
    private String scanUrl;
    @Value("${dingSetting.appkey}")
    private String clientId;//钉钉应用key
    @Value("${dingSetting.appSecret}")
    private String appSecret;//钉钉应用密钥
    @Value("${dingSetting.saveQrcodeUrl}")
    private String saveQrcodeUrl;
    @Value("${dingSetting.redirectUri}")
    private String redirectUri;
    @Resource
    private ScanLoginDao scanLoginDao;
    @Resource
    private UserDao userDao;
    private static String SUCCESS_STR="1";
    private static String ERROR_STR="0";

    @Override
    public ScanLogin productScanLogin(String type) {
        try {
            String picPath = ResourceUtils.getURL("classpath:").getPath()+"static/";
            String path = picPath+"dingdinglogo.png";
            String uid=UniqueIdUtil.getSuid();
            String redirectUriEno=java.net.URLEncoder.encode(redirectUri,"utf-8");
            //生成二维码扫码跳转链接
            String qrcodeUrl=scanUrl+"&redirect_uri="+redirectUriEno+"&client_id="+clientId+"&state="+uid+"_"+type;
            String saveImgPath=saveQrcodeUrl+"/"+uid+".jpg";
            //生成二维码
            QrCodeUtils.encode(qrcodeUrl,path,saveImgPath,true);
            String fileAccessUrl="/qrcode/"+uid+".jpg";//二维码地址
            ScanLogin scanLogin=new ScanLogin();
            scanLogin.setId(uid);
            scanLogin.setQrCodeUrl(fileAccessUrl);
            scanLogin.setState(ERROR_STR);
            scanLogin.setType(type);
            scanLogin.setScanIng(ERROR_STR);
//            scanLoginDao.addScanLoginInfo(scanLogin);
            this.saveOrUpdate(scanLogin);

            return scanLogin;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public User getDingUserInfo(String code) {
        try {
            com.aliyun.dingtalkoauth2_1_0.Client client  = authClient();
            GetUserTokenRequest getUserTokenRequest = new GetUserTokenRequest()
                    //应用基础信息-应用信息的AppKey,请务必替换为开发的应用AppKey
                    .setClientId(clientId)
                    //应用基础信息-应用信息的AppSecret，,请务必替换为开发的应用AppSecret
                    .setClientSecret(appSecret)
                    .setCode(code)
                    .setGrantType("authorization_code");
            GetUserTokenResponse getUserTokenResponse = client.getUserToken(getUserTokenRequest);
            //获取用户个人token
            String accessToken = getUserTokenResponse.getBody().getAccessToken();
            String userInfo=getUserinfo(accessToken);
            log.debug("userInfo==="+userInfo);
            if(StringUtil.isNotEmpty(userInfo)){
                cn.hutool.json.JSONObject jsonObject=new cn.hutool.json.JSONObject(userInfo);
                String mobile = (String) jsonObject.get("mobile");
                String name= (String) jsonObject.get("nick");
                if(StringUtil.isNotEmpty(mobile)){
                    User user=userDao.getByMobile(mobile);
                    log.debug("user==="+user);
                    return user;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void updateScanLoginInfo(String scanId,String userId) {
        LambdaQueryWrapper<ScanLogin> qw=new LambdaQueryWrapper<>();
        qw.eq(ScanLogin::getId,scanId);
        ScanLogin scanLogin=this.baseMapper.selectOne(qw);
        if(scanLogin!=null){
            scanLogin.setState(SUCCESS_STR);
            scanLogin.setUserId(userId);
            scanLogin.setCreateTime(LocalDateTime.now());
            this.saveOrUpdate(scanLogin);
        }
    }

    @Override
    public User queryScanLoginInfo(String scanId) {
        LambdaQueryWrapper<ScanLogin> qw=new LambdaQueryWrapper<>();
        qw.eq(ScanLogin::getId,scanId);
        ScanLogin scanLogin=this.baseMapper.selectOne(qw);
        if(scanLogin!=null){
            String userId=scanLogin.getUserId();
            if(StringUtil.isNotEmpty(userId)){
                String account=userDao.getAccountByUserId(userId);
                return userDao.getByAccount(account);
            }
        }
        return null;
    }

    @Override
    public CommonResult<?> queryScanIng(String scanId) {
        LambdaQueryWrapper<ScanLogin> qw=new LambdaQueryWrapper<>();
        qw.eq(ScanLogin::getId,scanId);
        ScanLogin scanLogin=this.baseMapper.selectOne(qw);
        if(scanLogin!=null){
            return new CommonResult<>(true,"成功",scanLogin);
        }
        return new CommonResult<>(false,"失败",null);
    }

    @Override
    public CommonResult<?> putScanResult(String scanId) {
        LambdaQueryWrapper<ScanLogin> qw=new LambdaQueryWrapper<>();
        qw.eq(ScanLogin::getId,scanId.split("_")[0]);
        ScanLogin scanLogin=this.baseMapper.selectOne(qw);
        scanLogin.setScanIng(SUCCESS_STR);
        this.saveOrUpdate(scanLogin);
        return new CommonResult<>(true,"成功",scanLogin);
    }

    /**
     * 获取用户个人信息
     * @param accessToken
     * @return
     * @throws Exception
     */
    public String getUserinfo(String accessToken) throws Exception {
        com.aliyun.dingtalkcontact_1_0.Client client = contactClient();
        GetUserHeaders getUserHeaders = new GetUserHeaders();
        getUserHeaders.xAcsDingtalkAccessToken = accessToken;
        //获取用户个人信息，如需获取当前授权人的信息，unionId参数必须传me
        cn.hutool.json.JSONObject jsonObject= new cn.hutool.json.JSONObject(client.getUserWithOptions("me", getUserHeaders, new RuntimeOptions()).getBody());
        String me = jsonObject.toString();
        System.out.println(me);
        return me;
    }
    public static com.aliyun.dingtalkoauth2_1_0.Client authClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }
    public static com.aliyun.dingtalkcontact_1_0.Client contactClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkcontact_1_0.Client(config);
    }
}
