package com.yunzhupaas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunzhupaas.base.Pagination;
import com.yunzhupaas.base.entity.SuperBaseEntity;
import com.yunzhupaas.base.service.DbLinkService;
import com.yunzhupaas.base.service.SuperServiceImpl;
import com.yunzhupaas.config.ConfigValueUtil;
import com.yunzhupaas.constant.GlobalConst;
import com.yunzhupaas.constant.MsgCode;
import com.yunzhupaas.database.model.entity.DbLinkEntity;
import com.yunzhupaas.database.util.ConnUtil;
import com.yunzhupaas.database.util.DataSourceUtil;
import com.yunzhupaas.database.util.DbTypeUtil;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.entity.BigDataEntity;
import com.yunzhupaas.exception.WorkFlowException;
import com.yunzhupaas.mapper.BigDataMapper;
import com.yunzhupaas.service.BigDataService;
import com.yunzhupaas.util.DateUtil;
import com.yunzhupaas.util.RandomUtil;
import com.yunzhupaas.util.StringUtil;
import com.yunzhupaas.util.UserProvider;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 大数据测试
 *
 * @author 云筑产品开发平台组
 * @version V3.1.0
 * @copyright 深圳市乐程软件有限公司
 * @date 2024-09-26 上午9:18
 */
@Slf4j
@Service
public class BigDataServiceImpl extends SuperServiceImpl<BigDataMapper, BigDataEntity> implements BigDataService {

    @Autowired
    private DataSourceUtil dataSourceUtils;
    @Autowired
    private ConfigValueUtil configValueUtil;
    @Autowired
    private DbLinkService dbLinkService;


    @Override
    public List<BigDataEntity> getList(Pagination pagination) {
        QueryWrapper<BigDataEntity> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(pagination.getKeyword())) {
            queryWrapper.lambda().and(
                    t -> t.like(BigDataEntity::getFullName, pagination.getKeyword())
                            .or().like(BigDataEntity::getEnCode, pagination.getKeyword())
            );
        }
        //排序
        queryWrapper.lambda().orderByDesc(SuperBaseEntity.SuperCBaseEntity::getCreatorTime, SuperBaseEntity.SuperIBaseEntity::getId);
        Page<BigDataEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<BigDataEntity> iPage = this.page(page, queryWrapper);
        return pagination.setData(iPage.getRecords(), page.getTotal());
    }

    @Override
    public void create(int insertCount) throws WorkFlowException {
        Integer code = this.baseMapper.maxCode();
        if (code == null) {
            code = 0;
        }
        int index = code == 0 ? 10000001 : code;
        if (index > 11500001) {
            throw new WorkFlowException(MsgCode.ETD113.get());
        }
        try {
            @Cleanup Connection conn = ConnUtil.getConnOrDefault(dataSourceUtils);
            @Cleanup PreparedStatement pstm = null;
            String sql = "";
            String tenantColumn = TenantDataSourceUtil.getTenantColumn();
            DbLinkEntity dbLinkEntity = dbLinkService.getResource("0");
            if (DbTypeUtil.checkOracle(dbLinkEntity)||DbTypeUtil.checkDM(dbLinkEntity)) {
                sql = "INSERT INTO ext_big_data(F_ID,F_EN_CODE,F_FULL_NAME,F_CREATOR_TIME{column})  VALUES (?,?,?,to_date(?,'yyyy-mm-dd hh24:mi:ss'){value})";
            } else {
                sql = "INSERT INTO ext_big_data(F_ID,F_EN_CODE,F_FULL_NAME,F_CREATOR_TIME{column})  VALUES (?,?,?,?{value})";
            }
            sql = sql.replaceAll("\\{column}", "," + configValueUtil.getMultiTenantColumn());
            sql = sql.replaceAll("\\{value}", ",?");
            pstm = conn.prepareStatement(sql);
            conn.setAutoCommit(false);
            if (DbTypeUtil.checkPostgre(dbLinkEntity)) {
                for (int i = 0; i < insertCount; i++) {
                    pstm.setString(1, RandomUtil.uuId());
                    pstm.setInt(2, index);
                    pstm.setString(3, "测试大数据" + index);
                    pstm.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
                    if (StringUtil.isNotEmpty(tenantColumn)) {
                        pstm.setString(5, tenantColumn);
                    }
                    pstm.addBatch();
                    index++;
                }
            } else {
                for (int i = 0; i < insertCount; i++) {
                    pstm.setString(1, RandomUtil.uuId());
                    pstm.setInt(2, index);
                    pstm.setString(3, "测试大数据" + index);
                    pstm.setString(4, DateUtil.getNow());
//                    pstm.setString(4, DateUtil.daFormatHHMMSSAddEight(System.currentTimeMillis()));
                    if (StringUtil.isNotEmpty(tenantColumn)) {
                        pstm.setString(5, tenantColumn);
                    }
                    pstm.addBatch();
                    index++;
                }
            }
            pstm.executeBatch();
            conn.commit();
            pstm.close();
            conn.close();
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }
}

