package com.yeejoin.amos.api.householdapi.face.service.impl;

import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.yeejoin.amos.api.householdapi.face.orm.houseapi.entity.houseapi.HYGFThirdStationLog;
import com.yeejoin.amos.api.householdapi.face.orm.mapper.houseapi.HYGFThirdStationLogMapper;
import com.yeejoin.amos.api.householdapi.face.service.IHYGFThirdStationLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

@Service
@Slf4j
public class HYGFThirdStationLogServiceImpl implements IHYGFThirdStationLogService {
    private final String TABLE_NAME = "hygf_third_station_log";
    @Autowired
    private HYGFThirdStationLogMapper hygfThirdStationLogMapper;
    @Value("${hygf.third.station.log.reserve.day:7}")
    private Integer reserveDay;

    @Override
    public  void saveLog(HYGFThirdStationLog hygfThirdStationLog) {
        try {
            // 获取今天的表名
            String tableName = TABLE_NAME + "_" + getCurrentDate();
            // 校验并创建新表
            checkAndCreateNewTable(tableName);
            //插入数据
            insertLogData(tableName,hygfThirdStationLog);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }

    private  void insertLogData(String tableName,HYGFThirdStationLog hygfThirdStationLog) {
        if (Objects.nonNull(hygfThirdStationLog)) {
            hygfThirdStationLog.setId(UUID.randomUUID().toString());
            hygfThirdStationLog.setReqTime(new Date());
            hygfThirdStationLogMapper.insertData(tableName, hygfThirdStationLog);
        }
    }

    private void checkAndCreateNewTable(String tableName) {
        // 查询当前表的数量
        Integer countTable = hygfThirdStationLogMapper.countTable(TABLE_NAME + "%");

        // 如果表超过7个，删除最旧的表
        if (countTable > reserveDay) {
            String oldestTableName = hygfThirdStationLogMapper.getOldestTableName(TABLE_NAME + "%");
            hygfThirdStationLogMapper.dropTable(oldestTableName);
        }

        // 创建新表
        hygfThirdStationLogMapper.createTable(tableName);
    }

    // 获取当前日期（格式为 yyyyMMdd）
    private String getCurrentDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        return sdf.format(new Date());
    }
}
