package weaver.mfbdt.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.time.util.DateUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;

import weaver.general.TimeUtil;
import weaver.general.Util;
import weaver.interfaces.schedule.BaseCronJob;
import weaver.mfbdt.util.DigestUtil;
import weaver.mfbdt.util.HttpClientUtil;
import weaver.mfbdt.util.SignUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 同步人员通行记录计划任务
 *
 * @author wangj
 * @version 1.00版本
 * @Date 2023/9/11
 */

public class SyncTrafficRecordsJob extends BaseCronJob {
    //总条数
    private static int total = 999999;
    //已同步的数据记录
    private static List<String> recordList;
    //人员工号-id信息
    private static Map<String,String> userMap;
    //插入的建模数据
    private static List<List<Object>> plist;
    @Override
    public void execute() {
        //获取八月份全量通行记录

        BaseBean bb = new BaseBean();
        // appkey,固定，
        String cappKey = Util.null2String(bb.getPropValue("ks_config","cappKey"));
        // 秘钥，固定
        String secret = Util.null2String(bb.getPropValue("ks_config","secret"));
        //ip端口 //http://10.122.101.181:18082
        String ipport = Util.null2String(bb.getPropValue("ks_config","ipport"));
        //考勤原始记录表模块id
        String formmodeid = Util.null2String(bb.getPropValue("ks_config","uf_kqysjl_formmodeid"));

        String modedatacreater = "1"; //模块创建人id
        String modedatacreatertype = "0"; //创建人类型(插入默认值0即可)
        String modedatacreatedate = DateUtil.getCurrentTime("yyyy-MM-dd");
        String modedatacreatetime = DateUtil.getCurrentTime("HH:mm:ss");

        //每页数量
        int pageSize = 1000;
        //页数
        int pageNum = 1;
        //通行类型 默认：1（通行）
        int passType = 1;

        total = 999999;

        String date = DateUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss");

        String before = weaver.mfbdt.util.TimeUtil.getBeforeHourDate(date);
        String beforehourdate = before.substring(0,13);

        //时间段查询，开始时间
        String startPassTime = beforehourdate+":00:00";
        //时间段查询，结束时间
        String endPassTime = beforehourdate+":59:59";

////        时间段查询，开始时间
//        String startPassTime = "2023-09-01 00:00:00";
//        //时间段查询，结束时间
//        String endPassTime = "2023-09-31 23:59:59";

        recordList = getRecordList(startPassTime,endPassTime);
        userMap = getUserMap();
        plist = new ArrayList<>(1000);
        bb.writeLog("--SyncTrafficRecordsJob-total1-:"+total);
        bb.writeLog("--SyncTrafficRecordsJob-plist-:"+plist.size());
        bb.writeLog("--SyncTrafficRecordsJob-recordList-:"+recordList.size());
        bb.writeLog("--SyncTrafficRecordsJob-userMap-:"+userMap.size());

        while ((pageNum -1) * pageSize < total){
            getTrafficRecords( formmodeid, modedatacreater, modedatacreatertype, modedatacreatedate, modedatacreatetime, ipport, cappKey, secret, pageNum, pageSize, passType, startPassTime, endPassTime);
            pageNum++;
        }
        bb.writeLog("--SyncTrafficRecordsJob-total2-:"+total);
        bb.writeLog("--SyncTrafficRecordsJob-plist-:"+plist.size());

        //批量插入建模数据
        StringBuffer sb = new StringBuffer();
        sb.append("insert into uf_kqysjl(");
        sb.append("MODEUUID,formmodeid,modedatacreater,modedatacreatertype,modedatacreatedate,modedatacreatetime,");
        sb.append("bh,xm,kqrq,kqsj,txjluuid,txlx,zpsbuuid,zpsbmc");
        sb.append(")values(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");

        BatchRecordSet batchRecordSet = new BatchRecordSet();
        batchRecordSet.executeBatchSql(sb.toString(), plist);

        //权限重构
        RecordSet rs = new RecordSet();
        String sql = "select id from uf_kqysjl where modedatacreatedate = '"+modedatacreatedate+"' and modedatacreatetime='" + modedatacreatetime + "'";
        rs.execute(sql);
        while (rs.next()) {
            int billid = Integer.parseInt(rs.getString("id"));
            ModeRightInfo info = new ModeRightInfo();
            info.setNewRight(true);
            info.rebuildModeDataShareByEdit(1, Integer.parseInt(formmodeid), billid);
        }


    }

    private Map<String,String> getUserMap(){
        Map<String,String> userMap = new HashMap<>(1000);
        RecordSet rs = new RecordSet();
        rs.execute("select id,workcode from hrmresource where LEN(workcode) > 0");
        while (rs.next()){
            String id = Util.null2String(rs.getString("id"));
            String workcode = Util.null2String(rs.getString("workcode"));
            userMap.put(workcode,id);
        }
        return userMap;
    }

    private List<String> getRecordList(String startPassTime, String endPassTime){
        List<String> list = new ArrayList<>(1000);
        RecordSet rs = new RecordSet();
        rs.executeQuery("select txjluuid from uf_kqysjl where CONVERT(DATE, concat(kqrq,' ',kqsj), 120) >= ? and CONVERT(DATE, concat(kqrq,' ',kqsj), 120) <= ?",startPassTime,endPassTime);
        while (rs.next()){
            String txjluuid = Util.null2String(rs.getString("txjluuid"));
            list.add(txjluuid);
        }
        return list;
    }

    private void getTrafficRecords(String formmodeid,String modedatacreater,String modedatacreatertype,String modedatacreatedate,String modedatacreatetime,String ipport,String cappKey,String secret,int pageNum,int pageSize,int passType,String startPassTime,String endPassTime){
        BaseBean bb = new BaseBean();
        String ctimestamp = DateUtil.getCurrentTime("yyyy-MM-dd HH:mm:ss");
        Date datec = TimeUtil.getString2Date(ctimestamp, "yyyy-MM-dd HH:mm:ss");
        long time = datec.getTime();
        ctimestamp = Util.object2String(time);
        // 时间戳，用户自己生成
        String cnonce = DigestUtil.getCnonce();
        // 6位随机码，用户自己生成
        String requestParam = "";
        //请求参数，form表单方式，鸿图大部分接口都是body传参，故这里大部分都是""，如果有参数，查看文档说明

        String url = Util.null2String(bb.getPropValue("ks_config","pass_record"));
        // 要请求的url,看要请求的接口说明
        String method = "POST";
        // 请求方式,看要请求的接口说明
//
        JSONObject requestBody = new JSONObject();

        requestBody.put("pageNum",pageNum);
        requestBody.put("pageSize",pageSize);
        requestBody.put("passType",passType);
        requestBody.put("startPassTime",startPassTime);
        requestBody.put("endPassTime",endPassTime);

        // 构建请求体，看要请求的接口说明
        // 计算签名
        String csign = SignUtils.sign(ctimestamp, cnonce, requestBody, requestParam, url, method, cappKey, secret);
        // 发起请求

        String realUrl = ipport + url;

        Map<String,String> header = new HashMap<>(100);
        header.put("ctimestamp",ctimestamp);
        header.put("csign",csign);
        header.put("cnonce",cnonce);
        header.put("cappKey",cappKey);
        if(pageNum == 1){
            bb.writeLog("-SyncTrafficRecordsJob-realUrl:"+realUrl);
            bb.writeLog("-SyncTrafficRecordsJob-header:"+header);
            bb.writeLog("-SyncTrafficRecordsJob-json:"+requestBody.toJSONString());
        }


        String json = requestBody.toJSONString();
        String result = HttpClientUtil.doPostJsonHeader(realUrl,json,header);
        bb.writeLog("-SyncTrafficRecordsJob-result:"+result);
        JSONObject resObj = JSONObject.parseObject(result);

        int code = (int) resObj.get("code");
        if(code == 0){
            JSONObject data = (JSONObject) resObj.get("data");
            if(pageNum == 1){
                bb.writeLog("-SyncTrafficRecordsJob-pass_record");
                bb.writeLog("-SyncTrafficRecordsJob-ctimestamp:"+ctimestamp);
                bb.writeLog("-SyncTrafficRecordsJob-cnonce:"+cnonce);
                bb.writeLog("-SyncTrafficRecordsJob-cappKey:"+cappKey);
                bb.writeLog("-SyncTrafficRecordsJob-csign:"+csign);
                bb.writeLog("-SyncTrafficRecordsJob-requestBody:"+requestBody);
                bb.writeLog("-SyncTrafficRecordsJob-url:"+url);
                total = (int) data.get("total");
            }
            bb.writeLog("-SyncTrafficRecordsJob-pageNum:"+pageNum);


            JSONArray listArr = (JSONArray) data.get("list");
            if(listArr.size() > 0){
                //插入数据到建模表
                for (int i = 0; i < listArr.size(); i++) {
                    JSONObject list = (JSONObject) listArr.get(i);
                    String uuid = Util.null2String((String) list.get("uuid"));
                    if(recordList.contains(uuid)){
                        continue;
                    }else{
                        recordList.add(uuid);
                        //插入数据到建模表
                        //工号
                        String bh = Util.null2String((String) list.get("personCode"));
                        //人员id
                        String userid = Util.null2String(userMap.get(bh));
                        if("".equals(bh)|| "".equals(userid)){
                            continue;
                        }
                        //通行时间 时间戳 1694419156000
                        String passTimestamp = Util.object2String(list.get("passTimestamp"));
                        Map<String,String> datetime = getDateTime(passTimestamp);

                        String kqrq = Util.null2String(datetime.get("date"));
                        String kqsj = Util.null2String(datetime.get("time"));
                        //通行类型
                        String txlx = Util.object2String(list.get("passType"));
                        //抓拍设备uuid
                        String zpsbuuid = Util.object2String(list.get("deviceUuid"));
                        //抓拍设备名称
                        String zpsbmc = Util.object2String(list.get("deviceName"));

                        List<Object> listobj = new ArrayList<>(100);
                        listobj.add(UUID.randomUUID().toString());
                        listobj.add(formmodeid);
                        listobj.add(modedatacreater);
                        listobj.add(modedatacreatertype);
                        listobj.add(modedatacreatedate);
                        listobj.add(modedatacreatetime);

                        //业务字段
                        listobj.add(bh);
                        listobj.add(userid);
                        listobj.add(kqrq);
                        listobj.add(kqsj);
                        listobj.add(uuid);
                        listobj.add(txlx);
                        listobj.add(zpsbuuid);
                        listobj.add(zpsbmc);

                        plist.add(listobj);
                    }
                }
            }
        }
    }

    private Map<String,String> getDateTime(String passTime){
        SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");
        String date = df.format(new Date(Long.parseLong(passTime)));

        SimpleDateFormat tf=new SimpleDateFormat("HH:mm");
        String time = tf.format(new Date(Long.parseLong(passTime)));

        Map<String,String> datetime = new HashMap<>(100);
        datetime.put("date",date);
        datetime.put("time",time);
        return datetime;
    }

}
