package com.trs.digital.module.manager.controller.admin.search.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.trs.digital.framework.common.pojo.PageResult;
import com.trs.digital.module.manager.configure.HybaseFactory;
import com.trs.hybase.client.*;
import com.trs.hybase.client.params.OperationParams;
import com.trs.hybase.client.params.SearchParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;


@Slf4j
@Component
public class HyBaseService {

    public PageResult<Map<String, Object>> select(String tableName, String where, Long start, Long num, SearchParams searchParams) {
        PageResult<Map<String, Object>> pageResult = new PageResult<>();
        TRSConnection connection = HybaseFactory.getClient();
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            TRSResultSet rs = connection.executeSelect(tableName, where, start, num, searchParams);
            pageResult.setTotal(rs.getNumFound());
            for (int i = 0; i < rs.size(); i++) {
                rs.moveNext();
                TRSRecord trsRecord = rs.get();
                Map<String, Object> map = new HashMap<>();
                for (String column : trsRecord.getColumnNames()) {
                    if("doc_content".equals(column)||"doc_content_translate".equals(column)){
                        //System.out.println("doc_content"+ trsRecord.getString(column));
                        if(null!=trsRecord.getString(column)){
                            map.put(column, trsRecord.getString(column).replaceAll("&lt;", "<")
                                    .replaceAll("&gt;", ">")
                                    .replaceAll("&amp;", "&")
                                    .replaceAll("&quot;", "\"")
                                    .replaceAll("&apos;", "'"));
                        }
                    }else if("doc_abstract".equals(column)){
                        //System.out.println("doc_content"+ trsRecord.getString(column));
                        if(null!=trsRecord.getString(column)){
                            map.put(column, trsRecord.getString(column).replaceAll("&lt;/br&gt;", " "));
                        }
                    }else {
                        map.put(column, trsRecord.getString(column));
                    }

                }
                map.put("uid", trsRecord.getUid());
                map.put("isCollectClick", false);
                map.put("isVisitClick", false);
                list.add(map);
            }
            pageResult.setList(list);
            return pageResult;
        } catch (Exception e) {
            log.warn("海贝查询异常:{}", e.getMessage());
            //e.printStackTrace();
        } finally {
            HybaseFactory.clean();
        }
        return pageResult;
    }

    public List selectlist(String tableName, String where, Long start, Long num, SearchParams searchParams) {
        TRSConnection connection = HybaseFactory.getClient();
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            TRSResultSet rs = connection.executeSelect(tableName, where, start, num, searchParams);
            for (int i = 0; i < rs.size(); i++) {
                rs.moveNext();
                TRSRecord trsRecord = rs.get();
                Map<String, Object> map = new HashMap<>();
                for (String column : trsRecord.getColumnNames()) {
                    map.put(column, trsRecord.getString(column));
                }
                map.put("uid", trsRecord.getUid());
                list.add(map);
            }
            return list;
        } catch (Exception e) {
            log.warn("海贝查询异常:{}", e.getMessage());
        } finally {
            HybaseFactory.clean();
        }
        return new ArrayList<>();
    }

    public JSONObject categoryQuery(String tableName, String where, String defaultColumn,String categoryColumn,Integer num, SearchParams searchParams) {
        PageResult<Map<String, Object>> pageResult = new PageResult<>();
        TRSConnection connection = HybaseFactory.getClient();
        JSONObject finalJson = new JSONObject();
        JSONArray jsonArray1 = new JSONArray();
        JSONArray jsonArray2 = new JSONArray();
        JSONArray jsonArray3 = new JSONArray();
        try {

            TRSResultSet result = connection.categoryQuery(tableName, where, defaultColumn, categoryColumn,num,searchParams);

//            System.out.println("result numFound:" + result.getNumFound());
//            System.out.println("total categories:" + result.getCategoryCount());
            Map<String, Long> people_lable = result.getCategoryMap("people_lable");
            Map<String, Long> org_lable = result.getCategoryMap("org_lable");
            Map<String, Long> area_lable = result.getCategoryMap("area_lable");
            Iterator<Map.Entry<String, Long>> iter1 = people_lable.entrySet().iterator();
            while (iter1.hasNext()) {
                Map.Entry<String, Long> entry = iter1.next();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("label",entry.getKey() );
                jsonObject.put("amount",entry.getValue() );
                jsonArray1.add(jsonObject);
            }
            Iterator<Map.Entry<String, Long>> iter2 = org_lable.entrySet().iterator();
            while (iter2.hasNext()) {
                Map.Entry<String, Long> entry = iter2.next();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("label",entry.getKey() );
                jsonObject.put("amount",entry.getValue() );
                jsonArray2.add(jsonObject);
            }
            Iterator<Map.Entry<String, Long>> iter3 = area_lable.entrySet().iterator();
            while (iter3.hasNext()) {
                Map.Entry<String, Long> entry = iter3.next();
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("label",entry.getKey() );
                jsonObject.put("amount",entry.getValue() );
                jsonArray3.add(jsonObject);
            }
            finalJson.put("people_lable",jsonArray1);
            finalJson.put("org_lable",jsonArray2);
            finalJson.put("area_lable",jsonArray3);
            return finalJson;
        } catch (Exception e) {
            log.warn("海贝查询异常:{}", e.getMessage());
        } finally {
            HybaseFactory.clean();
        }
        return new JSONObject();
    }

    public String selectByDataid(String tableName, String where, Long start, Long num, SearchParams searchParams) {
        TRSConnection connection = HybaseFactory.getClient();
        String uid = "";
        try {
            TRSResultSet rs = connection.executeSelect(tableName, where, start, num, searchParams);
            rs.moveNext();
            TRSRecord trsRecord = rs.get();
            return trsRecord.getUid();
        } catch (Exception e) {
            log.warn("海贝查询异常:{}", e.getMessage());
        } finally {
            HybaseFactory.clean();
        }
        return "";
    }

    public Long selectVisitByDataid(String tableName, String where, Long start, Long num, SearchParams searchParams) {
        TRSConnection connection = HybaseFactory.getClient();
        String uid = "";
        try {
            TRSResultSet rs = connection.executeSelect(tableName, where, start, num, searchParams);
            rs.moveNext();
            TRSRecord trsRecord = rs.get();
            return trsRecord.getLong("doc_visit");
        } catch (Exception e) {
            log.warn("海贝查询异常:{}", e.getMessage());
        } finally {
            HybaseFactory.clean();
        }
        return -1L;
    }

    public Map<String, Object> selectColsByDataid(String tableName, String where, Long start, Long num, SearchParams searchParams) {
        TRSConnection connection = HybaseFactory.getClient();
        Map<String, Object> map = new HashMap<>();
        try {
            TRSResultSet rs = connection.executeSelect(tableName, where, start, num, searchParams);
            rs.moveNext();
            TRSRecord trsRecord = rs.get();
            for (String column : trsRecord.getColumnNames()) {
                map.put(column, trsRecord.getString(column));
            }
            map.put("uid", trsRecord.getUid());
            return map;
        } catch (Exception e) {
            log.warn("海贝查询异常:{}", e.getMessage());
        } finally {
            HybaseFactory.clean();
        }
        return new HashMap<>();
    }

    public void update(String tableName, Map<String, Object> params) {
        TRSInputRecord inputRecord = new TRSInputRecord();
        params.forEach((k, v) -> {
            try {
                inputRecord.addColumn(k, v);
            } catch (TRSException e) {
                log.info(String.format("update[%s:%s]:", k, v) + e.getMessage());
            }
        });
        this.update(tableName, inputRecord);
    }

    public void update(String tableName, TRSInputRecord inputRecord) {
        List<TRSInputRecord> records = new ArrayList<>(1);
        records.add(inputRecord);
        this.updateBatch(tableName, records);
    }

    public void updateBatch(String tableName, List<TRSInputRecord> trsInputRecords) {
        TRSConnection connection = HybaseFactory.getClient();
        OperationParams newParams = new OperationParams();
        TRSReport report = new TRSReport();
        try {
            newParams.setProperty("unique.column.search", "true");
            newParams.setProperty("unique.column", "id");
            connection.executeUpdate(tableName, trsInputRecords, newParams, report);
            log.info("HyBase update success num:" + report.getUpdatedNum());
            log.error("HyBase update fail :" + report.getErrorNo());
            log.error("HyBase update fail info:" + report.getErrorMessage());
        } catch (TRSException e) {
            throw new RuntimeException(e);
        } finally {
            HybaseFactory.clean();
        }
    }

    public Integer updateHybaseById(String tableName, String uid, Map<String, Object> map) {
        TRSConnection connection = HybaseFactory.getClient();
        try {
            TRSInputRecord updated = new TRSInputRecord();
            updated.setUid(uid);
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                updated.addColumn(entry.getKey(), entry.getValue());
            }

            ArrayList<TRSInputRecord> updateList = new ArrayList<TRSInputRecord>(1);
            updateList.add(updated);
            OperationParams uParams = new OperationParams();
            uParams.setProperty("update.mode.replace", "false");
            connection.executeUpdate(tableName, updateList,uParams,new TRSReport());
        } catch (TRSException e) {
            e.printStackTrace();
        } finally {
            HybaseFactory.clean();
        }
        return 1;
    }

    public void insertHybase(String tableName, Map<String, Object> map) {
        TRSConnection connection = HybaseFactory.getClient();
        try {
            List<TRSInputRecord> recordList = new ArrayList<TRSInputRecord>();
            TRSInputRecord updated = new TRSInputRecord();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                updated.addColumn(entry.getKey(), entry.getValue());
            }
            recordList.add(updated);
            OperationParams params = new OperationParams();
            params.setBoolProperty("insert.skip.error", true);
            TRSReport report = new TRSReport();
            connection.executeInsert(tableName, recordList, params, report);
        } catch (TRSException e) {
            System.out.println(e.getErrorCode() + ":" + e.getErrorString());
        } finally {
            connection.close();
        }
    }

    public void deleteHybaseById(String tableName, String uid) {
        TRSConnection connection = HybaseFactory.getClient();
        try {
            List<String> toBeDelete = new ArrayList<String>();
            toBeDelete.add(uid);
            connection.executeDelete(tableName, toBeDelete);
        } catch (TRSException e) {
            e.printStackTrace();
        } finally {
            HybaseFactory.clean();
        }
    }

    public JSONArray categoryQuery2(String tableName, String where, String defaultColumn,String categoryColumn,Integer num, SearchParams searchParams) {
        TRSConnection connection = HybaseFactory.getClient();
        JSONArray list = new JSONArray();
        try {

            TRSResultSet result = connection.categoryQuery(tableName, where, defaultColumn, categoryColumn,num,searchParams);
            Map<String, Long> userid = result.getCategoryMap("userid");
            Iterator<Map.Entry<String, Long>> iter1 = userid.entrySet().iterator();
            while (iter1.hasNext()) {
                Map.Entry<String, Long> entry = iter1.next();
                list.add(entry.getKey());
            }
            return list;
        } catch (Exception e) {
            log.warn("海贝查询异常:{}", e.getMessage());
        } finally {
            HybaseFactory.clean();
        }
        return new JSONArray();
    }


}
