package com.muzhi.dingtalk.test.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiSmartworkHrmEmployeeListRequest;
import com.dingtalk.api.request.OapiSmartworkHrmEmployeeQueryonjobRequest;
import com.dingtalk.api.response.OapiSmartworkHrmEmployeeListResponse;
import com.dingtalk.api.response.OapiSmartworkHrmEmployeeQueryonjobResponse;
import com.muzhi.dingtalk.test.entity.vo.EmployeeFangDeDataVo;
import com.muzhi.dingtalk.test.entity.vo.EmployeeFangDeToChuanYunDataVo;
import com.muzhi.dingtalk.test.entity.vo.EmployeeFangDeToChuanYunVo;
import com.muzhi.dingtalk.test.entity.vo.EmployeeFangDeVo;
import com.muzhi.dingtalk.test.mapper.EmployeeFangDeMapper;
import com.muzhi.dingtalk.test.service.ChuanYunTongbuService;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChuanYunTongbuServiceImpl implements ChuanYunTongbuService {

    @Autowired
    private FangDeDingAccessTokenServiceImpl fangDeDingAccessTokenService;

    //在职员工花名册变量
    public static String huamingce = null;
    //离职员工花名册变量
    public static String huamingce2 = null;

    //在职员工id变量
    public static String employee1 = null;
    //离职员工id变量
    public static String employee2 = null;


    @Override
    public String getFangDeHuamingceAll(){

        //在职员工id列表的循环获取
        DingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
        OapiSmartworkHrmEmployeeQueryonjobRequest request1 = new OapiSmartworkHrmEmployeeQueryonjobRequest();

        //企业在职员工userid列表
        int offset = 0;//分页游标，从0开始
        int size = 50;//分页大小，最大50

        JSONObject result1;

        String result11;

        do {
            List<String> list = new ArrayList<>();

            System.out.println("测试分页值：" + offset);

            try {
                request1.setStatusList("2,3,5,-1");
                request1.setOffset((long) offset);
                request1.setSize((long) size);
                OapiSmartworkHrmEmployeeQueryonjobResponse response1 = client1.execute(request1, fangDeDingAccessTokenService.getFangDeAccessToken());
                employee1 = response1.getBody();
                System.out.println(response1.getBody());
            } catch (ApiException e) {
                e.printStackTrace();
            }

            //通过fastjson工具转换成json对象,逐层解析
            JSONObject jsonObject1 = JSON.parseObject(employee1);
            result1 = jsonObject1.getJSONObject("result");

            String dataList = result1.getString("data_list");

            //将String数组进行处理，去掉所有的双引号（""）和中括号（[]）
            String dataRes = dataList.replace("\"", "").
                    replaceAll("\\[", "").
                    replaceAll("\\]", "");

            list.add(dataRes);

            String userid1 = list.toString().replace("\"", "").
                    replaceAll("\\[", "").
                    replaceAll("\\]", "");


            //TODO ---原始同步花名册数据至数据库--- //
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list");
            OapiSmartworkHrmEmployeeListRequest request = new OapiSmartworkHrmEmployeeListRequest();

            try {
                request.setUseridList(userid1);
//                request.setUseridList("046828063924575294");

                //需要获取的花名册字段信息
//                request.setFieldFilterList("sys00-name,145d3425-9dea-42a6-88ae-1e4e3590046c,473f9667-d220-426f-8431-56be1e8a027d," +
//                        "395840c1-2cbe-4f36-b3fb-249d7ddf42f2,sys00-confirmJoinTime,sys02-sexType,sys02-certNo,sys01-employeeType," +
//                        "sys04-accountBank,sys04-bankAccountNo,ed21c116-efcb-49f3-a507-f8474450260c,sys01-employeeStatus");

                OapiSmartworkHrmEmployeeListResponse response = client.execute(request, fangDeDingAccessTokenService.getFangDeAccessToken());
                huamingce = response.getBody();
                System.out.println(response.getBody());
            }catch (ApiException e){
                e.printStackTrace();
            }

            //通过fastjson工具转换成json对象,逐层解析
            //将String类型的花名册json数据转换为Object数据对象
            JSONObject jsonObject = JSON.parseObject(huamingce);

            //直接将花名册对象通过Object转换成Array数组格式
            result11 = jsonObject.getString("result");



            if (result1.getString("next_cursor") != null || result1.getString("data_list") != "") {

                offset = offset + size;

            }

        } while (result1.getString("next_cursor") != null);


        return result11;

    }


    //将房德钉钉花名册数据先处理成指定的json格式数据
    @Override
    public EmployeeFangDeToChuanYunDataVo<EmployeeFangDeToChuanYunVo> getFangDeHuamingceToCY() {

        //在职员工id列表的循环获取
        DingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/queryonjob");
        OapiSmartworkHrmEmployeeQueryonjobRequest request1 = new OapiSmartworkHrmEmployeeQueryonjobRequest();

        //企业在职员工userid列表
        int offset = 0;//分页游标，从0开始
        int size = 50;//分页大小，最大50

        JSONObject result1;

        EmployeeFangDeToChuanYunDataVo employeeFangDeToChuanYunDataVo = new EmployeeFangDeToChuanYunDataVo();

        List<EmployeeFangDeToChuanYunVo> employeeFangDeToChuanYunVoList = new ArrayList<>();

        do {
            List<String> list = new ArrayList<>();

            System.out.println("测试分页值：" + offset);

            try {
                request1.setStatusList("2,3,5,-1");
                request1.setOffset((long) offset);
                request1.setSize((long) size);
                OapiSmartworkHrmEmployeeQueryonjobResponse response1 = client1.execute(request1, fangDeDingAccessTokenService.getFangDeAccessToken());
                employee1 = response1.getBody();
                System.out.println(response1.getBody());
            } catch (ApiException e) {
                e.printStackTrace();
            }

            //通过fastjson工具转换成json对象,逐层解析
            JSONObject jsonObject1 = JSON.parseObject(employee1);
            result1 = jsonObject1.getJSONObject("result");

            String dataList = result1.getString("data_list");

            //将String数组进行处理，去掉所有的双引号（""）和中括号（[]）
            String dataRes = dataList.replace("\"", "").
                    replaceAll("\\[", "").
                    replaceAll("\\]", "");

            list.add(dataRes);

            String userid1 = list.toString().replace("\"", "").
                    replaceAll("\\[", "").
                    replaceAll("\\]", "");


            //TODO ---原始同步花名册数据至数据库--- //
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/smartwork/hrm/employee/list");
            OapiSmartworkHrmEmployeeListRequest request = new OapiSmartworkHrmEmployeeListRequest();

            try {
                request.setUseridList(userid1);

                //需要获取的花名册字段信息
//                request.setFieldFilterList("sys00-name,145d3425-9dea-42a6-88ae-1e4e3590046c,473f9667-d220-426f-8431-56be1e8a027d," +
//                        "395840c1-2cbe-4f36-b3fb-249d7ddf42f2,sys00-confirmJoinTime,sys02-sexType,sys02-certNo,sys01-employeeType," +
//                        "sys04-accountBank,sys04-bankAccountNo,ed21c116-efcb-49f3-a507-f8474450260c,sys01-employeeStatus");

                OapiSmartworkHrmEmployeeListResponse response = client.execute(request, fangDeDingAccessTokenService.getFangDeAccessToken());
                huamingce = response.getBody();
                System.out.println(response.getBody());
            }catch (ApiException e){
                e.printStackTrace();
            }

            //通过fastjson工具转换成json对象,逐层解析
            //将String类型的花名册json数据转换为Object数据对象
            JSONObject jsonObject = JSON.parseObject(huamingce);

            //直接将花名册对象通过Object转换成Array数组格式
            JSONArray resultArray = jsonObject.getJSONArray("result");



            //氚云接口同步单条业务数据固定参数
            employeeFangDeToChuanYunDataVo.setActionName("CreateBizObjects");
            employeeFangDeToChuanYunDataVo.setSchemaCode("D116604ab3e5ca3a3f944b2bb2db76b67780a2a");
            employeeFangDeToChuanYunDataVo.setIsSubmit("true");



            for (int i = 0; i<resultArray.size(); i++){
                JSONArray fieldListArray = resultArray
                        .getJSONObject(i).getJSONArray("field_list");

                String userid = resultArray.getJSONObject(i).getString("userid");
                System.out.println("员工id：" + userid);

                //new一个employeeFangDeVo对象
                EmployeeFangDeToChuanYunVo employeeFangDeToChuanYunVo = new EmployeeFangDeToChuanYunVo();

                employeeFangDeToChuanYunVo.setF0000009(userid);
                employeeFangDeToChuanYunVo.setF0000011("sys00");


                for (int a = 0; a<fieldListArray.size(); a++){
                    String fieldCode = fieldListArray
                            .getJSONObject(a)
                            .getString("field_code");

                    switch (fieldCode){
                        //姓名
                        case "sys00-name":
                            if (fieldListArray.getJSONObject(a).getString("value") != null){
                                System.out.println("***《《《姓名》》》***-->" + fieldListArray.getJSONObject(a).getString("value"));

                                employeeFangDeToChuanYunVo.setF0000001(fieldListArray.getJSONObject(a).getString("value"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000001("");
                            }
                            break;

                        //主部门
                        case "sys00-mainDept":
                            if (fieldListArray.getJSONObject(a).getString("label") != null){
                                System.out.println("***主部门***-->" + fieldListArray.getJSONObject(a).getString("label"));

                                employeeFangDeToChuanYunVo.setF0000002(fieldListArray.getJSONObject(a).getString("label"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000002("");
                            }
                            break;

                        //劳动合同签约主体（所属公司）
                        case "145d3425-9dea-42a6-88ae-1e4e3590046c":
                            if (fieldListArray.getJSONObject(a).getString("label") != null){
                                System.out.println("***劳动合同签约主体（所属公司）***-->" + fieldListArray.getJSONObject(a).getString("label"));

                                employeeFangDeToChuanYunVo.setF0000003(fieldListArray.getJSONObject(a).getString("label"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000003("");
                            }
                            break;

                        //现合同起始日
                        case "sys05-nowContractStartTime":
                            if (fieldListArray.getJSONObject(a).getString("value") != null){
                                System.out.println("***现合同起始日***-->" + fieldListArray.getJSONObject(a).getString("value"));

                                employeeFangDeToChuanYunVo.setF0000004(fieldListArray.getJSONObject(a).getString("value"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000004("");
                            }
                            break;

                        //现合同到期日
                        case "sys05-nowContractEndTime":
                            if (fieldListArray.getJSONObject(a).getString("value") != null){
                                System.out.println("***现合同到期日***-->" + fieldListArray.getJSONObject(a).getString("value"));

                                employeeFangDeToChuanYunVo.setF0000005(fieldListArray.getJSONObject(a).getString("value"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000005("");
                            }
                            break;

                        //职位
                        case "sys00-position":
                            if (fieldListArray.getJSONObject(a).getString("label") != null){
                                System.out.println("***职位***-->" + fieldListArray.getJSONObject(a).getString("label"));

                                employeeFangDeToChuanYunVo.setF0000006(fieldListArray.getJSONObject(a).getString("label"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000006(null);
                            }
                            break;

                        //入职时间
                        case "sys00-confirmJoinTime":
                            if (fieldListArray.getJSONObject(a).getString("value") != null){
                                System.out.println("***入职时间***-->" + fieldListArray.getJSONObject(a).getString("value"));

                                employeeFangDeToChuanYunVo.setF0000007(fieldListArray.getJSONObject(a).getString("value"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000007("");
                            }
                            break;

                        //岗位职级
                        case "sys01-positionLevel":
                            if (fieldListArray.getJSONObject(a).getString("value") != null){
                                System.out.println("***岗位职级***-->" + fieldListArray.getJSONObject(a).getString("value"));

                                employeeFangDeToChuanYunVo.setF0000008(fieldListArray.getJSONObject(a).getString("value"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000008("");
                            }
                            break;

                        //主部门id
                        case "sys00-mainDeptId":
                            if (fieldListArray.getJSONObject(a).getString("value") != null){
                                System.out.println("***户名***-->" + fieldListArray.getJSONObject(a).getString("value"));

                                employeeFangDeToChuanYunVo.setF0000010(fieldListArray.getJSONObject(a).getString("value"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000010("");
                            }
                            break;

                        //续签期限
                        case "sys05-contractPeriodType":
                            if (fieldListArray.getJSONObject(a).getString("value") != null){
                                System.out.println("***户名***-->" + fieldListArray.getJSONObject(a).getString("value"));

                                employeeFangDeToChuanYunVo.setF0000012(fieldListArray.getJSONObject(a).getString("value"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000012("");
                            }
                            break;

                        //续签次数
                        case "sys05-contractRenewCount":
                            if (fieldListArray.getJSONObject(a).getString("value") != null){
                                System.out.println("***户名***-->" + fieldListArray.getJSONObject(a).getString("value"));

                                employeeFangDeToChuanYunVo.setF0000013(fieldListArray.getJSONObject(a).getString("value"));
                            }
                            else{
                                employeeFangDeToChuanYunVo.setF0000013("");
                            }
                            break;
                    }
                }
                employeeFangDeToChuanYunVoList.add(employeeFangDeToChuanYunVo);
            }


            employeeFangDeToChuanYunDataVo.setBizObjectArray(employeeFangDeToChuanYunVoList);

            if (result1.getString("next_cursor") != null || result1.getString("data_list") != "") {

                offset = offset + size;

            }

        } while (result1.getString("next_cursor") != null);

        return employeeFangDeToChuanYunDataVo;
    }
}
