package com.sooka.sponest.monitor.dahua.controller;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.system.api.domain.SysDept;
import com.sooka.sponest.monitor.dahua.domain.CenternonitorTDahuaOperateLog;
import com.sooka.sponest.monitor.dahua.domain.CenternonitorTDahuaOperateLogUrl;
import com.sooka.sponest.monitor.dahua.mapper.CenternonitorTDahuaOperateLogUrlMapper;
import com.sooka.sponest.monitor.dahua.service.ICenternonitorTDahuaOperateLogService;
import com.sooka.sponest.monitor.dahua.utils.HttpTestUtils;
import com.sooka.sponest.monitor.remoteapi.service.center.system.RemoteService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 对接大华云台日志定时任务Controller
 *
 * "12": "视频",
 * "13": "云台控制",
 *
 * @author ruoyi
 * @date 2023-12-09
 */
@Slf4j
@Component
@RestController
@RequestMapping("/dahuaWhiteOperateLog")
public class DahuaOperateLogWhiteTask {

    @Resource
    private ICenternonitorTDahuaOperateLogService centernonitorTDahuaOperateLogService;
    @Resource
    private CenternonitorTDahuaOperateLogUrlMapper centernonitorTDahuaOperateLogUrlMapper;
    @Resource
    private RemoteService remoteService;
    private final List<String> operateTypeWhiteList = Arrays.asList("12", "13");


    @Value("${sooka.dahua_interface_server.loginIp}")
    private String loginIp;
    @Value("${sooka.dahua_interface_server.loginPort}")
    private String loginPort;
    @Value("${sooka.dahua_interface_server.userName}")
    private String userName;
    @Value("${sooka.dahua_interface_server.userPwd}")
    private String userPwd;
    private final String url = "/SlsService/opreationlog/list";
//    private String loginIp = "10.53.0.35";
//    private String loginPort = "7901";
//    private String userName = "system";
//    private String userPwd = "Admin123";


//    @Scheduled(cron = "0 0/1 * * * ?")
//    @Log(title = "对接大华云台日志定时任务", businessType = BusinessType.OTHER)
    @ApiOperation(value = "对接大华云台日志定时任务", notes = "对接大华云台日志定时任务")
    @RequestMapping(value = "configureWhiteTasks", method = POST)
    public void configureWhiteTasks() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
        Calendar calendar = Calendar.getInstance();
        Date now = new Date();
        //设置入参开始时间
        calendar.setTime(now);
        // 获取当前时间前一天的日期
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        // 设置时间为16:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 16);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startTime = calendar.getTime();
        //获取当前时间的15:59:59
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date endTime = calendar.getTime();

        try {
            R<?> result = HttpTestUtils.getToken(loginIp, Integer.parseInt(loginPort), userName, userPwd);
            if (result.getCode() != 200) {
                log.error("调用获取token接口报错：{}", result);
            }
            String token = result.getData().toString();
            extractedWhite(token, sdf.format(startTime), sdf.format(endTime), null);
        } catch (Exception e) {
            log.error("configureWhiteTasks background error：", e);
        }
    }

    public void extractedWhite(String token, String startTime, String endTime, String operateTypeValue) throws Exception {
        //取消证书认证
        SSLContext sslContext = SSLContextBuilder.create()
                .loadTrustMaterial(new TrustSelfSignedStrategy())
                .build();
        HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
        HttpClient httpClient = HttpClients.custom()
                .setSSLContext(sslContext)
                .setSSLHostnameVerifier(hostnameVerifier)
                .setRedirectStrategy(new LaxRedirectStrategy())
                .build();
        long startTimeDate = System.currentTimeMillis();
        //3.调用操作日志查询接口
        String proto = loginPort.equals("8320") ? "https://" : "http://";
        HttpPost httpPost = new HttpPost(proto + loginIp + ":" + loginPort + url);
        httpPost.setHeader("X-Subject-Token", token);
        httpPost.setHeader("content-type", "application/json");
        if (StringUtils.isNotEmpty(operateTypeValue)) {
            extracted(startTime, endTime, operateTypeValue, httpPost, httpClient);
        } else {
            for (String str : operateTypeWhiteList) {
                extracted(startTime, endTime, str, httpPost, httpClient);
            }
        }
    }

    private void extracted(String startTime, String endTime, String str, HttpPost httpPost, HttpClient httpClient) throws Exception {
        //第三次请求入参入参
        Integer pageNo = 1;
        Integer nextPage = 1;
        for (int i = 1; i <= pageNo; i++) {
            if (nextPage > 0) {
                //循环赋值第几页
                String requestBody = "{\n" +
                        "\t\"condition\": {\n" +
                        "\t\t\"startTime\": \"" + startTime + "\",\n" +
                        "\t\t\"endTime\": \"" + endTime + "\",\n" +
                        "\t\t\"type\": 2,\n" +
                        "\t\t\"operateNames\": [],\n" +
                        "\t\t\"operateType\": \"" + str + "\",\n" +
                        "\t\t\"deptCode\": \"\",\n" +
                        "\t\t\"userName\": \"\",\n" +
                        "\t\t\"address\": \"\",\n" +
                        "\t\t\"eventDetail\": \"\"\n" +
                        "\t},\n" +
                        "\t\"order\": [\n" +
                        "\t\t{\n" +
                        "\t\t\t\"orderBy\": \"operateTime\",\n" +
                        "\t\t\t\"order\": \"desc\"\n" +
                        "\t\t}\n" +
                        "\t],\n" +
                        "\t\"page\": \"" + i + "\",\n" +
                        "\t\"pageSize\": 512\n" +
                        "}";
                StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
                httpPost.setEntity(requestEntity);
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    List<CenternonitorTDahuaOperateLogUrl> centernonitorTDahuaOperateLogUrlList = new ArrayList<>();
                    String responseBody = EntityUtils.toString(responseEntity);
                    JSONObject jsonObject = JSONObject.parseObject(responseBody);
                    if (ObjectUtils.isNotEmpty(jsonObject.get("code")) && jsonObject.get("code").toString().equals("402")) {
                        //如果token过期重新走业务逻辑
                        getTokenWhite();
                    } else {
                        pageNo = (Integer) jsonObject.get("totalCount") / 512 + 1;
                        nextPage = (Integer) jsonObject.get("nextPage");
                        List<CenternonitorTDahuaOperateLog> list = JSONObject.parseArray(jsonObject.get("results").toString(), CenternonitorTDahuaOperateLog.class);
                        if (CollectionUtils.isNotEmpty(list)) {
                            for (CenternonitorTDahuaOperateLog item : list) {
                                R<SysDept> result = remoteService.findDeptIdByUserName(item.getUserName());
                                if (result.getCode() == 200 && result.getData() != null) {
                                    item.setDeptId(result.getData().getDeptId());
                                    item.setDeptName(result.getData().getDeptName());
                                    item.setAncestors(result.getData().getAncestors());
                                    item.setParentId(result.getData().getParentId());
                                }
                            }
                            int count = centernonitorTDahuaOperateLogService.insertBatch(list);
                            list.stream().forEach(item -> {
                                if (CollectionUtils.isNotEmpty(item.getUrl())) {
                                    item.getUrl().stream().forEach(var -> {
                                        CenternonitorTDahuaOperateLogUrl centernonitorTDahuaOperateLogUrl = new CenternonitorTDahuaOperateLogUrl();
                                        centernonitorTDahuaOperateLogUrl.setOperateId(item.getId());
                                        centernonitorTDahuaOperateLogUrl.setUrl(var);
                                        centernonitorTDahuaOperateLogUrlList.add(centernonitorTDahuaOperateLogUrl);
                                    });
                                }
                            });
                            if (CollectionUtils.isNotEmpty(centernonitorTDahuaOperateLogUrlList)) {
                                centernonitorTDahuaOperateLogUrlMapper.insertBatch(centernonitorTDahuaOperateLogUrlList);
                            }
                        }
                    }
                }
            }
        }
    }


    public R<?> getTokenWhite() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
        Calendar calendar = Calendar.getInstance();
        Date now = new Date();
        //设置入参开始时间
        calendar.setTime(now);
        // 获取当前时间前一天的日期
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        // 设置时间为16:00:00
        calendar.set(Calendar.HOUR_OF_DAY, 16);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date startTime = calendar.getTime();
        //获取当前时间的15:59:59
        calendar.setTime(now);
        calendar.set(Calendar.HOUR_OF_DAY, 15);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        Date endTime = calendar.getTime();

        try {
            R<?> result = HttpTestUtils.getToken(loginIp, Integer.parseInt(loginPort), userName, userPwd);
            if (result.getCode() != 200) {
                return R.fail(result.getMsg());
            }
            String token = result.getData().toString();
            extractedWhite(token, sdf.format(startTime), sdf.format(endTime), null);
            return R.ok();
        } catch (Exception e) {
            return R.fail("调用操作日志接口报错");
        }
    }


}


