package com.fs.kdzl.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.http.HttpUtils;
import com.fs.kdzl.dto.Custm;
import com.fs.kdzl.dto.CustomerResponse;
import com.fs.kdzl.dto.KdzlCustomerDTO;
import com.fs.kdzl.service.KdzlService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class KdzlServiceImpl implements KdzlService {

    private static final Logger log = LoggerFactory.getLogger(KdzlServiceImpl.class);

    private static final String APPID = "71605";
    private static final String DID = "3697222";
    private static final String SECRET = "95c0bb697d8f444a";
    private static final String URL = "https://api.kdzl.cn/cgi-bin";
    private static final String ACCESS_TOKEN_CACHE_KEY = "kdzl:access_token";
    private static final int TOKEN_EXPIRE_SECONDS = 7200;
    private static final int CACHE_ADVANCE_EXPIRE_SECONDS = 600;
    private static final String CUSTOMER_NEXT_CACHE_KEY = "kdzl:customer_next";
    private static final int MAX_COUNT = 2000;

    @Autowired
    private RedisCache redisCache;

    @Override
    public String getAccessToken() {
        try {
            String cachedToken = redisCache.getCacheObject(ACCESS_TOKEN_CACHE_KEY);
            if (cachedToken != null && !cachedToken.isEmpty()) {
                log.info("从缓存中获取access_token: {}", cachedToken);
                return cachedToken;
            }
            
            String params = "appid=" + APPID + "&did=" + DID + "&secret=" + SECRET + "&expire=" + TOKEN_EXPIRE_SECONDS;
            String response = HttpUtils.sendGet(URL + "/oauth/access_token", params);
            
            log.info("获取口袋助理access_token响应: {}", response);
            
            if (response.isEmpty()) {
                log.error("获取access_token失败，响应为空");
                return "";
            }
            
            JSONObject jsonObject = JSONObject.parseObject(response);
            Integer result = jsonObject.getInteger("result");
            
            if (result != null && result == 0) {
                String accessToken = jsonObject.getString("access_token");
                log.info("成功获取access_token: {}", accessToken);
                
//                int cacheExpireSeconds = TOKEN_EXPIRE_SECONDS - CACHE_ADVANCE_EXPIRE_SECONDS;
//                redisCache.setCacheObject(ACCESS_TOKEN_CACHE_KEY, accessToken, cacheExpireSeconds, TimeUnit.SECONDS);
//                log.info("access_token已存入缓存，缓存时间: {}秒", cacheExpireSeconds);
                
                return accessToken;
            } else {
                String errMsg = jsonObject.getString("errmsg");
                log.error("获取access_token失败，错误码: {}, 错误信息: {}", result, errMsg);
                return "";
            }
        } catch (Exception e) {
            log.error("获取access_token异常", e);
            return "";
        }
    }

    @Override
    public List<Custm> exportCustomers() {
        List<Custm> customerList = new ArrayList<>();
        
        try {
            String accessToken = getAccessToken();
            if (accessToken.isEmpty()) {
                log.error("获取access_token失败，无法导出客户");
                return customerList;
            }
            
            Integer cachedNext = redisCache.getCacheObject(CUSTOMER_NEXT_CACHE_KEY);
            int start = (cachedNext != null) ? cachedNext : 0;
            int count = MAX_COUNT;
            
            String params = "access_token=" + accessToken + "&start=" + start + "&count=" + count;
            String response = HttpUtils.sendGet(URL + "/customer/export", params);
            
            //log.info("导出客户响应: {}", response);
            
            if (response.isEmpty()) {
                log.error("导出客户失败，响应为空");
                return customerList;
            }
            
            JSONObject jsonObject = JSONObject.parseObject(response);
            CustomerResponse customerResponse = jsonObject.toJavaObject(CustomerResponse.class);
            Integer result = customerResponse.getResult();

            if (result != null && result == 0) {
                if (!CollectionUtils.isEmpty(customerResponse.getCustms())) {
                    customerList = customerResponse.getCustms();
                    log.info("成功导出客户数量: {}, 当前start: {}", customerList.size(), start);
                    
                    if (customerList.size() == MAX_COUNT) {
                        Integer next = start + count;
                        redisCache.setCacheObject(CUSTOMER_NEXT_CACHE_KEY, next, 7, TimeUnit.DAYS);
                        log.info("数据量达到{}，更新next缓存为: {}", MAX_COUNT, next);
                    } else {
                        redisCache.deleteObject(CUSTOMER_NEXT_CACHE_KEY);
                        log.info("数据量不足{}，清除缓存，所有客户数据已获取完毕", MAX_COUNT);
                    }
                } else {
                    log.info("未查询到客户数据");
                    redisCache.deleteObject(CUSTOMER_NEXT_CACHE_KEY);
                }
            } else {
                String errMsg = jsonObject.getString("errmsg");
                log.error("导出客户失败，错误码: {}, 错误信息: {}", result, errMsg);
            }
        } catch (Exception e) {
            log.error("导出客户异常", e);
        }
        //log.info("导出客户完成，共导出客户数量: {}, 数据: {}", customerList.size(), customerList);
        return customerList;
    }

    @Override
    public List<Custm> exportCustomersByPost(Integer start, Long psid) {
        List<Custm> customerList = new ArrayList<>();
        
        try {
            String accessToken = getAccessToken();
            if (accessToken.isEmpty()) {
                log.error("获取access_token失败，无法导出会员");
                return customerList;
            }
            
            if (start == null) {
                start = 0;
            }
            
            String url = URL + "/open/api/customer/exportCustomer?access_token=" + accessToken;
            
            JSONObject requestBody = new JSONObject();
            requestBody.put("start", start);
            if (psid != null) {
                requestBody.put("psid", psid);
            }
            
            log.info("导出会员请求URL: {}, 请求体: {}", url, requestBody.toJSONString());
            
            String response = HttpUtils.sendPost(url, requestBody.toJSONString());
            
            log.info("导出会员响应: {}", response);
            
            if (response.isEmpty()) {
                log.error("导出会员失败，响应为空");
                return customerList;
            }
            
            JSONObject jsonObject = JSONObject.parseObject(response);
            CustomerResponse customerResponse = jsonObject.toJavaObject(CustomerResponse.class);
            Integer result = customerResponse.getResult();

            if (result != null && result == 0) {
                if (!CollectionUtils.isEmpty(customerResponse.getCustms())) {
                    customerList = customerResponse.getCustms();
                    log.info("成功导出会员数量: {}, 当前start: {}", customerList.size(), start);
                    
                    if (!customerList.isEmpty()) {
                        Custm lastCustomer = customerList.get(customerList.size() - 1);
                        if (lastCustomer.getCustmid() != null) {
                            redisCache.setCacheObject(CUSTOMER_NEXT_CACHE_KEY, lastCustomer.getCustmid().intValue(), 7, TimeUnit.DAYS);
                            log.info("下次start值已存入/更新缓存: {}", lastCustomer.getCustmid());
                        }
                    }
                } else {
                    log.info("未查询到会员数据");
                }
            } else {
                String errMsg = jsonObject.getString("errmsg");
                log.error("导出会员失败，错误码: {}, 错误信息: {}", result, errMsg);
            }
        } catch (Exception e) {
            log.error("导出会员异常", e);
        }
        
        //log.info("导出会员完成，共导出会员数量: {}, 数据: {}", customerList.size(), customerList);
        log.info("导出会员完成，共导出会员数量: {}", customerList.size());
        return customerList;
    }
}
