package thyyxxk.webserver.service.outpatient.wxapi;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import thyyxxk.webserver.config.exception.BizException;
import thyyxxk.webserver.service.TokenService;
import thyyxxk.webserver.utils.SnowFlakeId;
import thyyxxk.webserver.utils.WeComUtil;

import java.util.concurrent.ThreadLocalRandom;

@Service
@Slf4j
public class SendWxInfoService {
    private static final String SEND_MSG_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=ACCESS_TOKEN";
    private static final String CREATE_GROUP_URL = "https://qyapi.weixin.qq.com/cgi-bin/appchat/create?access_token=ACCESS_TOKEN";
    private static final String SEND_GROUP_MSG = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=ACCESS_TOKEN";
    private static final int AGENT_ID = 1000041;
    private static final int SAFE_MODE = 0;
    private final TokenService tokenService;
    private final RestTemplate template;

    @Autowired
    public SendWxInfoService(TokenService tokenService, RestTemplate template) {
        this.tokenService = tokenService;
        this.template = template;
    }

    public JSONObject sendCorpWxMsg(String touser, String content) {
        String weComToken = tokenService.getWeComSendMsgToken();
        if (StrUtil.isBlank(weComToken)) {
            JSONObject json = new JSONObject();
            json.put("errcode", -1);
            json.put("msg", "无法推送消息，没有企业微信token");
            return json;
        }
        String requestUrl = SEND_MSG_URL.replace("ACCESS_TOKEN", weComToken);
        JSONObject msgObj = new JSONObject();
        msgObj.put("content", content);
        JSONObject param = new JSONObject();
        param.put("agentid", AGENT_ID);
        param.put("touser", touser.replaceAll(",", "|"));
        param.put("toparty", "");
        param.put("totag", "");
        param.put("msgtype", "text");
        param.put("text", msgObj);
        param.put("safe", SAFE_MODE);
        String response = template.postForObject(requestUrl, param, String.class);
        JSONObject result = JSONObject.parseObject(response);
        log.info("推送企业信息消息：\n内容：{}\n结果：{}", param, result);
        return result;
    }

    public static @NotNull String generateRandomNumber(int length) {
        StringBuilder sb = new StringBuilder(length);
        ThreadLocalRandom random = ThreadLocalRandom.current();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(0, 10));  // 生成0到9之间的随机数字
        }
        return sb.toString();
    }

    public static @NotNull String generateRandomNumber() {
        return generateRandomNumber(6);
    }

    @Data
    public static class Verification {
        private String verificationCode;
        private String error;
    }

    public Verification sendResetPassword(String touser) {
        Verification v = new Verification();
        String weComToken = tokenService.getWeComSendMsgToken();
        if (StrUtil.isBlank(weComToken)) {
            v.setError("没有企业微信token");
            return v;
        }
        String requestUrl = SEND_MSG_URL.replace("ACCESS_TOKEN", weComToken);
        String verificationCode = generateRandomNumber();
        JSONObject msgObj = new JSONObject() {{
            put("content", StrUtil.format("重置密码\n您的验证码为：【{}】\n30分钟有效", verificationCode));
        }};
        JSONObject param = new JSONObject() {{
            put("touser", touser);
            put("msgtype", "text");
            put("agentid", AGENT_ID);
            put("safe", 0);
            put("text", msgObj);
        }};

        String response = template.postForObject(requestUrl, param, String.class);
        JSONObject result = JSONObject.parseObject(response);
        log.info("推送企业信息消息：\n内容：{}\n结果：{}", param, result);
        Integer errcode = result.getInteger("errcode");
        int a = null == errcode ? -1 : errcode;

        v.setVerificationCode(a == 0 ? verificationCode : null);
        v.setError(result.getString("errmsg"));
        return v;

    }


    public int sendCriticalValue(String touser, String content) {
        String weComToken = tokenService.getWeComSendMsgToken();
        if (StrUtil.isBlank(weComToken)) {
            log.error("无法推送危急值，没有企业微信token");
            return -1;
        }
        String requestUrl = SEND_MSG_URL.replace("ACCESS_TOKEN", weComToken);
        JSONObject msgObj = new JSONObject();
        msgObj.put("content", content);
        JSONObject param = new JSONObject();
        param.put("agentid", AGENT_ID);
        param.put("touser", touser);
        param.put("toparty", "");
        param.put("totag", "");
        param.put("msgtype", "text");
        param.put("text", msgObj);
        param.put("safe", SAFE_MODE);
        String response = template.postForObject(requestUrl, param, String.class);
        JSONObject result = JSONObject.parseObject(response);
        log.info("推送企业信息消息：\n内容：{}\n结果：{}", param, result);
        Integer errcode = result.getInteger("errcode");
        return null == errcode ? -1 : errcode;
    }


    public JSONObject createGroupChat(String name) {
        JSONObject msgobj = new JSONObject();
        String weComToken = tokenService.getWeComSendMsgToken();
        if (StrUtil.isBlank(weComToken)) {
            msgobj.put("errcode", -1);
            msgobj.put("msg", "无法创建企业微信群聊，没有企业微信token");
            return msgobj;
        }
        String url = CREATE_GROUP_URL.replace("ACCESS_TOKEN", weComToken);
        msgobj.put("name", name);
        msgobj.put("owner", "1038");
        JSONArray userlist = new JSONArray();
        userlist.add("1038");
        userlist.add("2801");
        msgobj.put("userlist", userlist);
        msgobj.put("chatid", SnowFlakeId.instance().nextId());
        String response = template.postForObject(url, msgobj, String.class);
        JSONObject result = JSONObject.parseObject(response);
        log.info("创建企业微信群聊：\n内容：{}\n结果：{}", msgobj, result);
        return result;
    }

    public JSONObject sendGroupMsg(String chatid, String content) {
        JSONObject msgobj = new JSONObject();
        String weComToken = tokenService.getWeComSendMsgToken();
        if (StrUtil.isBlank(weComToken)) {
            msgobj.put("errcode", -1);
            msgobj.put("msg", "无法发送企业微信群聊消息，没有企业微信token");
            return msgobj;
        }
        String url = SEND_GROUP_MSG.replace("ACCESS_TOKEN", weComToken);
        msgobj.put("chatid", chatid);
        msgobj.put("msgtype", "text");
        JSONObject text = new JSONObject();
        text.put("content", content);
        msgobj.put("text", text);
        msgobj.put("safe", 0);
        String response = template.postForObject(url, msgobj, String.class);
        JSONObject result = JSONObject.parseObject(response);
        log.info("发送企业微信群聊消息：\n内容：{}\n结果：{}", msgobj, result);
        return result;
    }

    public void sendFile(String touser, String mediaId) {
        String weComToken = tokenService.getWeComSendFileToken();
        if (StrUtil.isBlank(weComToken)) {
            log.error("无法发送文件，没有企业微信token");
            return;
        }
        String requestUrl = SEND_MSG_URL.replace("ACCESS_TOKEN", weComToken);
        JSONObject obj = new JSONObject();
        obj.put("agentid", 1000024);
        obj.put("touser", touser);
        obj.put("toparty", "file");
        obj.put("totag", "");
        obj.put("msgtype", "file");
        JSONObject file = new JSONObject();
        file.put("media_id", mediaId);
        obj.put("file", file);
        obj.put("safe", '0');
        String outputStr = obj.toString();
        log.info("企业微信发送文件：{}", outputStr);
        WeComUtil.httpsRequest(requestUrl, "POST", outputStr);
    }
}
