package me.zhengjie.modules.quartz.task;

import cn.hutool.http.HttpRequest;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.modules.dmAccessTraffic.domain.DmAccessTraffic;
import me.zhengjie.modules.dmAccessTraffic.repository.DmAccessTrafficRepository;
import me.zhengjie.modules.dmAccessTraffic.service.DmAccessTrafficService;
import me.zhengjie.modules.dmuser.domain.DmUser;
import me.zhengjie.modules.dmuser.repository.DmUserRepository;
import me.zhengjie.modules.dmuser.service.DmUserService;
import me.zhengjie.modules.dmuser.service.dto.DmUserQueryCriteria;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.dto.UserQueryCriteria;
import me.zhengjie.utils.BeanMapUtils;
import me.zhengjie.ykt.domain.DmRoomDevice;
import me.zhengjie.ykt.repository.DmRoomDeviceRepository;
import me.zhengjie.ykt.service.DmRoomDeviceService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

@Slf4j
@Component
@RequiredArgsConstructor
public class AccessDataTask {

    @Value("${accessUrl}")
    private String url;
    @Value("${getDeviceUrl}")
    private String getDeviceUrl;
    private final DmAccessTrafficService dmAccessTrafficService;
    private final DmAccessTrafficRepository dmAccessTrafficRepository;
    private final DmRoomDeviceService dmRoomDeviceService;
    private final DmRoomDeviceRepository roomDeviceRepository;
    private final DmUserService dmUserService;
    private final UserRepository userRepository;
    private final DmUserRepository dmUserRepository;

    public void run() throws ParseException, IOException {
        log.info("run 执行开始");
        createAccess();
        log.info("run 执行结束");
    }

    public void run2() throws ParseException, IOException {
        log.info("run2 执行开始");
        createAccessAll();
        log.info("run2 执行结束");
    }

    public JSONObject getData(String url ,JSONObject param){
        Map<String,String> formDataParam = new HashMap<>();
        System.out.println("formDataParam:"+param.toJSONString());
        formDataParam.put("date",param.toJSONString());
        String data = BeanMapUtils.doPostForm(url,formDataParam);
        System.out.println("historyRecord:"+data);
        JSONObject dataJSON = JSONObject.parseObject(data);
        return dataJSON;
    }

    public void createAccess() throws IOException, ParseException {
//        String url = "http://47.103.9.22:8069/openapi/getHistoryRecord";

        JSONObject data = new JSONObject();
        int limit = 100;//页数
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat formater2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY,-24);
        Date start = formater2.parse(formater.format(calendar.getTime())+ " 00:00:00");
        Date end = formater2.parse(formater.format(calendar.getTime())+ " 23:59:59");

        System.out.println("开始时间"+formater2.format(start));
        data.put("dateStart",formater2.format(start));
        data.put("dateEnd",formater2.format(end));
        data.put("page",1);//当前页数
        data.put("limit",limit);
        data.put("sort","desc");

        JSONObject generateProcDataJson = getData(url,data);

        Integer total = generateProcDataJson.getInteger("total");//总条数
        int pageTotal = (total / limit);
        if (total % limit != 0) {
            pageTotal++;
        }
        log.info("pageTotal:"+pageTotal);

        for(int i = 1;i<=pageTotal;i++){//循环总页数
            //获取当前页数
            data.put("page",i);//当前页数
            JSONObject newGenerateProcDataJson = getData(url,data);
            JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");//第二层
            JSONArray arr2 = dataJSON.getJSONArray("data");//第三层集合数据
            for (int j = 0;j<arr2.size();j++){//
                JSONObject attendance = arr2.getJSONObject(j);
                //组装返回数据
                JSONObject acc = new JSONObject();
                if (attendance.getString("open")=="true"){
                    acc.put("accessTime",attendance.getString("date"));
                    acc.put("cardNumber",attendance.getString("cardID"));
                    acc.put("userNumber",attendance.getString("userID"));//user
                    acc.put("roomDevice",attendance.getString("deviceID"));
                    acc.put("accessPhoto",attendance.getString("picture"));
                    if (attendance.getString("cardID")!=null){
                        acc.put("passageWay","园区卡");
                    }else {
                        acc.put("passageWay","其他");
                    }
                    DmAccessTraffic accessTraffic = JSON.toJavaObject(acc,DmAccessTraffic.class);
                    dmAccessTrafficService.create(accessTraffic);
                }
            }
        }
    }

    public void createAccessAll() throws IOException, ParseException {
//        String url = "http://47.103.9.22:8069/openapi/getHistoryRecord";

        JSONObject data = new JSONObject();
        int limit = 100;//页数
        data.put("dateStart","");
        data.put("dateEnd","");
        data.put("page",1);//当前页数
        data.put("limit",limit);
        data.put("sort","desc");

        JSONObject generateProcDataJson = getData(url,data);

        Integer total = generateProcDataJson.getInteger("total");//总条数
        int pageTotal = (total / limit);
        if (total % limit != 0) {
            pageTotal++;
        }
        log.info("pageTotal:"+pageTotal);

        for(int i = 1;i<=pageTotal;i++){//循环总页数
            //获取当前页数
            data.put("page",i);//当前页数
            JSONObject newGenerateProcDataJson = getData(url,data);
            JSONObject dataJSON = newGenerateProcDataJson.getJSONObject("data");//第二层
            JSONArray arr2 = dataJSON.getJSONArray("data");//第三层集合数据
            for (int j = 0;j<arr2.size();j++){//
                JSONObject attendance = arr2.getJSONObject(j);
                //组装返回数据
                JSONObject acc = new JSONObject();
                if (attendance.getString("open")=="true"){
                    acc.put("accessTime",attendance.getString("date"));
                    acc.put("cardNumber",attendance.getString("cardID"));
                    acc.put("userNumber",attendance.getString("userID"));//user
                    acc.put("roomDevice",attendance.getString("deviceID"));
                    acc.put("accessPhoto",attendance.getString("picture"));
                    if (attendance.getString("cardID")!=null){
                        acc.put("passageWay","园区卡");
                    }else {
                        acc.put("passageWay","其他");
                    }
                    DmAccessTraffic accessTraffic = JSON.toJavaObject(acc,DmAccessTraffic.class);
                    dmAccessTrafficService.create(accessTraffic);
                }
            }
        }
    }

    public void syncAccessData() throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        Date startDate = sdf2.parse(sdf.format(calendar.getTime())+ " 00:00:00");
        Date endDate = sdf2.parse(sdf.format(calendar.getTime())+ " 23:59:59");
        String start = sdf2.format(startDate);
        String end = sdf2.format(endDate);
        log.info("开始时间"+start);
        log.info("结束时间"+end);
        //查询本地当天的所有数据
        List<Map<String,String>> maps = dmAccessTrafficService.queryByAccessTime(start,end);
        //查询费浦当天的所有数据
        JSONArray array = getSelect(start,end);
        log.info("array:"+array.toJSONString());
        //进行今天所有数据的比对，没有的部分重新入库，并且同步到erp考勤系统
        for(int i = 0; i<array.size();i++){
            JSONObject object = array.getJSONObject(i);
            String UserID = object.getString("UserID");
            String Remark1 = object.getString("Remark1");
            String EventTime = object.getString("EventTime");
            String CardID = object.getString("CardID");
            log.info("UserID:"+UserID);
            log.info("Remark1:"+Remark1);
            log.info("EventTime:"+EventTime);
            log.info("CardID:"+CardID);
            //用于区分两个集合中是否有重复数据，如果出现重复数据，则为false，不进入新增操作
            Boolean isRepeat = true;
            for(Map<String,String> map : maps){
                String userNumber = map.get("user_number");
                String code = map.get("code");
                String accessTime = sdf2.format(map.get("access_time"));
                log.info("userNumber:"+userNumber);
                log.info("code:"+code);
                log.info("accessTime:"+accessTime);
                if(StringUtils.equals(UserID,userNumber) && StringUtils.equals(Remark1,code) && StringUtils.equals(EventTime,accessTime)){
                    isRepeat = false;
                }
            }
            if(isRepeat) {
                DmAccessTraffic dmAccessTraffic = new DmAccessTraffic();
                List<DmRoomDevice> roomDevice = dmRoomDeviceService.findByCode(Remark1,null);
                dmAccessTraffic.setRoomDevice(roomDevice.get(0).getCode());
                dmAccessTraffic.setCardNumber(CardID);
                DmUser dmUser = dmUserService.findByUserNumber(UserID);
                dmAccessTraffic.setUser(dmUser);
                dmAccessTraffic.setAccessTime(new Timestamp(sdf2.parse(EventTime).getTime()));
                DmAccessTraffic newDmAccessTraffic = dmAccessTrafficRepository.save(dmAccessTraffic);
                String erpAttendanceApi = "http://10.22.2.66:8700/attendance-api/device/identify/callback";
                //组装返回数据
                JSONObject ertAttendanceJSON = new JSONObject();
                ertAttendanceJSON.put("deviceKey", newDmAccessTraffic.getRoomDevice());
                ertAttendanceJSON.put("personId", newDmAccessTraffic.getUser().getUserNumber());
                ertAttendanceJSON.put("time", newDmAccessTraffic.getAccessTime());
                ertAttendanceJSON.put("type", "face_0");
                System.out.println("ertAttendanceJSON:" + ertAttendanceJSON);
                String res = HttpRequest.get(erpAttendanceApi).body(ertAttendanceJSON.toJSONString()).execute().body();
                System.out.println("res:" + res);
            }
        }
    }

    public void syncAccessData2() throws ParseException {
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.HOUR_OF_DAY,-2);
        Calendar calendar2 = Calendar.getInstance();
        String start = sdf2.format(calendar.getTime());
        String end = sdf2.format(calendar2.getTime());
        log.info("开始时间"+start);
        log.info("结束时间"+end);
        //查询费浦当天的所有数据
        JSONArray array = getSelect(start,end);
        log.info("array:"+array.toJSONString());
        //进行今天所有数据的比对，没有的部分重新入库，并且同步到erp考勤系统
        for(int i = 0; i<array.size();i++){
            JSONObject object = array.getJSONObject(i);
            String UserID = object.getString("UserID");
            String Remark1 = object.getString("Remark1");
            String EventTime = object.getString("EventTime");
            String CardID = object.getString("CardID");
            log.info("UserID:"+UserID);
            log.info("Remark1:"+Remark1);
            log.info("EventTime:"+EventTime);
            log.info("CardID:"+CardID);
            //用于区分两个集合中是否有重复数据，如果出现重复数据，则为false，不进入新增操作
            DmUser dmUser = dmUserService.findByUserNumber(UserID);
            if(!ObjectUtils.isEmpty(dmUser)){
                String id = dmUser.getId();
                log.info("id:"+id);
                List<DmRoomDevice> roomDevice = dmRoomDeviceService.findByCode(Remark1,null);
                if(!ObjectUtils.isEmpty(roomDevice)){
                    List<Map<String,String>> map = dmAccessTrafficService.queryByRoomDevice(id,Remark1,EventTime);
                    if(ObjectUtils.isEmpty(map)){
                        DmAccessTraffic dmAccessTraffic = new DmAccessTraffic();
                        dmAccessTraffic.setRoomDevice(roomDevice.get(0).getCode());
                        dmAccessTraffic.setCardNumber(CardID);
                        dmAccessTraffic.setUser(dmUser);
                        dmAccessTraffic.setAccessTime(new Timestamp(sdf2.parse(EventTime).getTime()));
                        DmAccessTraffic newDmAccessTraffic = dmAccessTrafficRepository.save(dmAccessTraffic);
                        String erpAttendanceApi = "http://10.21.104.230:8700/attendance-api/device/identify/callback";
                        //组装返回数据
                        JSONObject ertAttendanceJSON = new JSONObject();
                        ertAttendanceJSON.put("deviceKey", newDmAccessTraffic.getRoomDevice());
                        ertAttendanceJSON.put("personId", newDmAccessTraffic.getUser().getUserNumber());
                        ertAttendanceJSON.put("time", newDmAccessTraffic.getAccessTime());
                        ertAttendanceJSON.put("type", "face_0");
                        System.out.println("ertAttendanceJSON:" + ertAttendanceJSON);
                        String res = HttpRequest.get(erpAttendanceApi).body(ertAttendanceJSON.toJSONString()).execute().body();
                        System.out.println("res:" + res);
                    }
                }
            }
        }
    }

    public Connection getCon() {
        //数据库连接名称
        String username="root";
        //数据库连接密码
        String password="qwe123";
        String driver="net.sf.log4jdbc.sql.jdbcapi.DriverSpy";
        String url="jdbc:mysql://10.208.128.14:3306/qudao?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false";
        Connection conn=null;
        try{
            Class.forName(driver);
            conn=(Connection) DriverManager.getConnection(url,username,password);
        }catch(Exception e){
            e.printStackTrace();
        }
        return conn;
    }

    public JSONArray getSelect(String start, String end) throws ParseException {
        // sql语句
        String sql = "select * from adk_accesslog where DATE_FORMAT(EventTime,'%Y-%m-%d %H:%i:%s') between '"+start+"' and '"+end+"' and UserID!='' and UserID!='陌生人' order by EventTime ASC";
        // 获取到连接
        Connection conn = getCon();
        PreparedStatement pst = null;
        // 定义一个list用于接受数据库查询到的内容
        JSONArray array = new JSONArray();
        try {
            pst = (PreparedStatement) conn.prepareStatement(sql);
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                // 将查询出的内容添加到list中，其中userName为数据库中的字段名称
                JSONObject object = new JSONObject();
                object.put("ID",rs.getString("ID")); //自增序号
                object.put("UserID",rs.getString("UserID")); //刷卡或刷脸人员ID
                object.put("CardID",rs.getString("CardID")); //卡号
                object.put("EventTime",rs.getString("EventTime")); //出入时间
                object.put("Remark1",rs.getString("Remark1")); //设备序列号
                array.add(object);
            }
        } catch (Exception e) {
        }
        return array;
    }


    public void synchronizationDevicesList(){

        /**
         * 获取全部未离职的用户
         */
         List<Map<String,Object>> maps = userRepository.findAllByEnable(1,null);
//        List<Map<String,Object>> maps = new ArrayList<>();
//        Map<String,Object> temp = new HashMap<>();
//        temp.put("userID","100000030");
//        temp.put("persion_id","ffa3b057-bdb4-4237-9bc5-efe1559fc178");
//        maps.add(temp);
        /**
         * 遍历用户数据
         */
        maps.forEach(item->{
            /**
             * 对方不支持list查询 那么就一个一个查询
             */
            String res = HttpRequest.post(getDeviceUrl).form("user", JSONObject.toJSONString(item)).execute().body();
              dmUserRepository.delUserDevice(item.get("persion_id").toString(),null ,null,null);
//             String res = "{\n" +
//                     "    \"result\": 1,\n" +
//                     "    \"success\": true,\n" +
//                     "    \"msg\": \"success\",\n" +
//                     "    \"data\": {\n" +
//                     "        \"data\": [\n" +
//                     "            {\n" +
//                     "                \"deviceID\": \"219201773\",\n" +
//                     "                \"deviceStatus\": \"1\",\n" +
//                     "                \"doorID\": 1,\n" +
//                     "                \"doorName\": \"门点1\"\n" +
//                     "            },\n" +
//                     "            {\n" +
//                     "                \"deviceID\": \"219201773\",\n" +
//                     "                \"deviceStatus\": \"1\",\n" +
//                     "                \"doorID\": 2,\n" +
//                     "                \"doorName\": \"门点2\"\n" +
//                     "            },\n" +
//                     "            {\n" +
//                     "                \"deviceID\": \"219201801\",\n" +
//                     "                \"deviceStatus\": \"1\",\n" +
//                     "                \"doorID\": 1,\n" +
//                     "                \"doorName\": \"门点1\"\n" +
//                     "            }\n" +
//                     "        ]\n" +
//                     "    }\n" +
//                     "}";
            //将返回结果
             JSONObject jsonObject = JSONObject.parseObject(res);
            log.info("单个用户权限设备：{}",jsonObject.toJSONString());
            //判断返回结果是否是正常的并且是成功的
             if (null != jsonObject.get("result") && "1".equals(jsonObject.get("result").toString()) && null != jsonObject.get("data")){
                     //将返回的结果data 转换为list<JSONObject>对象
                  JSONObject data = JSONObject.parseObject(jsonObject.get("data").toString());
                  JSONArray jsonObjectList = JSONObject.parseArray(data.getString("data"));
                 log.info("用户全部权限设备对象：{}",jsonObjectList.toString());
                     //遍历 用户权限设备JSON对象
                     jsonObjectList.forEach(device->{
                          JSONObject jsonObject1 = JSONObject.parseObject(device.toString());
                         //向param列表中添加
                         JSONObject param = new JSONObject();
                         param.put("deviceId",jsonObject1.get("deviceID").toString());
                         param.put("doorId",jsonObject1.get("doorID").toString());
                         //根据设备id和门禁id查询设备
                         List<DmRoomDevice> deviceID = roomDeviceRepository.findByCode(jsonObject1.get("deviceID").toString(), jsonObject1.get("doorID").toString());
                            log.info("用户设备信息：{}",deviceID);

                             for (int i = 0; i < deviceID.size(); i++) {
                                 deviceID.get(i).setDoorName(jsonObject1.get("doorName").toString());
                                 deviceID.get(i).setStatus("0"+(jsonObject1.get("deviceStatus").toString().equals("1")?"0":"1"));
                                 //修改设备名称和状态
                                 roomDeviceRepository.save(deviceID.get(i));
                                 //向user设备中间表加入数据  根据用户id和设备id和门禁id查询  如果有则新增 没有则不新增
                                  if (dmUserRepository.createUserDeviceBySelect(item.get("persion_id").toString(),jsonObject1.get("deviceID").toString(),jsonObject1.get("doorID").toString(),deviceID.get(i).getId().toString())>0){
                                      log.info("新增成功：{}",deviceID);
                                  }
                             }
                     });
             }
        });

    }

}
