package com.yanzhu.jh.project.task;

import cn.hutool.core.date.DateUtil;
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.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("attendanceHuazhuTask")
public class AttendanceHuazhuTask {
    @Autowired
    ISurProjectAttendanceUserService attendanceUserService;

    @Autowired
    ISurProjectAttendanceCfgService attendanceCfgService;

    @Autowired
    ISurProjectAttendanceDataService attendanceDataService;

    @Autowired
    ISurProjectAttendanceGroupService attendanceGroupService;


    public static void main(String[] args) {
        //String host="http://tapi.huazhukeji.cn:82/hz-labour";
        String host="http://api.1357.cn/hz-labour";
        //String path="/api/open/labour/findWorkerTypeByPage";
        String path="/api/open/labour/findCardRecordByPage";
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(host + path))
                .newBuilder();


        long startTime=DateUtil.date(DateUtil.parse("2024-03-16")).getTime();
        long endTime=startTime+3600*1000*24*1;
        Map<String, String> headerParams=new HashMap<>();
        headerParams.put("appId","8024283707153666851");
        headerParams.put("appSecret","2070308b49399d94b401d98adeaa5b342aa81627");
        headerParams.put("Content-Type","application/json");

        Map<String, Object> params = new HashMap<>();
        params.put("orgId","1666339529033805825");
        params.put("tenantId","1666337067184893953");
        params.put("size","200");
        params.put("current","1");
        params.put("startTime",startTime);
        params.put("endTime",endTime);

        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .post(toFormBody(params)).headers(setHeaderParams(headerParams))
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONObject joData= jo.getJSONObject("data");
        JSONArray arr=joData.getJSONArray("records");
        long pages=joData.getLong("pages");
        if(arr!=null && arr.size()>0){
            for(int i=0;i<arr.size();i++) {
                JSONObject json = arr.getJSONObject(i);
                SurProjectAttendanceData sdata = SurProjectAttendanceData.createFromHuazhu(json);
                System.out.println(JSON.toJSONString(sdata));
            }
        }

    }
    //380649600000
    public static void main2(String[] args) {
        //String s= DateUtil.format(DateUtil.date(1704167341751l),"yyyy-MM-dd HH:mm:ss");
        System.out.println(DateUtil.current());

    }
    public static void main3(String[] args) {
        String path="/api/open/labour/findLabourWorkerByPage";
        Map<String,String> map=new HashMap<>();

        map.put("appId","8024283707153666851");
        map.put("secret","2070308b49399d94b401d98adeaa5b342aa81627");
        map.put("projectId","1666339529033805825");
        map.put("tenantId","1666337067184893953");
        JSONObject jo=JSON.parseObject(JSON.toJSONString(map));
        int page=1;
        SurProjectAttendanceCfg it=new SurProjectAttendanceCfg();
        it.setId(0l);;
        //new AttendanceHuazhuTask().doSyncWorker(jo,1,it);
        //long p=jo.getLongValue("page",1);
        //jo.put("page",1);
        //System.out.println(p);
        //System.out.println(jo.toString());
        new AttendanceHuazhuTask().doSyncGroup(jo,1,it);
        //new AttendanceHuazhuTask().doSyncWorker(jo,1,it);
    }
    private static RequestBody toFormBody(Map<String, Object> params ){
        String json=JSON.toJSONString(params);
        return  RequestBody.create(
                MediaType.parse("application/json"),json );
    }
    private static  Headers setHeaderParams(Map<String, String> headerParams) {
        Headers headers = null;
        Headers.Builder headersbuilder = new Headers.Builder();
        if (headerParams != null && headerParams.size() > 0) {
            for (String key : headerParams.keySet()) {
                if (!Strings.isEmpty(key) && !Strings.isEmpty(headerParams.get(key))) {
                    //如果参数不是null并且不是""，就拼接起来
                    headersbuilder.add(key, headerParams.get(key));
                }
            }
        }

        headers = headersbuilder.build();
        return headers;
    }

    /**
     * 同步90天之内的数据
     */
    public void  syncLast90DayAttendanceData() {
        long endTime=DateUtil.current();
        long startTime=endTime-3600*1000*24*90;
        syncAttendanceData(startTime);
    }

    /**
     * 同步7天之内的数据
     */
    public void  syncLastWeekAttendanceData() {
        long endTime=DateUtil.current();
        long startTime=endTime-3600*1000*24*7;
        syncAttendanceData(startTime);
    }

    /**
     * 同步当天数据
     */
    public void  syncAttendanceData(){
        long startTime=DateUtil.date(DateUtil.parse(DateUtil.format(new Date(),"yyyy-MM-dd"))).getTime();
        syncAttendanceData(startTime);
    }

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

    private void doSyncGroup(JSONObject jdata, long page, SurProjectAttendanceCfg it) {
        String path="/api/open/labour/findUnitProjectByPage";
        Request request=getRequest(path,jdata,page);
        String data=AttendanceTask.getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONObject joData= jo.getJSONObject("data");
        JSONArray arr=joData.getJSONArray("records");
        long pages=joData.getLong("pages");
        if(arr!=null && arr.size()>0){
            for(int i=0;i<arr.size();i++) {
                JSONObject json = arr.getJSONObject(i);
                SurProjectAttendanceGroup group=SurProjectAttendanceGroup.createHuazhu(json);
                group.setCfgid(it.getId());
                group.setAppId(jdata.getString("appId"));
                attendanceGroupService.add(group);
            }
        }
        if(page<pages){
            doSyncGroup(jdata,page+1,it);
        }
    }

    private void syncAttendanceData(long startTime){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("huazhu");
        List<SurProjectAttendanceCfg> list=attendanceCfgService.selectSurProjectAttendanceCfgList(where);
        Map<String,Object> map=new HashMap<>();
        long endTime=DateUtil.current();

        //map.put("endTime",endTime);
        map.put("startTime",startTime);
        for(SurProjectAttendanceCfg it :list){
            String param= it.getVendorsParameter();
            if(Strings.isNotEmpty(param)){
                try{
                    JSONObject jo=JSON.parseObject(param);
                    doSyncAttendanceData(jo,1,it,map);

                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * 同步所有数据
     */
    public void  syncAllAttendanceData(){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("huazhu");
        List<SurProjectAttendanceCfg> list=attendanceCfgService.selectSurProjectAttendanceCfgList(where);
        for(SurProjectAttendanceCfg it :list){
            String param= it.getVendorsParameter();
            if(Strings.isNotEmpty(param)){
                try{
                    JSONObject jo=JSON.parseObject(param);
                    Long page=attendanceDataService.getHuazhuPage(it.getId());
                    if(null==page){
                        doSyncAttendanceData(jo,1,it,null);
                    }else{
                        doSyncAttendanceData(jo,page,it,null);
                    }

                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }
    private   void doSyncAttendanceData(JSONObject jdata,long page,SurProjectAttendanceCfg it,Map<String,Object> ps){
        String path="/api/open/labour/findCardRecordByPage";
        Request request=getRequest(path,jdata,page,ps);
        String data=AttendanceTask.getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONObject joData= jo.getJSONObject("data");
        JSONArray arr=joData.getJSONArray("records");
        long pages=joData.getLong("pages");
        if(arr!=null && arr.size()>0){
            for(int i=0;i<arr.size();i++) {
                JSONObject json = arr.getJSONObject(i);
                SurProjectAttendanceData sdata = SurProjectAttendanceData.createFromHuazhu(json);
                sdata.setVendorId(page); //VendorId保存华筑的页
                sdata.setCfgid(it.getId());
                sdata.setAppId(jdata.getString("appId"));
                sdata.setVendorsCode(it.getVendorsCode());
                attendanceDataService.add(sdata);
            }
        }
        if(page<pages){
            doSyncAttendanceData(jdata,page+1,it,ps);
        }
    }

    /**
     * 同步人员信息
     */
    public  void syncWorker(){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("huazhu");
        List<SurProjectAttendanceCfg> list=attendanceCfgService.selectSurProjectAttendanceCfgList(where);
        for(SurProjectAttendanceCfg it :list){
            String param= it.getVendorsParameter();
            if(Strings.isNotEmpty(param)){
                try{
                    JSONObject jo=JSON.parseObject(param);

                    doSyncWorker(jo,1,it);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }
    public static  Request getRequest(String path,JSONObject jo,long page) {
        return  getRequest(path,jo,page,null);
    }
    public static  Request getRequest(String path,JSONObject jo,long page,Map<String,Object> ps){
        String appId=jo.getString("appId");
        String secret=jo.getString("secret");
        String projectId=jo.getString("projectId");
        String tenantId=jo.getString("tenantId");
        String host="http://api.1357.cn/hz-labour";
        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(host + path))
                .newBuilder();

        Map<String, String> headerParams=new HashMap<>();
        headerParams.put("appId",appId);
        headerParams.put("appSecret",secret);
        headerParams.put("Content-Type","application/json");

        Map<String, Object> params = new HashMap<>();
        params.put("orgId",projectId);
        params.put("tenantId",tenantId);
        params.put("size",500);
        params.put("current",page);
        if(ps!=null){
            for(String k :ps.keySet()){
                params.put(k,ps.get(k));
            }
        }

        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .post(toFormBody(params)).headers(setHeaderParams(headerParams))
                .build();
        return request;
    }
    private  void doSyncWorker(JSONObject jdata,long page,SurProjectAttendanceCfg it){
        String path="/api/open/labour/findLabourWorkerByPage";
        Request request=getRequest(path,jdata,page);
        String data=AttendanceTask.getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONObject joData= jo.getJSONObject("data");
        JSONArray arr=joData.getJSONArray("records");
        long pages=joData.getLong("pages");
        if(arr!=null && arr.size()>0){
            for(int i=0;i<arr.size();i++){
                JSONObject json=arr.getJSONObject(i);
                SurProjectAttendanceUser user=SurProjectAttendanceUser.createFromHuazhu(json);
                user.setVendorsCode(it.getVendorsCode());
                user.setCfgid(it.getId());
                user.setAppId(jdata.getString("appId"));
                attendanceUserService.add(user);

            }
        }
        if(page<pages){
            doSyncWorker(jdata,page+1,it);
        }
    }
}
