package com.mortals.xhx.module.platform.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mortals.framework.exception.AppException;
import com.mortals.framework.model.Context;
import com.mortals.framework.service.ICacheService;
import com.mortals.framework.service.impl.LocalCacheServiceImpl;
import com.mortals.framework.web.BaseCRUDJsonMappingController;
import com.mortals.xhx.base.system.param.service.ParamService;
import com.mortals.xhx.module.platform.model.PlatformEntity;
import com.mortals.xhx.module.platform.service.PlatformService;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 平台系统
 *
 * @author zxfei
 * @date 2022-04-25
 */
@RestController
@RequestMapping("platform")
public class PlatformController extends BaseCRUDJsonMappingController<PlatformService, PlatformForm, PlatformEntity, Long> {

    @Autowired
    private ParamService paramService;

    private ICacheService cacheService = LocalCacheServiceImpl.getInstance();

    private final String KEY = "base-platform:admin,admin";//基础服务平台获取token

    public PlatformController() {
        super.setFormClass(PlatformForm.class);
        super.setModuleDesc("平台系统");
    }

    @Override
    protected void init(HttpServletRequest request, HttpServletResponse response, PlatformForm form, Map<String, Object> model, Context context) {
        this.addDict(model, "sendMsgType", paramService.getParamBySecondOrganize("Platform", "sendMsgType"));
        this.addDict(model, "sendSwitch", paramService.getParamBySecondOrganize("Platform", "sendSwitch"));
        super.init(request, response, form, model, context);
    }





    @GetMapping("getSite")
    public String getSite(@RequestParam("parentId") String parentId) {
        log.info("【获取站点】【请求体】-->parentId  " + parentId);
        String res = null;
        try {
            String token = cacheService.get(KEY);
            if(token == null){
                token = getToken();
                if(token == null){
                    throw new AppException("未获取到token");
                }
            }
            res = getSiteList(parentId, token);
            if(JSONObject.parseObject(res).get("code").equals(-1)){
                token = getToken();
                res = getSiteList(parentId, token);
            }
        } catch (Exception e) {
            log.error("接收数据失败", e);
            return res;
        }
        log.info("响应【获取站点】【响应体】-->  " + res);
        return res;
    }

    //获取基础服务平台站点信息
    private String getSiteList(String parentId, String token){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet("http://192.168.0.98:11071/zwfw/area/getListByParentId?parentId=" + parentId);
            // 设置请求头信息，鉴权
            httpGet.setHeader("Authorization", token);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            log.error("接收数据失败", e);
            return JSON.toJSONString(result);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        JSONObject object = JSONObject.parseObject(result);
        if(object == null || object.get("code") == null){
            throw new AppException("基础服务平台获取站点信息失败，响应值: " + response);
        }
        return result;
    }

    //获取基础服务平台token
    private String getToken() {
        CloseableHttpResponse httpResponse = null;
        String response = "";
        Object token = null;
        // 创建httpClient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建httpPost远程连接实例
        HttpPost httpPost = new HttpPost("http://192.168.0.98:11071/zwfw/login/login");
        JSONObject request = null;
        try {
            request = new JSONObject();
            request.put("loginName", "admin");
            request.put("password", "admin");
            request.put("securityCode", 8888);
            log.info("登录基础服务平台，参数-->" + request);
            StringEntity entity = new StringEntity(request.toString());
            entity.setContentType("application/json;charset=UTF-8");
            httpPost.setEntity(entity);
            // httpClient对象执行post请求,并返回响应参数对象
            httpResponse = httpClient.execute(httpPost);
            // 从响应对象中获取响应内容
            HttpEntity httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("基础服务平台登录失败,响应体：" + httpResponse);
        } finally {
            // 关闭资源
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        JSONObject object = JSONObject.parseObject(response);
        if(object == null || object.get("code") == null || object.get("code").equals(-1)){
            throw new AppException("基础服务平台登录获取token失败，响应值: " + response);
        }
        if(object.get("code").equals(1)){
            token = JSONObject.parseObject(object.get("data").toString()).get("token");
            cacheService.sadd(KEY,token);
            return token.toString();
        }
        return null;
    }
}