package com.ruoyi.business.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.business.domain.FileExchangePackage;
import com.ruoyi.business.domain.FileExchangePackageLog;
import com.ruoyi.business.service.IDatabaseService;
import com.ruoyi.business.service.IFileExchangePackageLogService;
import com.ruoyi.business.service.IFileExchangePackageService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.annotation.InnerAuth;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ruoyi.common.core.utils.Arith.randomNum;
import static com.ruoyi.common.core.utils.file.ZipUtils.jsonZip;
import static com.ruoyi.common.core.web.domain.AjaxResult.success;

@Slf4j
@Validated
@RestController
@RequestMapping("/package")
@RequiredArgsConstructor
public class PackageController {
    private final IFileExchangePackageService fileExchangePackageService;
    private final IFileExchangePackageLogService fileExchangePackageLogService;
    private final IDatabaseService databaseService;

    @InnerAuth
    @GetMapping
    public AjaxResult filePackage(@RequestParam("exchangePackageId") Long id) throws SQLException, ClassNotFoundException {
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        DateTimeFormatter dfClock = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        FileExchangePackage exchangePackage = fileExchangePackageService.selectFileExchangePackageById(id);
        String sqlStr = "select * from " + exchangePackage.getPackageSourceTable() + " where id > ? and delete_flag = '0' order by id limit " + exchangePackage.getPackageNumLimit();
        Connection conn = databaseService.getConnection(exchangePackage.getPackageSourceDbId(), null);
        PreparedStatement st = conn.prepareStatement(sqlStr);
        if(ObjectUtils.isEmpty(exchangePackage.getCurrId())) {
            st.setObject(1, 0);
        } else {
            st.setObject(1, exchangePackage.getCurrId());
        }
        ResultSet rs = st.executeQuery();
        List<Map<String, Object>> list = new ArrayList<>();

        while (rs.next()) {
            int columnCount = rs.getMetaData().getColumnCount();
            Map<String, Object> rowData = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = rs.getMetaData().getColumnLabel(i);
                if (columnName != null && !columnName.isEmpty()) {
                    Object value = rs.getObject(i);
                    if(value instanceof LocalDateTime) {
                        LocalDateTime timeTmp = (LocalDateTime) value;
                        value = timeTmp.format(dfClock);
                    }
                    rowData.put(columnName, value);
                }
            }
            list.add(rowData);
        }

        if(list.isEmpty()) {
            return success("打包数据为空");
        }

        String password = randomNum(6);
        String zipName = exchangePackage.getPackageSourceTableName() + "_" + LocalDateTime.now().format(df) + ".zip";
        String zipFullName = exchangePackage.getFilePosition() + File.separator + zipName;
        jsonZip(list, exchangePackage.getPackageSourceTableName() +".json", zipFullName, password);
        FileExchangePackageLog exchangePackageLog = new FileExchangePackageLog();
        exchangePackageLog.setParentId(exchangePackage.getId());
        exchangePackageLog.setInterfaceName(exchangePackage.getInterfaceName());
        exchangePackageLog.setInterfaceUrl(exchangePackage.getInterfaceUrl());
        exchangePackageLog.setPackageIdRange(list.get(0).get("id") + "," + list.get(list.size() - 1).get("id"));
        exchangePackageLog.setPackageDataNum(list.size());
        exchangePackageLog.setPackageSourceDbId(exchangePackage.getPackageSourceDbId());
        exchangePackageLog.setPackageSourceDbName(exchangePackage.getPackageSourceDbName());
        exchangePackageLog.setPackageSourceTable(exchangePackage.getPackageSourceTable());
        exchangePackageLog.setPackageSourceTableName(exchangePackage.getPackageSourceTableName());
        exchangePackageLog.setFilePosition(exchangePackage.getFilePosition());
        exchangePackageLog.setPackageFileName(zipName);
        exchangePackageLog.setFileSecret(password);
        fileExchangePackageLogService.save(exchangePackageLog);
        //设置当前打包完成主键
        LambdaUpdateWrapper<FileExchangePackage> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(FileExchangePackage::getCurrId, list.get(list.size() - 1).get("id"));
        fileExchangePackageService.update(updateWrapper);
        return success();
    }
}
