package com.yanzhu.jh.project.task;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.yanzhu.jh.project.domain.SurProjectAttendanceCfg;
import com.yanzhu.jh.project.domain.SurProjectAttendanceData;
import com.yanzhu.jh.project.domain.SurProjectAttendanceGroup;
import com.yanzhu.jh.project.domain.SurProjectAttendanceUser;
import com.yanzhu.jh.project.service.ISurProjectAttendanceCfgService;
import com.yanzhu.jh.project.service.ISurProjectAttendanceDataService;
import com.yanzhu.jh.project.service.ISurProjectAttendanceGroupService;
import com.yanzhu.jh.project.service.ISurProjectAttendanceUserService;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Component("attendanceTask")
public class AttendanceTask {

    @Autowired
    ISurProjectAttendanceUserService attendanceUserService;

    @Autowired
    ISurProjectAttendanceCfgService attendanceCfgService;

    @Autowired
    ISurProjectAttendanceDataService attendanceDataService;

    @Autowired
    ISurProjectAttendanceGroupService attendanceGroupService;
    public  void syncWorker(){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("gld");
        List<SurProjectAttendanceCfg> list=attendanceCfgService.selectSurProjectAttendanceCfgList(where);
        for(SurProjectAttendanceCfg it :list){
            String param= it.getVendorsParameter();
            if(Strings.isNotEmpty(param)){
                try{
                    JSONObject jo=JSON.parseObject(param);
                    String appId=jo.getString("appId");
                    String secret=jo.getString("secret");
                    String projectId=jo.getString("projectId");
                    doSyncWorker(appId,secret,projectId,1,it);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    public void syncGroup(){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("gld");
        List<SurProjectAttendanceCfg> list=attendanceCfgService.selectSurProjectAttendanceCfgList(where);
        for(SurProjectAttendanceCfg it :list){
            String param= it.getVendorsParameter();
            if(Strings.isNotEmpty(param)){
                try{
                    JSONObject jo=JSON.parseObject(param);
                    String appId=jo.getString("appId");
                    String secret=jo.getString("secret");
                    String projectId=jo.getString("projectId");
                    doSyncGroup(appId,secret,projectId,it);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    private void doSyncGroup(String appId, String secret, String projectId, SurProjectAttendanceCfg it) {
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", projectId);
        params.put("appid",appId);
        String sign = getSign(params,secret);
        String host="https://glm.glodon.com/api/open";
        params.put("sign",sign);
        String path="/worker/allGroup";
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(host + path)).newBuilder();
        params.forEach((s, o) -> {
            urlBuilder.addQueryParameter(s, (String) o);
        });
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();
        String data=getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONArray arr=jo.getJSONArray("data");
        if(arr!=null && arr.size()>0) {
            for (int i = 0; i < arr.size(); i++) {
                JSONObject json=arr.getJSONObject(i);
                SurProjectAttendanceGroup group=SurProjectAttendanceGroup.create(json);
                group.setCfgid(it.getId());
                attendanceGroupService.add(group);
            }
        }
    }

    private  void doSyncWorker(String appid,String secret,String projectld,int page,SurProjectAttendanceCfg it){
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", projectld);
        params.put("start", "2000-01-01 00:00:00");
        params.put("end", "2099-01-01 00:00:00");
        params.put("pageNo",""+page);
        params.put("pageSize", "1000");
        params.put("appid",appid);
        String sign = getSign(params,secret);
        String host="https://glm.glodon.com/api/open";
        params.put("sign",sign);
        String path="/worker/new/allWorkerInfo";
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(host + path)).newBuilder();
        params.forEach((s, o) -> {
            urlBuilder.addQueryParameter(s, (String) o);
        });
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();
        String data=getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONArray arr=jo.getJSONArray("data");
        if(arr!=null && arr.size()>0){
          for(int i=0;i<arr.size();i++){
              JSONObject json=arr.getJSONObject(i);
              SurProjectAttendanceUser user=SurProjectAttendanceUser.create(json);
              user.setVendorsCode(it.getVendorsCode());
              user.setCfgid(it.getId());
              attendanceUserService.add(user);
          }
        }
        if(arr.size()==1000){
            doSyncWorker(appid,secret,projectld,page+1,it);
        }
    }
    public static void main1(String[] args) {
        //syncWorker("8fba899a21c64be4aa25bf0f3314ad5c","426b3d8280620176d80a826eebef3579","719148569880576",1);
        //doSyncAttendanceData("8fba899a21c64be4aa25bf0f3314ad5c","426b3d8280620176d80a826eebef3579","719148569880576",0,null);
    }

    public void  syncAttendanceData(){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("gld");
        List<SurProjectAttendanceCfg> list=attendanceCfgService.selectSurProjectAttendanceCfgList(where);
        for(SurProjectAttendanceCfg it :list){
            String param= it.getVendorsParameter();
            if(Strings.isNotEmpty(param)){
                try{
                    JSONObject jo=JSON.parseObject(param);
                    String appId=jo.getString("appId");
                    String secret=jo.getString("secret");
                    String projectId=jo.getString("projectId");
                    SurProjectAttendanceData dwhere=new SurProjectAttendanceData();
                    dwhere.setCfgid(it.getId());
                    long startId=attendanceDataService.getLastServerId(dwhere);
                    doSyncAttendanceData(appId,secret,projectId,startId,it);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }
    private   void doSyncAttendanceData(String appid,String secret,String projectld,long id,SurProjectAttendanceCfg it){
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", projectld);
        params.put("startId",""+id);
        params.put("pageSize", "500");
        params.put("appid",appid);
        String sign = getSign(params,secret);
        String host="https://glm.glodon.com/api/open";
        params.put("sign",sign);
        String path="/attendance/card";
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(host + path)).newBuilder();
        params.forEach((s, o) -> {
            urlBuilder.addQueryParameter(s, (String) o);
        });
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();
        String data=getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONArray arr=jo.getJSONArray("data");
        long lastId=0;
        if(arr!=null && arr.size()>0){
            for(int i=0;i<arr.size();i++){
                JSONObject json=arr.getJSONObject(i);
                SurProjectAttendanceData sdata=SurProjectAttendanceData.create(json);
                lastId=sdata.getServerid();
                sdata.setCfgid(it.getId());
                sdata.setVendorsCode(it.getVendorsCode());
               attendanceDataService.add(sdata);
            }
        }
        System.out.println("-------->"+id+","+lastId);
        if(arr.size()==500){
            doSyncAttendanceData(appid,secret,projectld,lastId,it);
        }
    }
    public static void main(String[] args){
        System.out.println("-------1--------->AttendanceUserTask.syncWorker");
        Map<String, Object> params = new HashMap<>();
        params.put("projectId", "719148569880576");
        //params.put("start", "2023-10-06 00:00:00");
        //params.put("end", "2023-10-07 00:00:00");
        //params.put("pageNo", "1");
        params.put("startId", "6755780004");
        params.put("pageSize", "1000");
        params.put("appid","8fba899a21c64be4aa25bf0f3314ad5c");
        String sign = getSign(params,"426b3d8280620176d80a826eebef3579");
        System.out.println("--->"+sign);
        params.put("sign",sign);
        String host="https://glm.glodon.com/api/open";
        String path="/attendance/card";
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(host + path)).newBuilder();
        params.forEach((s, o) -> {
            urlBuilder.addQueryParameter(s, (String) o);
        });
        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();
        String data=getResult(request);
        //System.out.println("data:"+data);
        JSONObject jo= JSON.parseObject(data);
        JSONArray jsonArray=jo.getJSONArray("data");
        for(int i=0;i<jsonArray.size();i++){
            JSONObject o=jsonArray.getJSONObject(i);
            if(o.getLong("workerId")==7813018){
                System.out.println(o.toString());
            }
        }
    }



    private static String getResult(Request request) {
        OkHttpClient client = new OkHttpClient();
        Response response;
        try {
            response = client.newCall(request).execute();
            if (response.body() != null) {
                return response.body().string();
            } else {
                throw new RuntimeException();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
    private static String getSign(Map<String,Object> paramsMap,String appSecret){
        List<String> paramsList = new ArrayList<>();
        paramsMap.forEach((s, o) -> {
            String stringBuilder = s + o;
            paramsList.add(stringBuilder);
        });
        StringBuilder beforeMd5 = new StringBuilder();
        beforeMd5.append(appSecret);
        paramsList.stream()
                .sorted(String::compareTo)
                .collect(Collectors.toList())
                .forEach(beforeMd5::append);
        beforeMd5.append(appSecret);
        return DigestUtils.md5Hex(beforeMd5.toString()).toUpperCase();
    }
}
