package com.dayou.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dayou.dto.history.HisMajorOrder;
import com.dayou.dto.history.HisOrderParam;
import com.dayou.exception.ErrorCode;
import com.dayou.service.IHistoryOrderService;
import com.dayou.utils.HttpKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类说明：
 *
 * @author: wucl
 * @since: 2024/5/8
 * created with IntelliJ IDEA.
 */
@Slf4j
@Service
public class HistoryOrderServiceImpl implements IHistoryOrderService {

    private static String COOKIE ;


    private static final String HISTORY_LOGIN_URL = "http://noa.scdayou.com/login?loginName=admin&password=ABC666000";

    private static final String HISTORY_MAJOR_ORDER_URL = "http://noa.scdayou.com/dyoa/order/pageQuery";

    @Override
    public Page<HisMajorOrder> hisMajorPage(HisOrderParam param) {
        checkCookie();
        pageSet(param);
        Page<HisMajorOrder> page = new Page<>();
        try {
            Map<String, Object> map = removeMapKey(BeanUtil.beanToMap(param));
            String respond = HttpKit.sendPost(HISTORY_MAJOR_ORDER_URL, map,COOKIE);
            JSONObject jsonObject = JSON.parseObject(respond);
            JSONObject data = jsonObject.getJSONObject("data");
            JSONArray dataArray = data.getJSONArray("data");
            if (CollectionUtil.isNotEmpty(dataArray)){
                List<HisMajorOrder> hisMajorOrders = dataArray.toJavaList(HisMajorOrder.class);
                page.setRecords(hisMajorOrders);
                page.setTotal(Long.valueOf(String.valueOf(data.get("total"))));
            }
        } catch (JSONException e) {
            historySystemLogin();
            ErrorCode.throwBusinessException(ErrorCode.CUSTOM_ERROR,"远程连接超时，请刷新页面。");
        } catch (Exception e) {
            log.error("远程调用失败.");
            e.printStackTrace();
        }

        return page;
    }

    @Override
    public String getEverCookie() {
        checkCookie();
        return COOKIE;
    }

    private void checkCookie(){
        if (StrUtil.isBlank(COOKIE)){
            historySystemLogin();
        }
    }
    /**
     * 登录原系统获取COOKIE
     * @return
     */
    private void historySystemLogin(){

        try {
            // 创建HttpClient对象
            HttpClient httpClient = new DefaultHttpClient();

            // 创建HttpGet请求对象
            HttpPost httpPost = new HttpPost(HISTORY_LOGIN_URL);

            // 发送请求并获取响应
            HttpResponse response = httpClient.execute(httpPost);

            // 获取cookie
            String cookies = Arrays.toString(response.getHeaders("Set-Cookie"));
            if (cookies != null) {
                String pattern = "(JSESSIONID)(.*?)( )";
                Pattern r = Pattern.compile(pattern);
                Matcher m = r.matcher(cookies);
                if (m.find()) {
                    COOKIE =  m.group(0).trim().split(";")[0];
                }
            }

            // 关闭连接
            httpClient.getConnectionManager().shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Map<String, Object> removeMapKey(Map param) {
        Set set = param.keySet();

        for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
            Object obj = (Object) iterator.next();
            Object value = (Object) param.get(obj);
            if (value == null || value.equals("") || value.equals("null") || obj.toString().length() == 0) {
                iterator.remove();
            }else {
                if (value instanceof String){
                    try {
                        String xValue = new String (((String) value).getBytes("ISO8859-1"),"UTF-8");
                        param.put(obj,xValue);
                    } catch (UnsupportedEncodingException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

        return param;
    }

    private void pageSet(HisOrderParam param){
        param.setLimit(param.getSize());
        param.setStart((param.getCurrent()-1)*param.getLimit());
    }
}
