package com.yanzhu.jh.project.task;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.common.utils.uuid.UUID;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
@Component("attendanceJgwTask")
public class AttendanceJgwTask {
    @Autowired
    ISurProjectAttendanceUserService attendanceUserService;

    @Autowired
    ISurProjectAttendanceCfgService attendanceCfgService;

    @Autowired
    ISurProjectAttendanceDataService attendanceDataService;

    @Autowired
    ISurProjectAttendanceGroupService attendanceGroupService;

    static String host="http://api.gongyoumishu.com:80/gomeetapi/";
    //sign/photo/20240101/E24E76-C9A5CB-0000FF/1741751233297383424_8848.JPG
    public  static  String getToken(String appid,String secret){
        String grantType="client_credential";
        String path="/webapi/credential";
        Map<String, Object> params = new HashMap<>();
        params.put("appId",appid);
        params.put("secret",secret);
        params.put("grantType",grantType);
        Request request = new Request.Builder()
                .url(host+path)
                .post(toFormBody(params))
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONObject joData= jo.getJSONObject("data");
        if(joData!=null){
            return  joData.getString("token");

        }
        return null;
    }
    private static RequestBody toFormBody(Map<String, Object> params ){
            FormBody.Builder builder=new FormBody.Builder();
            for(String key :params.keySet()){
                builder.add(key,params.get(key).toString());
            }
        return builder.build();
    }

    public static void main(String[] args){
        String d="sxyzxx2024suc";
        System.out.println(Base64.encode(d));
        System.out.println(DateTime.now().year());

        String appid="6a6f24fe35b04ee0bcf31cfb46ed1051";
        String secret="c3h5enh4MjAyNHN1Yw==";
        String prjId="db955e11ef774e63968a47c3dc2acc15";//"b67f1baa6dca4558a16bf90a4681b82e";
        String token= getToken(appid,secret);
        if(token==null || token.length()==0){
            return;
        }
        System.out.println(token);
        System.out.println(DateUtil.format(DateTime.now(),"yyyy-MM-dd"));
        findAddWorkerByProject(appid,token,prjId,0);
        //findAttendanceByProject(appid,token,prjId);
        //findTeamByProjectId(appid,token,prjId);
        //findProContractorByProjectId(appid,token,prjId);
    }
    public static void findAttendanceByProject(String appId,String token,String projectId){
        String path="/webapi/project/findAttendanceByProject";
        String time = System.currentTimeMillis() + "";
        String startId="0";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;
        System.out.println(url);
        String tokenSign = Md5Utils.hash(url);
        System.out.println(tokenSign);
        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("projectId",projectId);
        params.put("startId",startId);
        params.put("startTime",DateUtil.format(DateTime.now(),"yyyy-MM-dd"));
        params.put("endTime",DateUtil.format(DateUtil.offsetDay(DateTime.now(),0),"yyyy-MM-dd"));
        Request request = new Request.Builder()
                .url(host+path)
                .post(toFormBody(params))
                .build();
        String data=AttendanceTask.getResult(request);
        System.out.println(data);
        JSONObject j= JSON.parseObject(data);
        JSONObject joData= j.getJSONObject("data");
        String endId= joData.getString("endId");
        JSONArray arr=joData.getJSONArray("workerAttList");
        if(arr!=null && arr.size()>0){
            for(int i=0;i<arr.size();i++) {
                JSONObject json = arr.getJSONObject(i);
                String photo=json.getString("signimg");
                String photoUrl=getPhoto(appId,token,photo);
                SurProjectAttendanceData sdata = SurProjectAttendanceData.createFromJgw(json);
                sdata.setScanPhoto(photoUrl);
            }
        }

    }

    private static String getPhoto(String appId,String token, String photo) {
        String path="/webapi/dictInfo/getPhoyoAllPaths";
        String time = System.currentTimeMillis() + "";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;
        String tokenSign = Md5Utils.hash(url);
        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("filePath",photo);
        Request request = new Request.Builder()
                .url(host+path)
                .post(toFormBody(params))
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject j= JSON.parseObject(data);
        JSONObject joData= j.getJSONObject("data");
        String purl=joData.getString("result");
        byte[] buffer= HttpUtil.downloadBytes(purl);
        String filePath= RuoYiConfig.getUploadPath();
        filePath="D:/data/uploadPath";
        try {
           return FileUtils.writeBytes(buffer, filePath+"/jgw");
        }catch (Exception ex){
            return  "";
        }
    }

    public  static  void findProContractorByProjectId(String appId,String token,String projectId){
        String path="/webapi/project/findProContractorByProjectId";
        String time = System.currentTimeMillis() + "";
        String startId="0";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;

        String tokenSign = Md5Utils.hash(url);

        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("projectId",projectId);
        params.put("rowId",startId);
        url=host+path+"?appId="+appId+"&tokenSign="+tokenSign+"&projectId="+projectId+"&timestamp="+time+"&rowId="+startId;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject j= JSON.parseObject(data);
        JSONObject joData= j.getJSONObject("data");
        JSONArray arr=joData.getJSONArray("proContractorList");
        if(arr.size()>0){
            for(int i=0;i<arr.size();i++){
                JSONObject json=arr.getJSONObject(i);
                SurProjectAttendanceGroup group=new SurProjectAttendanceGroup();
            }
        }
    }
    public  static  void findTeamByProjectId(String appId,String token,String projectId){
        String path="/webapi/project/findTeamByProjectId";
        String time = System.currentTimeMillis() + "";
        String startId="34549";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;

        String tokenSign = Md5Utils.hash(url);

        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("projectId",projectId);
        params.put("rowId",startId);
        url=host+path+"?appId="+appId+"&tokenSign="+tokenSign+"&projectId="+projectId+"&timestamp="+time+"&rowId="+startId;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject j= JSON.parseObject(data);
        JSONObject joData= j.getJSONObject("data");
        JSONArray arr=joData.getJSONArray("teamList");
        if(arr.size()>0){
            for(int i=0;i<arr.size();i++){
                JSONObject json=arr.getJSONObject(i);
                SurProjectAttendanceGroup group=SurProjectAttendanceGroup.createJgw(json);
                group.setBizLicense(json.getString("corpCode"));
                String type=json.getString("corpType");
                if("009".equals(type)){ //总包人员
                    group.setCompanyTypeId("1");
                }else if("007".equals(type)){//监理人员
                    group.setCompanyTypeId("8");
                }else if("006".equals(type)){//劳务人员
                    group.setCompanyTypeId("2");
                }
                if(StrUtil.isNotEmpty(group.getCompanyTypeId())){

                }

            }
        }
    }
    public static void findAddWorkerByProject(String appId,String token,String projectId,int startId){
        String path="/webapi/project/findAddWorkerByProject";
        String time = System.currentTimeMillis() + "";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;

        String tokenSign = Md5Utils.hash(url);

        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("projectId",projectId);
        params.put("startId",startId);
        Request request = new Request.Builder()
                .url(host+path)
                .post(toFormBody(params))
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject jo= JSON.parseObject(data);
        JSONObject joData= jo.getJSONObject("data");
        int endId= joData.getInteger("endId");
        JSONArray arr=joData.getJSONArray("workerList");
        if(arr.size()>0) {
            int cnt=0;
            for(int i=0;i<arr.size();i++){
                JSONObject json=arr.getJSONObject(i);
                String workerStatus= json.getString("workerStatus");
                if("02".equals(workerStatus)){
                    cnt++;
                }
               SurProjectAttendanceUser user=SurProjectAttendanceUser.createFromJgw(json);
            }
            System.out.println("cnt:"+cnt+","+arr.size());
            //findAddWorkerByProject(appId, token, projectId, endId);
        }
    }

    /**
     * 同步人员信息
     */
    public  void syncWorker(){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("jgw");
        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");
                    secret=Base64.encode(secret);
                    jo.put("secret",secret);
                    String token= getToken(appId,secret);
                    jo.put("token",token);
                    doSyncWorker(jo,0l,it);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    private void doSyncWorker(JSONObject jo, long startId, SurProjectAttendanceCfg it) {
        String appId=jo.getString("appId");
        String token=jo.getString("token");
        String projectId=jo.getString("projectId");
        String path="/webapi/project/findAddWorkerByProject";
        String time = System.currentTimeMillis() + "";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;

        String tokenSign = Md5Utils.hash(url);

        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("projectId",projectId);
        params.put("startId",startId);
        Request request = new Request.Builder()
                .url(host+path)
                .post(toFormBody(params))
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject j= JSON.parseObject(data);
        JSONObject joData= j.getJSONObject("data");
        long endId= joData.getLong("endId");
        JSONArray arr=joData.getJSONArray("workerList");
        if(arr.size()>0) {
            for(int i=0;i<arr.size();i++){
                JSONObject json=arr.getJSONObject(i);
                SurProjectAttendanceUser user=SurProjectAttendanceUser.createFromJgw(json);
                user.setVendorsCode(it.getVendorsCode());
                user.setCfgid(it.getId());
                user.setAppId(appId);
                attendanceUserService.add(user);
            }
            doSyncWorker(jo,endId,it);
        }
    }

    /**
     * 同步群组信息
     */
    public void syncGroup(){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("jgw");
        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");
                    secret=Base64.encode(secret);
                    jo.put("secret",secret);
                    String token= getToken(appId,secret);
                    jo.put("token",token);
                    doSyncGroup(jo,0l,it);
                    doSyncProContractor(jo,0l,it);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * 查询参建单位
     * @param jo
     * @param l
     * @param it
     */
    private void doSyncProContractor(JSONObject jo, long startId, SurProjectAttendanceCfg it) {
        String appId=jo.getString("appId");
        String token=jo.getString("token");
        String projectId=jo.getString("projectId");
        String path="/webapi/project/findProContractorByProjectId";
        String time = System.currentTimeMillis() + "";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;

        String tokenSign = Md5Utils.hash(url);

        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("projectId",projectId);
        params.put("rowId",startId);
        url=host+path+"?appId="+appId+"&tokenSign="+tokenSign+"&projectId="+projectId+"&timestamp="+time+"&rowId="+startId;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject j= JSON.parseObject(data);
        JSONObject joData= j.getJSONObject("data");
        JSONArray arr=joData.getJSONArray("proContractorList");
        if(arr.size()>0){
            long rowId=0;
            for(int i=0;i<arr.size();i++){
                JSONObject json=arr.getJSONObject(i);
                rowId=json.getLong("id");
                SurProjectAttendanceGroup group=SurProjectAttendanceGroup.createJgw(json);
                group.setBizLicense(json.getString("corpCode"));
                String type=json.getString("corpType");
                if("009".equals(type)){ //总包人员
                    group.setCompanyTypeId("1");
                }else if("007".equals(type)){//监理人员
                    group.setCompanyTypeId("8");
                }else if("006".equals(type)){//劳务人员
                    group.setCompanyTypeId("2");
                }
                if(StrUtil.isNotEmpty(group.getCompanyTypeId())){
                    attendanceGroupService.updateJgw(group);
                }
            }
            if(rowId>0){
                doSyncProContractor(jo,rowId+1,it);
            }
        }
    }

    /**
     * 查询班组
     * @param jo
     * @param startId
     * @param it
     */
    private void doSyncGroup(JSONObject jo, long startId, SurProjectAttendanceCfg it) {
        String appId=jo.getString("appId");
        String token=jo.getString("token");
        String projectId=jo.getString("projectId");
        String path="/webapi/project/findTeamByProjectId";
        String time = System.currentTimeMillis() + "";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;

        String tokenSign = Md5Utils.hash(url);

        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("projectId",projectId);
        params.put("rowId",startId);
        url=host+path+"?appId="+appId+"&tokenSign="+tokenSign+"&projectId="+projectId+"&timestamp="+time+"&rowId="+startId;
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        String data=AttendanceTask.getResult(request);
        JSONObject j= JSON.parseObject(data);
        JSONObject joData= j.getJSONObject("data");
        JSONArray arr=joData.getJSONArray("teamList");
        if(arr.size()>0){
            long rowId=0;
            for(int i=0;i<arr.size();i++){
                JSONObject json=arr.getJSONObject(i);
                SurProjectAttendanceGroup group=SurProjectAttendanceGroup.createJgw(json);
                group.setCfgid(it.getId());
                group.setAppId(appId);
                rowId=json.getLong("id");
                attendanceGroupService.add(group);
            }
            if(rowId>0){
                doSyncGroup(jo,rowId+1,it);
            }
        }
    }

    /**
     * 同步当天数据
     */
    public void syncAttendanceData(){
        String dtStart=DateUtil.format(DateTime.now(),"yyyy-MM-dd");
        String dtEnd=dtStart;
        syncAttendanceData(dtStart,dtEnd);
    }

    /**
     * 同步7天之内数据
     */
    public void syncLastWeekAttendanceData(){
        String dtEnd=DateUtil.format(DateTime.now(),"yyyy-MM-dd");
        String dtStart=DateUtil.format(DateUtil.offsetDay(DateTime.now(),-7),"yyyy-MM-dd");
        syncAttendanceData(dtStart,dtEnd);
    }

    /**
     * 同步30天内数据
     */
    public void syncLast30DayAttendanceData(){
        String dtEnd=DateUtil.format(DateTime.now(),"yyyy-MM-dd");
        String dtStart=DateUtil.format(DateUtil.offsetDay(DateTime.now(),-30),"yyyy-MM-dd");
        syncAttendanceData(dtStart,dtEnd);
        syncAttendanceData(dtStart,dtEnd);
    }


    private void syncAttendanceData(String dtStart,String dtEnd){
        SurProjectAttendanceCfg where =new SurProjectAttendanceCfg();
        where.setEnabled(1l);
        where.setIsDel(0l);
        where.setVendorsCode("jgw");
        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");
                    secret=Base64.encode(secret);
                    jo.put("secret",secret);
                    String token= getToken(appId,secret);
                    jo.put("token",token);
                    jo.put("startTime",dtStart);
                    jo.put("endTime",dtEnd);
                    doSyncAttendanceData(jo,"0",it);
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    private void doSyncAttendanceData(JSONObject jo, String startId, SurProjectAttendanceCfg it) {
        String appId=jo.getString("appId");
        String token=jo.getString("token");
        String projectId=jo.getString("projectId");
        String startTime=jo.getString("startTime");
        String endTime=jo.getString("endTime");
        String path="/webapi/project/findAttendanceByProject";
        String time = System.currentTimeMillis() + "";
        String url=host+path+"?appId=" + appId + "&tokenSign=" + token +"&timestamp=" + time;

        String tokenSign = Md5Utils.hash(url);
        Map<String, Object> params = new HashMap<>();
        params.put("appId",appId);
        params.put("timestamp",time);
        params.put("tokenSign",tokenSign);
        params.put("projectId",projectId);
        params.put("startId",startId);
        params.put("startTime",startTime);
        params.put("endTime",endTime);
        Request request = new Request.Builder()
                .url(host+path)
                .post(toFormBody(params))
                .build();
        String data=AttendanceTask.getResult(request);
        System.out.println(data);
        JSONObject j= JSON.parseObject(data);
        JSONObject joData= j.getJSONObject("data");
        String endId= joData.getString("endId");
        JSONArray arr=joData.getJSONArray("workerAttList");
        if(arr!=null && arr.size()>0){
            for(int i=0;i<arr.size();i++) {
                JSONObject json = arr.getJSONObject(i);
                String photo=json.getString("signimg");
                String photoUrl=getPhoto(appId,token,photo);
                SurProjectAttendanceData sdata = SurProjectAttendanceData.createFromJgw(json);
                sdata.setScanPhoto(photoUrl);
                sdata.setCfgid(it.getId());
                sdata.setAppId(appId);
                sdata.setVendorsCode(it.getVendorsCode());
                attendanceDataService.add(sdata);
            }
            doSyncAttendanceData(jo,endId,it);
        }
    }


}
