package com.template.services.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.template.common.utils.AesTestOne;
import com.template.common.utils.CommonUtil;
import com.template.common.utils.RequestUtils;
import com.template.common.utils.TimeExchange;
import com.template.model.pojo.SmartFaceDiscern;
import com.template.mapper.SmartFaceDiscernMapper;
import com.template.model.pojo.SmartUser;
import com.template.services.SmartFaceDiscernService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.template.services.SmartUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import static com.template.common.utils.AesTestOne.decrypt;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ceshi
 * @since 2024-01-18
 */
@Service
public class SmartFaceDiscernServiceImpl extends ServiceImpl<SmartFaceDiscernMapper, SmartFaceDiscern> implements SmartFaceDiscernService {
    @Autowired
    SmartUserService smartUserService;


    //    static String appid = "sc5efc60f2bd373df9";
    static String appid = "sc1eb792c1ea3237e9";
    //    static String appSecret = "fe0d767a2a394d1b81ccda6fc0ce5ecc";
    static String appSecret = "61afd794ed3244e995c5e894e5788193";
    //    static String schoolCode = "SL1701743624375793";
    static String schoolCode = "SL1704880825203963";

    private Integer page = 1;
    private Integer size = 20;

//    @Scheduled(cron = "0 0/30 * * * ? ")
    public void baiS()  {
        try {
            getFaceDiscern(page, size);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


    public void getFaceDiscern(Integer pageindex, Integer pagesize) throws Exception {
//        String url = "http://schoolopenapi.szymzh.com/openapi/record/searchrecord";
        String url = "https://schoolopenapi.ymiot.net/openapi/record/searchrecord";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("appid", appid);
        String timestamp = TimeExchange.DateNowTimeStamo();
        jsonObject.put("timestamp", timestamp);
        jsonObject.put("schoolno", schoolCode);
        JSONObject data = new JSONObject();
        data.put("pageindex", pageindex + "");
        data.put("pagesize", pagesize + "");

//        时间
        DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime stateTime = now.withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endTime = now.withHour(23).withMinute(59).withSecond(59);
//        开始时间
        data.put("record_begintime", stateTime.format(dateTimeFormatter1));
//        结束时间
        data.put("record_endtime", endTime.format(dateTimeFormatter1));


        String dataString = data.toJSONString();
        System.out.println(dataString);
//        加密
        String aesStr = URLEncoder.encode(AesTestOne.encrypt(dataString, appSecret), "UTF-8");

        jsonObject.put("data", aesStr);

        String stringA = "appid=" + appid + "&data=" + dataString + "&schoolno=" + schoolCode + "&timestamp=" + timestamp + "&key=" + appSecret;

        String sign = CommonUtil.MD5(stringA);

        jsonObject.put("sign", sign);

        String s = RequestUtils.httpPost(url, jsonObject.toJSONString());
        JSONObject jsonObject1 = JSONObject.parseObject(s);
        String data1 = jsonObject1.getString("data");
        // URL解码
        String decodedUrl = URLDecoder.decode(data1, "UTF-8");

        String decrypt = decrypt(decodedUrl, appSecret);
        System.out.println("decrypt = " + decrypt);
        if (ObjectUtils.isNotEmpty(decrypt)) {
            JSONObject jsonObject2 = JSONObject.parseObject(decrypt);
//            获取总数
            Integer total = Integer.valueOf(jsonObject2.getString("total"));

            if (total > pageindex * pagesize) {
                page = pageindex + 1;
            } else {
                page = pageindex - 1;
            }


            JSONArray data2 = jsonObject2.getJSONArray("data");
            for (int i = 0; i < data2.size(); i++) {
                JSONObject jsonObject3 = data2.getJSONObject(i);
                SmartFaceDiscern smartFaceDiscern = new SmartFaceDiscern();

//                事件
                String deviceName = jsonObject3.getString("device_name");
                smartFaceDiscern.setType(deviceName);

//                地点
                String deviceArea = jsonObject3.getString("device_area");
                smartFaceDiscern.setLocation(deviceArea);

//                图片
                String recordPhoto = jsonObject3.getString("record_photo");
                smartFaceDiscern.setImage(recordPhoto);

//                时间
                String recordAddtime = jsonObject3.getString("record_addtime");
                smartFaceDiscern.setDateTime(recordAddtime);

//                名字
                String student_name = jsonObject3.getString("student_name");
                smartFaceDiscern.setName(student_name);
//                 学号
                String student_number = jsonObject3.getString("student_number");
//                编号
                String student_no = jsonObject3.getString("student_no");

                LambdaQueryWrapper<SmartUser> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SmartUser::getBsStudentNo, student_no);
                wrapper.eq(SmartUser::getName, student_name);
                SmartUser smartUser = smartUserService.getOne(wrapper);

                if (ObjectUtils.isNotEmpty(smartUser)) {
                    smartFaceDiscern.setUserId(smartUser.getId());

//                    判断是否已经添加
                    LambdaQueryWrapper<SmartFaceDiscern> wrapperFD = new LambdaQueryWrapper<>();
                    wrapperFD.eq(SmartFaceDiscern::getDateTime, recordAddtime)
                            .eq(SmartFaceDiscern::getId, smartUser.getId());
                    SmartFaceDiscern one = this.getOne(wrapperFD);

                    if (ObjectUtils.isEmpty(one)) {
                        this.save(smartFaceDiscern);
                    }


                }

            }

        }
    }

    @Override
    public List<SmartFaceDiscern> track(String stateTime, String endTime, Integer id) {

        LambdaQueryWrapper<SmartFaceDiscern> wrapper=new LambdaQueryWrapper<>();
        wrapper.between(SmartFaceDiscern::getDateTime,stateTime,endTime)
                .eq(SmartFaceDiscern::getUserId,id)
                .orderByDesc(SmartFaceDiscern::getDateTime);

        List<SmartFaceDiscern> list = this.list(wrapper);

        return list;
    }
}
