package org.jeecg.modules.cas.service;

import com.alibaba.fastjson.JSON;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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.util.EntityUtils;
import org.jasig.cas.client.util.URIBuilder;
import org.jasig.cas.client.validation.Assertion;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.config.util.HttpUtil;
import org.jeecg.modules.cas.entity.WellboreUser;
import org.jeecg.modules.dataVue.service.ILjrbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.List;
import java.util.Map;

@Service
public class WellboreAuthQuery implements IWellboreAuthQuery {
    @Autowired
    ILjrbService iLjrbService;
    @Value("${wellbore.auth-url-base}")
    private String wellboreAuthUrlBase;

    @Autowired
    private Environment env;

    @Override
    @Cacheable(cacheNames = "wellboreCas_Account")
    public WellboreUser queryCasLogginedUserInformation(String casAccount) throws IOException {
        WellboreUser result = new WellboreUser();
        URI uri = null;
        uri = new URIBuilder(wellboreAuthUrlBase + "getEntUserByLoginName")
                .build();
        HttpPost httpPost = new HttpPost(uri);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            String param = String.format("{\"loginName\":\"%s\"}", casAccount);
            StringEntity se = new StringEntity(param, "UTF-8");
            se.setContentEncoding("UTF-8");
            se.setContentType("application/json");
            httpPost.setEntity(se);
            HttpResponse response;
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String body = EntityUtils.toString(entity, "UTF-8");
                result = JSON.parseObject(body, WellboreUser.class);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return result;
    }

    @Override
    @Cacheable(cacheNames = "wellboreCas_Ejdw")
    public List<Map<String, Object>> queryEjdwList() {
//        String sql = "SELECT groupid, g_cname FROM V_SYS_gROUP \n" +
//                "WHERE G_PARENTID='101'\n" +
//                "ORDER BY G_SHOWORDER";
//        List<Map<String, Object>> result = iLjrbService.querySql(sql, null);
        List<Map<String, Object>> result = iLjrbService.getEjdwList();
        return result;
    }

    @Override
    public String getEjdwInFullName(String casAccount) {
        WellboreUser user = null;
        try {
            user = queryCasLogginedUserInformation(casAccount);
            List<Map<String, Object>> ejdwList = queryEjdwList();
            for (Map<String, Object> dw : ejdwList) {
                String orgnaFullName = user.getENT_USER().getOrgMap().getOrgnaFullName();
                String g_cname = dw.get("G_CNAME").toString();
                if (orgnaFullName.contains(g_cname)) {
                    // TODO: for test need remove
                    if(casAccount.equals("liuruibing.ossl")){
                        return  null; // "黄河钻井总公司";
                    }
                    // end ===============================
                    return g_cname;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean isEjdwUser(String casAccout) {
        String ejdwName = getEjdwInFullName(casAccout);
        return ejdwName != null;
    }

    @Override
    public Boolean canAccessAllWells(String casAccount) {
        return !isEjdwUser(casAccount);
    }

    @Override
    public String getSessionCasName() {
        String active = env.getProperty("spring.profiles.active");
        if (!"prod".equals(active)){
            return "chenggq58";
        }
        HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
        return ((Assertion) request.getSession().getAttribute(CommonConstant.CAS_USER_SESSION_KEY)).getPrincipal().getName();
    }
}
