package com.cool.store.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.models.*;
import com.aliyun.sdk.service.dysmsapi20170525.*;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.cool.store.dao.EnterpriseUserDAO;
import com.cool.store.dto.message.SendMessageDTO;
import com.cool.store.enums.*;
import com.cool.store.mq.producer.SimpleMessageService;
import com.cool.store.request.AuditResultRequest;
import com.cool.store.utils.UUIDUtils;
import com.cool.store.utils.poi.constant.Constants;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * @author zhangchenbiao
 * @FileName: CommonService
 * @Description:
 * @date 2024-03-20 17:09
 */
@Slf4j
@Service
public class CommonService {

    @Autowired
    private ApplicationContext applicationContext;
    @Resource
    private EnterpriseUserDAO enterpriseUserDAO;
    @Resource
    private SimpleMessageService simpleMessageService;
    @Value("${coolstore.page.domain}")
    private String coolStoreDomainUrl;
    @Value("${cool.app.id}")
    private String appId;
    @Value("${mybatis.configuration.variables.enterpriseId}")
    private String enterpriseId;
    @Value("${enterprise.dingCorpId}")
    private String dingCorpId;
    @Value("${aliyun.sms.accessKeyId}")
    private String smsAccessKeyId;
    @Value("${aliyun.sms.accessKeySecret}")
    private String smsAccessKeySecret;
    @Value("${aliyun.sms.signName}")
    private String signName;

    public LineFlowService getLineFlowService(Integer workflowSubStage){
        WorkflowSubStageEnum workflowSubStageEnum = WorkflowSubStageEnum.getWorkflowSubStageEnum(workflowSubStage);
        return (LineFlowService)applicationContext.getBean(workflowSubStageEnum.getClazz());
    }

    public AuditResultService getAuditService(AuditResultRequest request) {
        String flag = splitMethod(request.getKdzBusinessId());
        AuditEnum auditEnum = AuditEnum.getWorkflowSubStageEnum(flag);
        return (AuditResultService) applicationContext.getBean(auditEnum.getClazz());
    }

    public void sendMessageAsync(List<String> userIds, MessageEnum message, Map<String, String> requestMap){
        CompletableFuture.runAsync(() -> sendMessage(userIds, message, requestMap));
    }

    public void sendMessage(List<String> userIds, MessageEnum message, Map<String, String> requestMap){
        log.info("message:{}, request:{}, userIds:{}", message.getTitle(), JSONObject.toJSONString(requestMap), JSONObject.toJSONString(userIds));
        if(CollectionUtils.isEmpty(userIds)){
            return;
        }
        userIds = userIds.stream().filter(StringUtils::isNotBlank).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(userIds)){
            return;
        }
        try {
            String messageUrl = message.getMessageUrl(coolStoreDomainUrl, appId, dingCorpId, requestMap);
            if(StringUtils.isBlank(messageUrl)){
                log.info("获取通知url为空");
                return;
            }
            SendMessageDTO messageDTO = new SendMessageDTO();
            messageDTO.setCorpId(dingCorpId);
            messageDTO.setUserIds(String.join(Constants.COMMA, userIds));
            messageDTO.setOutBusinessId(UUIDUtils.get32UUID());
            messageDTO.setAppType("dingding2");
            JSONObject map = new JSONObject();
            map.put("message_url", messageUrl);
            map.put("pcMessageUrl", messageUrl);
            JSONObject headJson = new JSONObject();
            headJson.put("bgcolor", "FFBBBBBB");
            map.put("head", headJson);
            JSONObject body = new JSONObject();
            body.put("title", message.getTitle());
            body.put("image", message.getImageUrl());
            body.put("content", message.getContent(requestMap));
            map.put("body",body);
            messageDTO.setOaJson(map);
            simpleMessageService.send(JSONObject.toJSONString(messageDTO), RocketMqTagEnum.STORE_DING_QUEUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void sendSms(String poneNumber, SMSMsgEnum templateCode){
        sendSms(Arrays.asList(poneNumber), templateCode, null);
    }

    public void sendSms(String poneNumber, SMSMsgEnum templateCode, Map<String, String> templateParamMap){
        sendSms(Arrays.asList(poneNumber), templateCode, templateParamMap);
    }

    public void sendSmsAsync(String poneNumber, SMSMsgEnum templateCode, Map<String, String> templateParamMap){
        CompletableFuture.runAsync(() -> sendSms(Arrays.asList(poneNumber), templateCode, templateParamMap));
    }

    public void sendSms(List<String> poneNumbers, SMSMsgEnum templateCode, Map<String, String> templateParamMap){
        log.info("templateCode:{}, request:{}, poneNumbers:{}", templateCode.getTitle(), JSONObject.toJSONString(templateParamMap), JSONObject.toJSONString(poneNumbers));
        if(CollectionUtils.isEmpty(poneNumbers)){
            return;
        }
        List<String> signNameList = new ArrayList<>();
        signNameList.add("酷店掌");
        AsyncClient client = null;
        try {
            StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                    .accessKeyId(smsAccessKeyId)
                    .accessKeySecret(smsAccessKeySecret)
                    .build());
            client = AsyncClient.builder()
                    .region("cn-hangzhou")
                    .credentialsProvider(provider)
                    .overrideConfiguration(
                            ClientOverrideConfiguration.create()
                                    .setEndpointOverride("dysmsapi.aliyuncs.com")
                    )
                    .build();
            SendBatchSmsRequest sendBatchSmsRequest = SendBatchSmsRequest.builder()
                    .phoneNumberJson(JSONObject.toJSONString(poneNumbers))
                    .signNameJson(JSONObject.toJSONString(signNameList))
                    .templateCode(templateCode.getTemplateCode())
                    .templateParamJson("[" + JSONObject.toJSONString(templateParamMap) + "]")
                    .build();
            CompletableFuture<SendBatchSmsResponse> response = client.sendBatchSms(sendBatchSmsRequest);
            SendBatchSmsResponse resp = response.get();
            log.info("短信发送templateCode:{}, response:{}", templateCode.getTemplateCode(), JSONObject.toJSONString(resp));
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally {
            if(Objects.isNull(client)){
                client.close();
            }
        }
        log.info("短信发送成功（已过滤）");
    }

    public static String splitMethod(String kdzBusinessId) {
        String[] split = kdzBusinessId.split(Constants.D_LINE);
        if (split.length >= 2) {
            return split[0];
        } else {
            return null;
        }
    }

}
