package com.engine.custom.yunxuetang;

import com.alibaba.fastjson.JSONObject;

import com.engine.custom.yunxuetang.bean.DeptRequestBody;
import com.engine.custom.yunxuetang.bean.JobRequestBody;
import com.engine.custom.yunxuetang.bean.JobTypeRequestBody;
import com.engine.custom.yunxuetang.bean.ResponseData;
import com.engine.custom.yunxuetang.util.HttpClientUtil;
import com.engine.custom.yunxuetang.util.SyncUtil;
import com.weaver.general.Util;
import okhttp3.*;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.general.GCONST;
import weaver.general.StringUtil;
import weaver.hrm.job.JobActivitiesComInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
       //查询未封存的分部  数量不大暂不分页
    public static final String querySubsql = "select ID,SUBCOMPANYNAME,SHOWORDER,SUBCOMPANYCODE from hrmsubcompany where CANCELED is null or CANCELED != 1";
    //更新分部云学堂id
    public static final String updateSubyxtid = "update hrmsubcompanydefined set yxtid = ? where subcomid = ?";
    //查询部门等级sql
    public static final String queryDeptLevelsql = "select TLEVEL level from HRMDEPARTMENT group by TLEVEL";
    //根据层级获取对应层级的总数
    public static final String queryDeptLevelCountsql = "select count(*) cnt from HRMDEPARTMENT where  TLEVEL = ?";
    //查询某级部门
    public static final String queryDeptsql = "select dept.* from (" +
                                                " select id , DEPARTMENTNAME ,DEPARTMENTCODE ,SUBCOMPANYID1 , SUPDEPID,SHOWORDER, " +
                                                " ROW_NUMBER() OVER (ORDER BY SHOWORDER) AS rn from HRMDEPARTMENT where TLEVEL = ? " +
                                                "  ) dept WHERE dept.rn BETWEEN ? AND  ? ";
    //查询删除的部门
    public static final String queryDelDeptsql =  "select id from HRMDEPARTMENT where CANCELED = 1 order by TLEVEL desc";
    // public static final String queryDelDeptsql =  "select id from HRMDEPARTMENT  order by TLEVEL desc";
    //查询删除的分部
    public static final String queryDelSubsql =  "select id from HRMSUBCOMPANY where CANCELED = 1 order by TLEVEL desc";
    // public static final String queryDelSubsql =  "select id from HRMSUBCOMPANY  order by TLEVEL desc";
    //查询岗位分类
    public static final String queryJobTypesql =  "select * from hrmjobactivities";
    //查询岗位
    public static final String queryJobsql =  "select * from hrmjobtitles";
    public static final char Separator = Util.getSeparator();

    public static void main(String[] args) {
        String rootPath = "D:\\WEAVER2\\ecology\\";
        GCONST.setRootPath(rootPath);
        GCONST.setServerName("ecology");
        // Test test = new Test();
        //同步部门成功,开始调用删除部门接口同步封存部门
        // test.syncDeptList();
        //先删除部门再删除分部
        // test.deldept();
        //同步岗位类型 防止有同名岗位
        // test.syncJobTypeList();
        //同步岗位
        // test.syncJobList();
        JobActivitiesComInfo jobActivitiesComInfo = new JobActivitiesComInfo();
        jobActivitiesComInfo.getJobActivitiesname();
        // boolean next = jobActivitiesComInfo.next();
    }




    private  void syncDeptList() {
        //同步分部作为一级部门
        //获取分部beanList
        SyncUtil syncUtil = new SyncUtil();
        RecordSet recordSet = new RecordSet();
        BatchRecordSet batchRecordSet = new BatchRecordSet();
        List<DeptRequestBody> subcompanyList = getSubcompanyList(recordSet);
        List<String> updatesubcompanyList = new ArrayList<>();
        //推送数据云学堂
        for (DeptRequestBody deptRequestBody : subcompanyList) {
            ResponseData responseData = syncUtil.syncDept(deptRequestBody);
            System.out.println("responseData"+responseData);
            String yxtid = responseData.getData().getString("id");
            updatesubcompanyList.add(yxtid+Separator+deptRequestBody.getThirdId());
            System.out.println("sql==="+yxtid+Separator+deptRequestBody.getThirdId());
        }
        batchRecordSet.executeSqlBatchNew(updateSubyxtid,updatesubcompanyList);
        //同步部门(从一级开始同步,查询一共几级部门,按顺序推送)
        ArrayList<Integer> levelList = new ArrayList<>();
        recordSet.executeQuery(queryDeptLevelsql);
        while (recordSet.next()){
            int level = Util.getIntValue(recordSet.getString("level"),2);
            levelList.add(level);
        }
        Collections.sort(levelList);
        //去重,一般不会有这个问题
        List<Integer> listWithoutDuplicates = new ArrayList<>(new LinkedHashSet<>(levelList));
        //禁止在循环中创建recordSet对象,防止连接溢出
        for (int i = 0; i < listWithoutDuplicates.size(); i++) {
            int total = getTotalRecords(recordSet, listWithoutDuplicates.get(i));
            int pageSize = 200;
            int totalPages = (int) Math.ceil((double) total / pageSize);
            if (i == 0) {
                //level为2的作为2级部门,上级部门字段为分部
                for (int pageIndex = 0; pageIndex < totalPages; pageIndex++) {
                    List<DeptRequestBody> pageData = getDeptList(listWithoutDuplicates.get(i),recordSet,pageIndex, pageSize);
                    for (DeptRequestBody deptRequestBody : pageData) {
                        ResponseData responseData = syncUtil.syncDept(deptRequestBody);
                        System.out.println("deptRequestBody===>"+deptRequestBody);
                        System.out.println("responseData===>"+responseData);
                        responseData.getData().getString("id");

                    }
                }

            } else {
                //level大于2的上级部门为oa原上级部门
                for (int pageIndex = 0; pageIndex < totalPages; pageIndex++) {
                    List<DeptRequestBody> pageData = getDeptList(listWithoutDuplicates.get(i),recordSet,pageIndex, pageSize);
                    for (DeptRequestBody deptRequestBody : pageData) {
                        ResponseData responseData = syncUtil.syncDept(deptRequestBody);
                        System.out.println("deptRequestBody===>"+deptRequestBody);
                        System.out.println("responseData===>"+responseData);
                        responseData.getData().getString("id");

                    }
                }
            }
        }
    }

    private List<DeptRequestBody> getSubcompanyList(RecordSet recordSet){
        recordSet.executeQuery(querySubsql);
        ArrayList<DeptRequestBody> subcompanyList = new ArrayList<>();
        while (recordSet.next()){
            DeptRequestBody deptRequestBody = new DeptRequestBody();
            //三方id
            deptRequestBody.setThirdId(Util.null2String("sub_"+recordSet.getString("ID")));
            //分部名称
            deptRequestBody.setName(Util.null2String(recordSet.getString("SUBCOMPANYNAME")));
            //排序
            deptRequestBody.setOrderIndex(Util.getIntValue(recordSet.getString("SHOWORDER")));
            //编码
            deptRequestBody.setCode(Util.null2String(recordSet.getString("SUBCOMPANYCODE")));
            subcompanyList.add(deptRequestBody);
        }
        return subcompanyList;
    };

    private  List<DeptRequestBody>  getDeptList(Integer level, RecordSet recordSet ,int pageIndex, int pageSize) {
        ArrayList<DeptRequestBody> deptRequestBodyList = new ArrayList<>();
        int start = pageIndex * pageSize + 1;
        int end = start + pageSize - 1;
        recordSet.executeQuery(queryDeptsql,level,start,end);
        while (recordSet.next()){
            DeptRequestBody deptRequestBody = new DeptRequestBody();
            //三方id
            deptRequestBody.setThirdId("dept_"+Util.null2String(recordSet.getString("ID")));
            //分部名称
            deptRequestBody.setName(Util.null2String(recordSet.getString("DEPARTMENTNAME")));
            //排序
            deptRequestBody.setOrderIndex(Util.getIntValue(recordSet.getString("SHOWORDER")));
            //编码
            deptRequestBody.setCode(Util.null2String(recordSet.getString("DEPARTMENTCODE")));
            String supdepid = Util.null2String(recordSet.getString("SUPDEPID"));
            if ("0".equals(supdepid)|| StringUtil.isEmpty(supdepid)){
                deptRequestBody.setParentThirdId("sub_"+Util.null2String(recordSet.getString("SUBCOMPANYID1")));
            }else {
                deptRequestBody.setParentThirdId("dept_"+supdepid);
            }
            deptRequestBodyList.add(deptRequestBody);
        }
        return deptRequestBodyList;
    }



    //获取对应层级总数
    public static int getTotalRecords(RecordSet recordSet , int level)  {
        recordSet.executeQuery(queryDeptLevelCountsql,level);
        recordSet.next();
        return  recordSet.getInt("cnt");
    }
    //删除部门
    public  void deldept()  {
        SyncUtil syncUtil = new SyncUtil();
        RecordSet recordSet = new RecordSet();
        recordSet.executeQuery(queryDelDeptsql);
        while (recordSet.next()){
            syncUtil.syncDelDept("dept_"+recordSet.getString("id"));
        }
        recordSet.executeQuery(queryDelSubsql);
        while (recordSet.next()){
            syncUtil.syncDelDept("sub_"+recordSet.getString("id"));
        }
    }

    private void syncJobList() {
        SyncUtil syncUtil = new SyncUtil();
        ArrayList<JobRequestBody> jobRequestBodyList = getJobRequestBodyList();
        for (JobRequestBody jobRequestBody : jobRequestBodyList) {
            syncUtil.syncJobs(jobRequestBody);
        }

    }


    private void syncJobTypeList() {
        SyncUtil syncUtil = new SyncUtil();
        ArrayList<JobTypeRequestBody> jobTypeRequestBodyList = getJobTypeRequestBodyList();
        for (JobTypeRequestBody jobTypeRequestBody : jobTypeRequestBodyList) {
            syncUtil.syncJobType(jobTypeRequestBody);
        }
    }

//  获取岗位
    private ArrayList<JobRequestBody> getJobRequestBodyList() {
        RecordSet recordSet = new RecordSet();
        ArrayList<JobRequestBody> jobList = new ArrayList<>();
        recordSet.executeQuery(queryJobsql);

        while (recordSet.next()){
            String id = recordSet.getString("id");
            String jobtitlename = recordSet.getString("JOBTITLENAME");
            JobRequestBody jobRequestBody = new JobRequestBody();
            jobRequestBody.setThirdId(id);
            jobRequestBody.setName(jobtitlename);
            jobList.add(jobRequestBody);
        }
        return jobList;
    }
    //  获取岗位分类
    private ArrayList<JobTypeRequestBody> getJobTypeRequestBodyList() {
        RecordSet recordSet = new RecordSet();
        ArrayList<JobTypeRequestBody> jobTypeList = new ArrayList<>();
        recordSet.executeQuery(queryJobTypesql);
        while (recordSet.next()){
            String id = recordSet.getString("id");
            String jobtitlename = recordSet.getString("JOBACTIVITYNAME");
            JobTypeRequestBody jobTypeRequestBody = new JobTypeRequestBody();
            jobTypeRequestBody.setThirdId(id);
            jobTypeRequestBody.setName(jobtitlename);
            jobTypeList.add(jobTypeRequestBody);
        }
        return jobTypeList;
    }



    public static String extractChinesePart(String input) {
        // 正则表达式匹配 ~`~`数字 中文内容`~`数字 的模式
        Pattern pattern = Pattern.compile("~`~`\\d+ ([\u4e00-\u9fa5]+)`~`");
        Matcher matcher = pattern.matcher(input);

        if (matcher.find()) {
            return matcher.group(1);  // 返回匹配的第一个分组，即中文内容
        }

        //birthdayReminders
        return input;
    }
}
