package com.palmnest.service.koala;


import com.alibaba.fastjson.JSON;
import com.palmnest.application.CodeConstants;
import com.palmnest.application.dto.OrgKoalaInfoVo;
import com.palmnest.service.redis.BaseRedisService;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.CookieStore;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.client.HttpClientErrorException;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Koala 对接
 */
public class KoalaService {

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

    public static boolean isDebugKoala = true;//是否调试 koala接口
    
	@Autowired
	private BaseRedisService    baseRedisService;

    @Autowired
    private  Environment environment;
    private  String getKoalaClientUrl() {
        //return environment.getProperty("koala.auth.url");
        return "http://192.168.1.50";
    }
    private  String getKoalaUserName() {
        //return environment.getProperty("koala.user.name");
        return "qingzhangyin@avic-s.com";
    }
    private  String getKoalaUserPwd() {
        //return environment.getProperty("koala.auth.url");
        return "Ac123456";
    }

    public String checkProjectConfig(Integer orgId){


        OrgKoalaInfoVo orgKoalaInfoVo = this.getOrgKoalaInfoVoByOrgId(orgId);

        if(StringUtils.isEmpty(orgKoalaInfoVo.getKoalaAuthUrl())){
             return "当前项目找不到koala连接信息";
        }
        //if(!AppConstants.koala_project_map.containsKey(orgId+"_cookieStore")){
        //    return "当前项目配置信息登录koala失败,请检查";
        //}
        return "";

    }


    public OrgKoalaInfoVo getOrgKoalaInfoVoByOrgId(Integer orgId){

        OrgKoalaInfoVo orgKoalaInfoVo = new OrgKoalaInfoVo();
        String data = baseRedisService.get("User.id:"+ CodeConstants.RSA_REDIS_ORGKOALA_KEY + "_"+orgId);
        log.info("根据orgId:{}找到koala信息:{}",orgId,data);
        if(StringUtils.isNotEmpty(data)){
            orgKoalaInfoVo = JSON.parseObject(data, OrgKoalaInfoVo.class);
        }

        return orgKoalaInfoVo;
    }


    //定时任务
   /* public void  koalaProjectConfig(){


        Map<String, Object> conditions = new HashMap<>();
        conditions.put("passType","4");//koala
        conditions.put("typeOfOperation","2");//住宅

        List<OrganizationEntityVo> listOrgEntirys = organizationEntityMapper.findAll(conditions);
        if(listOrgEntirys.size()>=1){
            for(OrganizationEntityVo vo:listOrgEntirys){


                log.info("项目：{} 考拉配置koalaProjectConfig _url:{},_koalaUserName:{},_koalaUserPwd:{}",vo.getName(),vo.getKoalaAuthUrl(),vo.getKoalaUserName(),vo.getKoalaUserPwd());
                //AppConstants.koala_project_map.put(vo.getId()+"_url",vo.getKoalaAuthUrl());
                //AppConstants.koala_project_map.put(vo.getId()+"_koalaUserName",vo.getKoalaUserName());
                //AppConstants.koala_project_map.put(vo.getId()+"_koalaUserPwd",vo.getKoalaUserPwd());


                RedisString redisString = new RedisString("User.id:"+ CodeConstants.RSA_REDIS_ORGKOALA_KEY + "_"+vo.getId());


                OrgKoalaInfoVo orgKoalaInfoVo =new OrgKoalaInfoVo(vo.getKoalaAuthUrl(),vo.getKoalaUserName(),vo.getKoalaUserPwd());

                redisString.set(JSON.toJSONString(orgKoalaInfoVo));

                CookieStore cookieStore = authLogin(vo.getKoalaAuthUrl(),vo.getKoalaUserName(),vo.getKoalaUserPwd());
                if(null==cookieStore){
                    log.error("koalaProjectConfig===>"+vo.getName()+"项目初始化koala失败");
                }else{

                    AppConstants.koala_project_map.put(vo.getId()+"_url",vo.getKoalaAuthUrl());
                    AppConstants.koala_project_map.put(vo.getId()+"_cookieStore",cookieStore);
                }
            }
        }


    }*/



    /**
     * 登录 获取cookie
     *
     * @return cookie
     */
    public  CookieStore authLogin(String koalaAuthUrl,String koalaUserName,String koalaUserPwd) {
        log.info("init 初始化 登录  Koala 连接:"+koalaAuthUrl+" Koala 账号：" + koalaUserName + "，密码：" + koalaUserPwd);

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost request    = new HttpPost(koalaAuthUrl + "/auth/login");
            request.setHeader("User-Agent", "Koala Admin");
            request.setHeader("Content-Type", "application/json");
            JSONObject json = new JSONObject();
            json.put("username", koalaUserName);
            json.put("password", koalaUserPwd);
            request.setEntity(new StringEntity(json.toString(), "UTF-8"));
            HttpClientContext context      = HttpClientContext.create();
            CloseableHttpResponse response     = httpclient.execute(request, context);
            String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 解析JSON数据
            JSONObject resp   = new JSONObject(responseBody);
            int        result = resp.optInt("code", -1);
            if (result != 0) {
                log.info("Login failed, code:" + result);
            } else {
                log.info("Login Success,id:" + resp.getJSONObject("data").getInt("id"));
                log.info("Login Success,返回内容:" + resp.getJSONObject("data"));
                return context.getCookieStore();
            }
        } catch (Exception e) {
            log.error("Login error, code:" + e.getMessage());
            return null;
        }
        return null;
    }


    /**
     * 登录 获取cookie
     *
     * @return cookie
     */
    public String checkAuthLogin(String koalaAuthUrl,String koalaUserName,String koalaUserPwd) {

        log.info("init 初始化 登录  Koala 连接:"+koalaAuthUrl+" Koala 账号：" + koalaUserName + "，密码：" + koalaUserPwd);

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost request    = new HttpPost(koalaAuthUrl + "/auth/login");
            request.setHeader("User-Agent", "Koala Admin");
            request.setHeader("Content-Type", "application/json");
            JSONObject json = new JSONObject();
            json.put("username", koalaUserName);
            json.put("password", koalaUserPwd);
            request.setEntity(new StringEntity(json.toString(), "UTF-8"));
            HttpClientContext context      = HttpClientContext.create();
            CloseableHttpResponse response     = httpclient.execute(request, context);
            String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 解析JSON数据
            JSONObject resp   = new JSONObject(responseBody);
            int        result = resp.optInt("code", -1);
            if (result != 0) {
                return resp.getString("desc");
            }
        } catch (Exception e) {
            log.error("Login error, code:" + e.getMessage());
            return e.getMessage();
        }
        return "";
    }



    /**
     * 上传识别底库
     *
     * @return
     * @throws Exception
     */
    public  JSONObject photo(Map<String, Object> paramMap) {

        log.info("调起上传识别照片（/subject/photo）接口  请求方式post 上传识别照片 ...");


        Integer  orgId = (Integer) paramMap.get("orgId");
        //String koalaClientUrl =  (String)AppConstants.koala_project_map.get(orgId+"_url");
        //String koalaUserName =  (String)AppConstants.koala_project_map.get(orgId+"_koalaUserName");
        //String koalaUserPwd =  (String)AppConstants.koala_project_map.get(orgId+"_koalaUserPwd");
        //CookieStore cookieStore =  (CookieStore)AppConstants.koala_project_map.get(orgId+"_cookieStore");

        OrgKoalaInfoVo orgKoalaInfoVo = this.getOrgKoalaInfoVoByOrgId(orgId);
        //因一个小时 token 会失效 不能用定时任务 要校验token 是否失效 不如每次登录
        CookieStore cookieStore = this.authLogin(orgKoalaInfoVo.getKoalaAuthUrl(),orgKoalaInfoVo.getKoalaUserName(),orgKoalaInfoVo.getKoalaUserPwd());

        //检查token 是否失败

        JSONObject returnObj = new JSONObject();

        try {
            // 自定义HttpClient 设置CookieStore
            CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            HttpPost            request    = new HttpPost(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject/photo");
            // 设置底库照片 并关联到用户
            MultipartEntity reqEntity = new MultipartEntity();
            String          photo     = paramMap.get("photo") + "";
            reqEntity.addPart("photo", new FileBody(new File(photo)));
            request.setEntity(reqEntity);
            CloseableHttpResponse response     = httpclient.execute(request);
            String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 解析JSON数据
            returnObj   = new JSONObject(responseBody);
            int        result = returnObj.optInt("code", -1);
            if (result != 0) {
                log.info("code:" + result + ",desc:" + returnObj.getString("desc"));
            } else {
                JSONObject data = returnObj.getJSONObject("data");
                log.info("Login Success,返回内容:" + data);
                //return data;
            }
        } catch (HttpClientErrorException httpClientErrorException) {
            log.error("httpClientErrorException 异常，错误信息：" + httpClientErrorException.getMessage());
        } catch (Exception e) {
            log.error("Exception 异常，错误信息：" + e.getMessage());
        }
        return returnObj;
    }



    /**
     * 上传用户信息接口
     *
     * @param paramMap [subjectType(用户类型0为员工1普通访客2为VIP访客),photo_ids 图片集合ID,
     *                 obj(subjectType为0是Appuser员工对象,其他则为VisitorInfo访客对象)]参数
     * @return
     * @throws Exception
     */
    public  JSONObject subject(Map<String, Object> paramMap) throws Exception {
        log.info("调起上传用户信息接口  请求方式post 创建用户 ...");


        Integer  orgId = (Integer) paramMap.get("orgId");
        //String koalaClientUrl =  (String)AppConstants.koala_project_map.get(orgId+"_url");
        //String koalaUserName =  (String)AppConstants.koala_project_map.get(orgId+"_koalaUserName");
        //String koalaUserPwd =  (String)AppConstants.koala_project_map.get(orgId+"_koalaUserPwd");
        //CookieStore cookieStore =  (CookieStore)AppConstants.koala_project_map.get(orgId+"_cookieStore");

        OrgKoalaInfoVo orgKoalaInfoVo = this.getOrgKoalaInfoVoByOrgId(orgId);

        //因一个小时 token 会失效 不能用定时任务 要校验token 是否失效 不如每次登录
        CookieStore cookieStore = this.authLogin(orgKoalaInfoVo.getKoalaAuthUrl(),orgKoalaInfoVo.getKoalaUserName(),orgKoalaInfoVo.getKoalaUserPwd());


        JSONObject returnObj = new JSONObject();

        try {
            CloseableHttpClient httpclient  = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            Integer             subject_type = (Integer) paramMap.get("subject_type");//subjectType为0是员工对象 其他则为访客
            List<Integer> photo_ids = (List<Integer>) paramMap.get("photo_ids");
            HttpPost request = new HttpPost(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject");
            request.setHeader("Content-Type", "application/json");
            JSONObject json = new JSONObject();
            json.put("subject_type", subject_type);// 如果subject_type不等于0，必须要指定start_time，end_time

            if(null!=photo_ids && photo_ids.size()>=1){
                json.put("photo_ids", photo_ids);//识别头像列表
            }
            if(paramMap.containsKey("name")){
                json.put("name", paramMap.get("name"));
            }
            if(paramMap.containsKey("extra_id")){
                json.put("extra_id", paramMap.get("extra_id"));//唯一userId
            }


            request.setEntity(new StringEntity(json.toString(), "UTF-8"));
            CloseableHttpResponse response     = httpclient.execute(request);
            String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 解析JSON数据
            JSONObject resp   = new JSONObject(responseBody);
            int        result = resp.optInt("code", -1);
            if (result != 0) {
                log.error("code:" + result + ",desc:" + resp.getString("desc"));
            } else {
                log.info("Login Success,返回内容:" + resp.getJSONObject("data"));
                //return resp.getJSONObject("data").getInt("id");
            }
            return resp;
        } catch (Exception e) {
            log.error("调起上传用户信息接口 错误：" + e.getMessage());
            returnObj.put("code",500);
            returnObj.put("desc",e.getMessage());
        }
        return returnObj;
    }




    /**
     * 修改用户信息接口
     *
     * @param ++图片ID集合),appUser(员工对象) 参数
     * @return
     * @throws Exception
     */
    public JSONObject updatesubject(Map<String, Object> paramMap) throws Exception {
        log.info("调起更新用户信息接口  请求方式post 创建用户 ...");



        Integer  orgId = (Integer) paramMap.get("orgId");
        //String koalaClientUrl =  (String)AppConstants.koala_project_map.get(orgId+"_url");
        //String koalaUserName =  (String)AppConstants.koala_project_map.get(orgId+"_koalaUserName");
        //String koalaUserPwd =  (String)AppConstants.koala_project_map.get(orgId+"_koalaUserPwd");
        //CookieStore cookieStore =  (CookieStore)AppConstants.koala_project_map.get(orgId+"_cookieStore");

        OrgKoalaInfoVo orgKoalaInfoVo = this.getOrgKoalaInfoVoByOrgId(orgId);

        //因一个小时 token 会失效 不能用定时任务 要校验token 是否失效 不如每次登录
        CookieStore cookieStore = this.authLogin(orgKoalaInfoVo.getKoalaAuthUrl(),orgKoalaInfoVo.getKoalaUserName(),orgKoalaInfoVo.getKoalaUserPwd());


        JSONObject returnObj = new JSONObject();
        try {

            Integer  subject_type = (Integer) paramMap.get("subject_type");
            Integer  subject_id = (Integer) paramMap.get("subject_id");//subjectType为0是员工对象 其他则为访客
            List<Integer> photo_ids = (List<Integer>) paramMap.get("photo_ids");

            CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
            HttpPut request    = new HttpPut(orgKoalaInfoVo.getKoalaAuthUrl() + "/subject/" + subject_id);
            request.setHeader("Content-Type", "application/json");
            JSONObject json = new JSONObject();

            json.put("subject_type", subject_type);
            if(null!=photo_ids && photo_ids.size()>=0){//用就更新、没有就删除(解除用户和图片关系
                json.put("photo_ids", photo_ids);//识别头像列表
            }

            request.setEntity(new StringEntity(json.toString(), "UTF-8"));
            log.info("updatesubject,请求参数:" + json.toString());
            CloseableHttpResponse response     = httpclient.execute(request);
            String                responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");
            // 解析JSON数据
            returnObj   = new JSONObject(responseBody);
            int        result = returnObj.optInt("code", -1);
            if (result != 0) {
                log.error("code:" + result + ",desc:" + returnObj.getString("desc"));
            } else {
                log.info("Login Success,返回内容:" + returnObj.getJSONObject("data"));
            }
        } catch (Exception e) {
            log.error("调起上传用户信息接口 错误：" + e.getMessage());
            returnObj.put("code",500);
            returnObj.put("desc",e.getMessage());
        }
        return returnObj;
    }



    public  void main(String[] args) throws Exception {



       /* CookieStore        cookieStore = authLogin();

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("photo","C:\\Users\\Administrator\\Desktop\\temp1111\\Python\\图片\\999.jpg");
        JSONObject returnObj = photo(paramMap,cookieStore);
        int        result = returnObj.optInt("code", -1);
        if (result != 0) {
            log.error("code:" + result + ",desc:" + returnObj.getString("desc"));
        } else {
            JSONObject jsonData=returnObj.getJSONObject("data");
            log.error("jsonData:" + jsonData.toString());
        }*/



        //paramMap.put("subject_type",0);
        //paramMap.put("extra_id","0426005");
        //paramMap.put("name","青005");
        //subject(paramMap,cookieStore);


        //paramMap.put("subject_id",13);
        //paramMap.put("subject_type",0);
        //List<Integer> photo_ids = new ArrayList<>();
        //photo_ids.add(7);
        //paramMap.put("photo_ids",photo_ids);

        //updatesubject(paramMap,cookieStore);

        //log.info("cookieStore===>"+ cookieStore.toString());

    }



}
