package com.jeeplus.assess.invoice.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.jeeplus.assess.invoice.service.dto.FinanceInvoiceDTO;
import com.jeeplus.sys.feign.IRoleApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author hgc
 * @Date 2026/3/12/9:44
 * @ClassName DingTalkUtil
 * @Description
 */
@Component
public class DingTalkUtil {
    private static String appKey;
    private static String appSecret;
    private static String agentId;
    private static String accessTokenUrl;
    private static String templateUrl;


    @Value("${dingTalk.appKey:}")
    public void setAppKey(String appKey) {
        DingTalkUtil.appKey = appKey;
    }

    @Value("${dingTalk.appSecret:}")
    public void setAppSecret(String appSecret) {
        DingTalkUtil.appSecret = appSecret;
    }

    @Value("${dingTalk.agentId:}")
    public void setAgentId(String agentId) {
        DingTalkUtil.agentId = agentId;
    }

    @Value("${dingTalk.accessTokenUrl:}")
    public void setAccessTokenUrl(String accessTokenUrl) {
        DingTalkUtil.accessTokenUrl = accessTokenUrl;
    }

    @Value("${dingTalk.templateUrl:}")
    public void setTemplateUrl(String templateUrl) {
        DingTalkUtil.templateUrl = templateUrl;
    }


    private static String templateText =
            "### 开票审批提醒\n\n" +
                    "**实际开票单位：** %s\n\n" +
                    "**发票金额(元)：** %s\n\n" +
                    "**申请人：** %s\n\n" +
                    "---\n\n" +
                    "[点击进入审批](%s)";

    public static String getToken(){
        // 增加空值校验，避免NPE
        if (appKey == null || appSecret == null || accessTokenUrl == null) {
            System.err.println("钉钉配置未正确注入：appKey=" + appKey + ", appSecret=" + appSecret + ", accessTokenUrl=" + accessTokenUrl);
            return null;
        }

        try {
            DingTalkClient client = new DefaultDingTalkClient(accessTokenUrl);
            OapiGettokenRequest req = new OapiGettokenRequest();
            req.setAppkey(appKey);
            req.setAppsecret(appSecret);
            req.setHttpMethod("GET");
            OapiGettokenResponse rsp = client.execute(req);
            System.out.println("获取到钉钉AccessToken：" + rsp.getAccessToken());
            return rsp.getAccessToken();
        } catch (ApiException e) {  // 捕获具体异常，而非泛化Exception
            System.err.println("获取钉钉AccessToken失败：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("获取钉钉AccessToken出现未知异常：" + e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
    public static ResponseEntity addDingtalkNotice(FinanceInvoiceDTO cwFinanceInvoiceDTO) {
        try {
            RoleDTO roleDTO = SpringUtil.getBean(IRoleApi.class).getRoleDTOByName2("发票管理员");
            List<UserDTO> notifiedPartyUsers =SpringUtil.getBean(IUserApi.class).findListByRoleId(roleDTO.getId());
            UserDTO assigneeDTO = notifiedPartyUsers.get(0);

            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
            OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();

            String token = getToken();
            req.setAgentId(Long.parseLong(agentId));
            //接受审批通知的钉钉id
            req.setUseridList(assigneeDTO.getDdId());
            OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
            msg.setMsgtype("markdown");
            OapiMessageCorpconversationAsyncsendV2Request.Markdown markdown = new OapiMessageCorpconversationAsyncsendV2Request.Markdown();
            markdown.setTitle("开票审批提醒");
            String finalUrl = String.format(templateUrl, assigneeDTO.getDdId(),cwFinanceInvoiceDTO.getId());
            String markdownText = String.format(
                    templateText,
                    cwFinanceInvoiceDTO.getBillingWorkplaceReal(),
                    cwFinanceInvoiceDTO.getAccount(),
                    cwFinanceInvoiceDTO.getBillingPeopleRealName(),
                    finalUrl
            );
            markdown.setText(markdownText);
            msg.setMarkdown(markdown);
            req.setMsg(msg);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, token);
            return ResponseEntity.ok(rsp.getBody());
        }  catch (ApiException e) {
            e.printStackTrace(); // 打印错误日志
            return ResponseEntity.badRequest().body("接口异常，请重试!");
        } catch (Exception e) {
            e.printStackTrace(); // 打印错误日志
            return ResponseEntity.badRequest().body("接口异常，请重试!");
        }
    }
}
