package com.template.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.template.annotation.DESRespondSecret;
import com.template.annotation.PassToken;
import com.template.api.SmartFaceDiscernTestControllerAPI;
import com.template.common.utils.Message2;
import com.template.common.utils.MultipartFileUtils;
import com.template.model.pojo.*;
import com.template.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2024-05-20
 */
@RestController
public class SmartFaceDiscernTestController implements SmartFaceDiscernTestControllerAPI {

    @Autowired
    SmartFaceDiscernTestService smartFaceDiscernTestService;

    @Autowired
    SmartUserService smartUserService;

    @Autowired
    SmartDeviceService smartDeviceService;

    @Autowired
    SmartUploadService smartUploadService;

    @Autowired
    SmartNotificationService smartNotificationService;

    @Override
    @PassToken
    @DESRespondSecret(validated = false)
    public String callBack(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());

//            比对结果
            Integer resultStatus = jsonObject.getInteger("resultStatus");
            if (1 == resultStatus) {
                //                比对时间
                String time = jsonObject.getString("time");
                //          设备sn
                String sn = jsonObject.getString("sn");
                SmartDevice smartDevice = smartDeviceService.getNum(sn);
                String address = "";
                String type = "";
                if (ObjectUtils.isNotEmpty(smartDevice)) {
                    //            地点
                    address = smartDevice.getAddress();
//            类型
                    type = smartDevice.getName();
                }

//            名字,学生会加班级[]
                String name = jsonObject.getString("name");
                System.out.println("name = " + name);
                String[] split = name.split("\\[");
                String s = split[0];
                System.out.println("s = " + s);
//            百胜门禁编号
                String idNum = jsonObject.getString("idNum");
                System.out.println("idNum = " + idNum);
                SmartUser smartUser = smartUserService.getBsStudentNo(idNum);
                Integer userId = 0;
                if (ObjectUtils.isNotEmpty(smartUser)) {
                    userId = smartUser.getId();
                } else {
                    userId = 0;
                }

//          抓拍的照片 base64字符串
                String scenePhoto = jsonObject.getString("scenePhoto");
                scenePhoto = "data:image/jpeg;base64," + scenePhoto;
//            base64转文件
                MultipartFile multipartFile = MultipartFileUtils.base64ToMultipartFile(scenePhoto);
//            上传到cos桶,并生成图片地址
                String image = smartUploadService.upload(new MultipartFile[]{multipartFile});


                SmartFaceDiscernTest smartFaceDiscernTest = new SmartFaceDiscernTest();
                smartFaceDiscernTest.setImage(image);
                smartFaceDiscernTest.setName(s);
                smartFaceDiscernTest.setLocation(address);
                smartFaceDiscernTest.setType(type);
                smartFaceDiscernTest.setUserId(userId);
                smartFaceDiscernTest.setDateTime(time);



                if (userId != 0) {
                    //                    判断是否已经添加
                    LambdaQueryWrapper<SmartFaceDiscernTest> wrapperFD = new LambdaQueryWrapper<>();
                    wrapperFD.eq(SmartFaceDiscernTest::getDateTime, time)
                            .eq(SmartFaceDiscernTest::getUserId, userId);
                    List<SmartFaceDiscernTest> list = smartFaceDiscernTestService.list(wrapperFD);
                    if (ObjectUtils.isEmpty(list) && list.size() == 0) {
                        smartFaceDiscernTestService.save(smartFaceDiscernTest);

//                        通过学生id找到关联的家长affiliate,并找到公众号,如果openid为空则不传
                        List<SmartUser> userList = smartUserService.getAffiliateList(userId);
                        if (ObjectUtils.isNotEmpty(userList) && userList.size() > 0) {

                            for (SmartUser user : userList) {
                                String gzhOpenId = user.getGzhOpenId();
                                if (ObjectUtils.isNotEmpty(gzhOpenId)) {
                                    String pushType = "";
                                    if (type.contains("进校")) {
                                        pushType = "进入大门";
                                    } else if (type.contains("出校")) {
                                        pushType = "离开大门";
                                    }
                                    DateTimeFormatter dateTimeFormatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                                    LocalDateTime date = LocalDateTime.now();
                                    String format = date.format(dateTimeFormatter1);
                                    //                    公众号信息推送
                                    Message2.send(gzhOpenId, pushType, address,format);

                                    SmartNotification smartNotification = new SmartNotification();
                                    smartNotification.setUserId(smartUser.getId());
                                    smartNotification.setUserName(smartUser.getName());
                                    smartNotification.setTypeName(pushType);
                                    smartNotification.setLocation(address);
                                    smartNotification.setImage(image);
                                    smartNotification.setDateTime(time);
                                    smartNotification.setType(2);

                                    smartNotificationService.save(smartNotification);

                                }

                            }
                        }
                    }
                }else {

                    smartFaceDiscernTest.setUserId(0);

//                    判断是否已经添加
                    LambdaQueryWrapper<SmartFaceDiscernTest> wrapperFD = new LambdaQueryWrapper<>();
                    wrapperFD.eq(SmartFaceDiscernTest::getDateTime, time)
                            .eq(SmartFaceDiscernTest::getName, s)
                            .eq(SmartFaceDiscernTest::getType, type);
                    List<SmartFaceDiscernTest> list = smartFaceDiscernTestService.list(wrapperFD);

                    if (ObjectUtils.isEmpty(list) && list.size() == 0) {
                        smartFaceDiscernTestService.save(smartFaceDiscernTest);
                    }

                }

            }

        } catch (
                Exception e) {
            e.printStackTrace();
            JSONObject r = new JSONObject();
            r.put("message", "Success");
            r.put("result", 0);
            return r.toJSONString();
        }

        JSONObject r = new JSONObject();
        r.put("message", "Success");
        r.put("result", 0);
        return r.toJSONString();
    }

    @Override
    @PassToken
    @DESRespondSecret(validated = false)
    public String heartBeatAlive(HttpServletRequest request, HttpServletResponse response) {
        try {
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
            StringBuilder responseStrBuilder = new StringBuilder();
            String inputStr;
            while ((inputStr = streamReader.readLine()) != null) {
                responseStrBuilder.append(inputStr);
            }
            JSONObject jsonObject = JSONObject.parseObject(responseStrBuilder.toString());
            System.out.println("jsonObject = " + jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject r = new JSONObject();
        r.put("message", "Success");
        r.put("result", 0);
        return r.toJSONString();
    }

}

