package com.fs.qw.service.impl;

import com.fs.common.core.domain.R;
import com.fs.crm.service.ICrmCustomerService;
import com.fs.qw.domain.QwCompany;
import com.fs.qw.mapper.QwExternalContactMapper;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.param.QwConfigSignatureParam;
import com.fs.qw.service.IQwCompanyService;
import com.fs.qw.service.IQwJsApiService;
import com.fs.qwApi.Result.QwJsapiTicketResult;
import com.fs.qwApi.param.QwCustomerDetailParam;
import com.fs.qwApi.param.QwExternalContactHParam;
import com.fs.qwApi.service.QwApiService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URI;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
public class QwJsApiServiceImpl implements IQwJsApiService {

    org.slf4j.Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private QwApiService qwApiService;

    @Autowired
    private ICrmCustomerService crmCustomerService;
    @Autowired
    QwExternalContactMapper qwExternalContactMapper;

    @Autowired
    IQwCompanyService iQwCompanyService;
    @Autowired
    QwUserMapper qwUserMapper;
    /**
     * 侧边栏-获取企业 签名
     */
    @Override
    public R getQwJsapiTicket(QwConfigSignatureParam qwConfigSignatureParam) throws Exception {

        logger.info("jsapiTicket:企业微信传参"+qwConfigSignatureParam);

        try {

            QwCompany qwCompany = iQwCompanyService.selectQwCompanyByCorpId(qwConfigSignatureParam.getCorpId());
            String appSecret = qwCompany.getOpenSecret();

            QwJsapiTicketResult jsapiTicket = qwApiService.getJsapiTicket(qwConfigSignatureParam.getCorpId(),appSecret);
            QwJsapiTicketResult jsapiTicketApp = qwApiService.getJsapiTicketApp(qwConfigSignatureParam.getCorpId(),appSecret);

            //获取企业微信当前登录人的userId
            QwJsapiTicketResult useridResult=new QwJsapiTicketResult();

            if (qwConfigSignatureParam.getIsGetUserId()==1){
                useridResult = qwApiService.getQwUserid(qwConfigSignatureParam.getCode(), qwConfigSignatureParam.getCorpId(),appSecret);
            }
            //获取登录员工的OAuth2 后获取url

            if (qwConfigSignatureParam.getIsGetUserId()==1 && useridResult.getErrcode()!=0){
                logger.error("获取企业当前登录人的userid失败:"+useridResult.getErrmsg());
                return R.error("获取企业当前登录人的userid:"+jsapiTicket.getErrmsg());
            }
            if (jsapiTicket.getErrcode()!=0){
                logger.error("获取企业的jsapi_ticket失败:"+jsapiTicket.getErrmsg());
                return R.error("获取企业的jsapi_ticket失败:"+jsapiTicket.getErrmsg());
            }
            if (jsapiTicketApp.getErrcode()!=0){
                logger.error("获取应用的jsapi_ticket失败:"+jsapiTicketApp.getErrmsg());
                return R.error("获取应用的jsapi_ticket失败:"+jsapiTicketApp.getErrmsg());
            }

            String nonceStr = createNonceStr();
            String timestamp = createTimestamp();

            // 生成签名
            String signatureOne = generateSignature(jsapiTicket.getTicket(), nonceStr, timestamp, qwConfigSignatureParam.getUrl());
            String signatureTwo = generateSignature(jsapiTicketApp.getTicket(), nonceStr, timestamp, qwConfigSignatureParam.getUrl());


            Map<String, String> config = new HashMap<>();
            config.put("nonceStr", nonceStr);
            config.put("timestamp", timestamp);
            config.put("configSignature", signatureOne);
            config.put("agentConfigSignature", signatureTwo);
            config.put("corpId", qwConfigSignatureParam.getCorpId());
            config.put("agentId", qwCompany.getServerAgentId());
            config.put("userid", useridResult.getUserId());
            logger.info("侧边栏-获取企业-签名成功-:{}",config);
            return R.ok().put("config",config);
        }catch (Exception e){
            logger.error("侧边栏-获取企业-签名失败",e);
            return R.error();
        }

    }

    /**
     *   根据userid和外部联系人id获取到客户详情
     */
    @Override
    public R getCustomerDetailsH5(QwCustomerDetailParam param) {

        return R.ok().put("data",crmCustomerService.getCustomerDetailsH5(param));
    }

    @Override
    public R getQwExternalContactDetails(QwExternalContactHParam param) {
        return R.ok().put("data",qwExternalContactMapper.getQwExternalContactDetails(param));
    }


    // 合成签名
    private static String generateSignature(String jsapiTicket, String nonceStr, String timestamp, String url) throws Exception {
        String string1 = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonceStr +
                "&timestamp=" + timestamp +
                "&url=" + url;

        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(string1.getBytes("UTF-8"));
        return byteToHex(crypt.digest());
    }

    // 将字节数组转换为十六进制字符串
    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    //随机数
    private static String createNonceStr() {
        return UUID.randomUUID().toString().replace("-","");
    }

    //时间戳
    private static String createTimestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    //获取url上的参数
    public static Map<String, String> getURLQueryParamsUrl(String url) throws URISyntaxException {
        URI uri = new URI(url);
        String query = uri.getQuery();
        String[] pairs = query.split("&");
        Map<String, String> queryParams = new HashMap<>();

        for (String pair : pairs) {
            int idx = pair.indexOf("=");
            queryParams.put(pair.substring(0, idx), pair.substring(idx + 1));
        }

        return queryParams;
    }
}
