package com.vote.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vote.system.domain.VoteFormTemplates;
import com.vote.system.domain.dto.VoteFormTemplatesDto;
import com.vote.system.mapper.VoteRegistrationFormsMapper;
import com.vote.system.service.VoteFormTemplatesService;
import com.vote.system.mapper.VoteFormTemplatesMapper;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Comparator;
import java.util.List;

import static com.vote.system.domain.dto.VoteFormTemplatesDto.ifDelete;
import static com.vote.system.util.ConstantUtils.IS_DELETED_0;

/**
 * @author MacBook
 * @description 针对表【vote_form_templates(报名表表单模板)】的数据库操作Service实现
 * @createDate 2024-08-09 11:26:00
 */
@Service
public class VoteFormTemplatesServiceImpl extends ServiceImpl<VoteFormTemplatesMapper, VoteFormTemplates>
        implements VoteFormTemplatesService {

    @Autowired
    private VoteFormTemplatesMapper voteFormTemplatesMapper;

    @Autowired
    private DataSource dataSource;


    /**
     * 添加 报名表单内容项
     *
     * @param voteFormTemplates
     * @return
     */
    @Override
    @Transactional
    public int createVoteFormTemplates(VoteFormTemplates voteFormTemplates) {
        //校验
        if (voteFormTemplates.getFieldName().isEmpty()) {
            throw new NullPointerException("fieldName 不允许为空");
        }

        if (voteFormTemplates.getTemplateName().isEmpty()) {
            throw new NullPointerException("templateName 不允许为空");
        }
        LambdaQueryWrapper<VoteFormTemplates> wrapper = new LambdaQueryWrapper<>();
        List<VoteFormTemplates> templates = voteFormTemplatesMapper.selectList(wrapper);
        //判断表中是否有该字段
        templates.forEach(item -> {
            if (item.getTemplateName().equals(voteFormTemplates.getTemplateName())) {
                throw new RuntimeException("已存在该内容项，不可添加！");
            }
        });

        int insert = voteFormTemplatesMapper.insert(voteFormTemplates);
        try {
            Connection connection = dataSource.getConnection();
            DatabaseMetaData metaData = connection.getMetaData();
            boolean columnExists = false;//标识
            //检查字段是否在表中
            var r = metaData.getColumns(null, null, "vote_registrations", voteFormTemplates.getFieldName());
            if (r.next()) {
                columnExists = true;
            }
            if (!columnExists) {
                String sql = "ALTER TABLE vote_registrations ADD COLUMN " + voteFormTemplates.getFieldName() + " VARCHAR(255)";
                try (Connection connections = dataSource.getConnection();
                     Statement statement = connections.createStatement()) {
                    statement.executeUpdate(sql);
                } catch (SQLException e) {
                    // 处理 SQL 错误
                    e.printStackTrace();
                    throw new RuntimeException("SQL 执行失败: " + sql, e);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return insert;
    }

    /**
     * 分页查询
     *
     * @param voteFormTemplates
     * @return
     */
    @Override
    public IPage<VoteFormTemplates> selectPage(VoteFormTemplates voteFormTemplates) {
        Long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        Long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);

        Page<VoteFormTemplates> mpPage = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<VoteFormTemplates> wrapper = new LambdaQueryWrapper<>();

        if (voteFormTemplates.getKeyword() != null && !voteFormTemplates.getKeyword().isEmpty()) {
            wrapper.like(VoteFormTemplates::getTemplateName, voteFormTemplates.getKeyword());
        }
        wrapper.eq(VoteFormTemplates::getIsDeleted, IS_DELETED_0)
                .orderByDesc(VoteFormTemplates::getCreatedAt);
        Page<VoteFormTemplates> page = voteFormTemplatesMapper.selectPage(mpPage, wrapper);

        //排序
        List<VoteFormTemplates> list = page.getRecords();
        list.sort(Comparator.comparingInt(VoteFormTemplates::getSortOrder));
        page.setRecords(list);

        return page;
    }


    /**
     * 修改 表单项
     *
     * @param voteFormTemplates
     * @return
     */
    @Override
    @Transactional
    public int editVoteFormTemplates(VoteFormTemplates voteFormTemplates) {
        return voteFormTemplatesMapper.updateById(voteFormTemplates);
    }


    /**
     * 删除内容项
     *
     * @param voteFormTemplatesDto
     * @return
     */
    @Override
    @Transactional
    public int deleteById(VoteFormTemplatesDto voteFormTemplatesDto) {
        Integer status = voteFormTemplatesDto.getStatus();
        Long id = voteFormTemplatesDto.getId();
        VoteFormTemplates voteFormTemplates = voteFormTemplatesMapper.selectById(id);
        //檢查status是否为空
        if (status != null) {
            if (status.equals(ifDelete)) {
                deletrColumnTable("vote_registrations", voteFormTemplates.getFieldName());
            }
        }

        return voteFormTemplatesMapper.deleteById(id);
    }


    //删除表头字段逻辑方法
    private void deletrColumnTable(String tableName, String fieldName) {
        try (Connection connection = dataSource.getConnection()) {
            DatabaseMetaData metaData = connection.getMetaData();
            boolean columExists = false;

            //检查是否存在于表中
            ResultSet resultSet = metaData.getColumns(null, null, tableName, fieldName);
            if (resultSet.next()) {
                columExists = true;
            }

            //如果存在则删除
            if (columExists) {
                String sql = "ALTER TABLE " + tableName + " DROP COLUMN " + fieldName;
                System.out.println(sql);
                Statement statement = connection.createStatement();
                statement.executeUpdate(sql);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}




