package com.malk.zhuogao.controller;

import com.alibaba.fastjson.JSON;
import com.malk.server.common.McException;
import com.malk.server.common.McR;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Dedicated;
import com.malk.utils.UtilDateTime;
import com.malk.utils.UtilExcel;
import com.malk.utils.UtilMap;
import com.malk.utils.UtilString;
import com.malk.zhuogao.repository.dao.TrustDeviceDao;
import com.malk.zhuogao.repository.entity.TrustDevicePo;
import com.malk.zhuogao.repository.entity.ZSDFileRecordPo;
import com.malk.zhuogao.service.ZSDClient_File;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 错误抛出与拦截详见 CatchException
 */
@Slf4j
@RestController
@RequestMapping
public class ZGController {

    @Autowired
    private DDClient ddClient;

    @Autowired
    private DDClient_Dedicated ddClient_orgapp;

    @Autowired
    private ZSDClient_File zsdFileClient;


    /**
     * 查询文件操作记录
     */
    @SneakyThrows
    @PostMapping("records/query")
    McR queryRecords(@RequestBody Map data) {

        McException.assertParamException_Null(data, "pageIndex", "pageSize");
        return McR.success(zsdFileClient.queryRecords(data, UtilMap.getInt(data, "pageIndex"), UtilMap.getInt(data, "pageSize")));
    }

    /**
     * 导出审计操作记录
     */
    @PostMapping("records/export")
    public void exportRecords(HttpServletResponse response, @RequestBody Map param) {

        log.info("导出审计操作记录 入参, {}", param);

        Page page = zsdFileClient.queryRecords(param, 1, 1);
        McException.assertAccessException(page.getTotalElements() > 100000L, "单次导出不能超过10万条数据!");

        List<ZSDFileRecordPo> dataList = zsdFileClient.queryRecords(param, 1, Integer.MAX_VALUE).getContent();
        List<String> columnHeader = Arrays.asList("员工姓名", "操作终端", "操作类型", "操作来源", "知识库名称", "知识库链接", "操作时间", "接收方名称", "接收方类型", "文件名称", "文件类型", "文件大小", "文件所属组织");
        List<String> columnProp = Arrays.asList("realName", "platformView", "actionView", "operateModuleView", "workSpaceName", "link", "gmtCreateTime", "receiverName", "receiverTypeView", "resource", "resourceExtension", "resourceSizeToM", "orgName");

        log.info("导出审计操作记录 数量, {}", dataList.size());
        UtilExcel.builder().heardList(columnHeader.toArray(new String[0])).heardKey(columnProp.toArray(new String[0]))
                .data(JSON.parseArray(JSON.toJSONString(dataList), Map.class)).fileName("审计操作记录").build()
                .exportExcelByPoi(response);
    }

    /////// test ///////

    /**
     * 同步记录
     */
    @PostMapping("sync")
    McR sync(@RequestParam String startDate, String endDate) {
        long startTime = UtilDateTime.parseDateTime(startDate + " 00:00:00").getTime();
        long endTime = UtilDateTime.parseDateTime(endDate + " 23:59:59").getTime();

        int pageSize = 500;
        zsdFileClient.syncFileRecords(startTime, endTime, pageSize, null);
        return McR.success();
    }

    /**
     * 同步记录: 失败续传
     */
    @PostMapping("sync-bc")
    McR sync_bc() {

        long startTime = 1688953500001L;
        long endTime = 1688954400001L;

        int pageSize = 500;
        Map last = UtilMap.map("gmtCreate, bizId", 1688954399589L, 109794444265L);
        zsdFileClient.syncFileRecords(startTime, endTime, pageSize, last);
        return McR.success();
    }

    /**
     * test
     */
    @PostMapping("test")
    McR test(@RequestBody Map data) {
        McException.assertParamException_Null(data, "startTime", "endTime", "pageSize");
        log.info("查询文件审计, {}", data);
//        long startTime = new Date().getTime() - 7 * 24 * 60 * 60 * 1000L;
//        long endTime = new Date().getTime();
//        int pageSize = 500;
        long startTime = UtilMap.getLong(data, "startTime");
        long endTime = UtilMap.getLong(data, "endTime");
        int pageSize = UtilMap.getInt(data, "pageSize");
        Map preLastRecord = (Map) data.get("preLastRecord");
        List<Map> records = ddClient_orgapp.obtainFileOperationRecords(ddClient.getAccessToken(), startTime, endTime, pageSize, preLastRecord).stream().map(item -> {
            item.put("resourceName", UtilMap.getString(item, "resource") + "." + UtilMap.getString(item, "resourceExtension"));
            if (item.containsKey("resourceSize")) {
                item.put("resourceSizeToM", UtilString.stringFormatFixed((UtilMap.getLong(item, "resourceSize") / 1024F / 1024L)) + "M");
            }
            return item;
        }).collect(Collectors.toList());

        log.info("响应文件审计, {}", records.size());

        return McR.success(records);
    }

    @Autowired
    private TrustDeviceDao trustDeviceDao;

    /// 可信设备, 需要启停账号, 重新登录才会生效, 客户需要立即生效因此通过接口操作
    @PostMapping("device")
    McR device() {

        List<TrustDevicePo> dataList = trustDeviceDao.findAll();
        for (TrustDevicePo po : dataList) {
//            ddClient_orgapp.orgAccountsDisable(ddClient.getAccessToken(), po.getUserId());
            ddClient_orgapp.orgAccountsEnable(ddClient.getAccessToken(), po.getUserId());
        }
        return McR.success(dataList);

    }
}
