package org.xyzh.common.wechat.kefu.account;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.xyzh.common.wechat.kefu.core.KefuAccessTokenManager;
import org.xyzh.common.wechat.pojo.kefu.KefuAccount;
import org.xyzh.common.wechat.pojo.kefu.WeChatResponse;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

/**
 * @description    客服账号管理服务
 *                 - 添加客服账号
 *                 - 删除客服账号
 *                 - 修改客服账号
 *                 - 获取客服账号列表
 *                 - 获取客服账号链接
 * @filename    KefuAccountService.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-12-19
 */
@Service
public class KefuAccountService {

    private static final Logger logger = LoggerFactory.getLogger(KefuAccountService.class);
    private static final String BASE_URL = "https://qyapi.weixin.qq.com/cgi-bin";
    
    private final RestTemplate restTemplate = new RestTemplate();
    private final KefuAccessTokenManager tokenManager;
    private KefuAccountHandler handler;

    public KefuAccountService(KefuAccessTokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    public void setHandler(KefuAccountHandler handler) {
        this.handler = handler;
    }

    /**
     * 添加客服账号
     */
    public String addAccount(String name, String mediaId) {
        String accessToken = tokenManager.getAccessToken();
        String url = BASE_URL + "/kf/account/add?access_token=" + accessToken;

        JSONObject body = new JSONObject();
        body.put("name", name);
        if (mediaId != null) {
            body.put("media_id", mediaId);
        }

        String response = postJson(url, body.toJSONString());
        JSONObject result = JSON.parseObject(response);
        
        if (result.getIntValue("errcode") == 0) {
            String openKfid = result.getString("open_kfid");
            logger.info("添加客服账号成功: name={}, openKfid={}", name, openKfid);
            if (handler != null) {
                handler.onAccountAdded(openKfid, name);
            }
            return openKfid;
        }
        
        logger.error("添加客服账号失败: {}", response);
        return null;
    }

    /**
     * 删除客服账号
     */
    public boolean deleteAccount(String openKfid) {
        String accessToken = tokenManager.getAccessToken();
        String url = BASE_URL + "/kf/account/del?access_token=" + accessToken;

        JSONObject body = new JSONObject();
        body.put("open_kfid", openKfid);

        String response = postJson(url, body.toJSONString());
        JSONObject result = JSON.parseObject(response);
        
        boolean success = result.getIntValue("errcode") == 0;
        if (success) {
            logger.info("删除客服账号成功: openKfid={}", openKfid);
            if (handler != null) {
                handler.onAccountDeleted(openKfid);
            }
        } else {
            logger.error("删除客服账号失败: {}", response);
        }
        return success;
    }

    /**
     * 修改客服账号
     */
    public boolean updateAccount(String openKfid, String name, String mediaId) {
        String accessToken = tokenManager.getAccessToken();
        String url = BASE_URL + "/kf/account/update?access_token=" + accessToken;

        JSONObject body = new JSONObject();
        body.put("open_kfid", openKfid);
        if (name != null) {
            body.put("name", name);
        }
        if (mediaId != null) {
            body.put("media_id", mediaId);
        }

        String response = postJson(url, body.toJSONString());
        JSONObject result = JSON.parseObject(response);
        
        boolean success = result.getIntValue("errcode") == 0;
        if (success) {
            logger.info("修改客服账号成功: openKfid={}", openKfid);
            if (handler != null) {
                handler.onAccountUpdated(openKfid, name);
            }
        } else {
            logger.error("修改客服账号失败: {}", response);
        }
        return success;
    }

    /**
     * 获取客服账号列表
     */
    public List<KefuAccount> getAccountList() {
        String accessToken = tokenManager.getAccessToken();
        String url = BASE_URL + "/kf/account/list?access_token=" + accessToken;

        String response = restTemplate.getForObject(url, String.class);
        JSONObject result = JSON.parseObject(response);
        
        if (result.getIntValue("errcode") == 0) {
            return result.getList("account_list", KefuAccount.class);
        }
        
        logger.error("获取客服账号列表失败: {}", response);
        return null;
    }

    /**
     * 获取客服账号链接
     */
    public String getAccountLink(String openKfid, String scene) {
        String accessToken = tokenManager.getAccessToken();
        String url = BASE_URL + "/kf/add_contact_way?access_token=" + accessToken;

        JSONObject body = new JSONObject();
        body.put("open_kfid", openKfid);
        if (scene != null) {
            body.put("scene", scene);
        }

        String response = postJson(url, body.toJSONString());
        JSONObject result = JSON.parseObject(response);
        
        if (result.getIntValue("errcode") == 0) {
            return result.getString("url");
        }
        
        logger.error("获取客服账号链接失败: {}", response);
        return null;
    }

    private String postJson(String url, String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(json, headers);
        return restTemplate.postForObject(url, entity, String.class);
    }

}
