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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.vctgo.common.core.text.Convert;
import com.vctgo.common.core.utils.ServletUtils;
import com.vctgo.common.core.web.domain.AjaxResult;
import com.vctgo.common.mybatisplus.constant.MybatisPageConstants;
import com.vote.system.domain.VoteFormTemplates;
import com.vote.system.domain.VoteRegistrationForms;
import com.vote.system.domain.VoteSubmissionForm;
import com.vote.system.mapper.VoteFormTemplatesMapper;
import com.vote.system.service.VoteRegistrationFormsService;
import com.vote.system.mapper.VoteRegistrationFormsMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.vote.system.util.ConstantUtils.IS_DELETED_0;

/**
 * @author MacBook
 * @description 针对表【vote_registration_forms(报名表单表)】的数据库操作Service实现
 * @createDate 2024-08-09 16:50:33
 */
@Service
@GlobalTransactional
public class VoteRegistrationFormsServiceImpl extends ServiceImpl<VoteRegistrationFormsMapper, VoteRegistrationForms>
        implements VoteRegistrationFormsService {

    @Autowired
    private VoteRegistrationFormsMapper voteRegistrationFormsMapper;


    @Autowired
    private VoteFormTemplatesMapper voteFormTemplatesMapper;


    /**
     * 分页
     *
     * @param voteRegistrationForms
     * @return
     */
    @Override
    public IPage<VoteRegistrationForms> selectPage(VoteRegistrationForms voteRegistrationForms) {
        // 提取并转换分页参数
        long pageNum = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_NUM), 1L);
        long pageSize = Convert.toLong(ServletUtils.getParameterToInt(MybatisPageConstants.PAGE_SIZE), 10L);

        Page<VoteRegistrationForms> mpPage = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<VoteRegistrationForms> wrapper = new LambdaQueryWrapper<>();

        // 关键字检查
        String keyword = voteRegistrationForms.getKeyword();
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like(VoteRegistrationForms::getFormName, keyword.trim());
        }
//        wrapper.eq(VoteRegistrationForms::getIsDeleted, IS_DELETED_0);
        wrapper.orderByDesc(VoteRegistrationForms::getUpdatedAt);
        // 使用流API处理内容项数量
        List<VoteRegistrationForms> forms = voteRegistrationFormsMapper.selectList(wrapper);
        forms.forEach(item -> item.setCount(countJsonObjects(item.getFormData())));
        mpPage.setRecords(forms);
        return mpPage;
    }

    /**
     * 保存报名表单
     *
     * @param voteRegistrationForms
     * @return
     */
    @Override
    public int saveRegistrationForms(VoteRegistrationForms voteRegistrationForms) {
        //数据校验
        if (voteRegistrationForms.getFormName().isEmpty()) {
            throw new NullPointerException("formName 不允许为空");
        }
        extracted(voteRegistrationForms);//检查是否存在该表单名称
        return voteRegistrationFormsMapper.insert(voteRegistrationForms);

    }

    /**
     * 查询全部内容项
     *
     * @return
     */
    @Override
    public List<VoteFormTemplates> queryByFormTemplates() {
        LambdaQueryWrapper<VoteFormTemplates> wrapper = new LambdaQueryWrapper<>();
        return voteFormTemplatesMapper.selectList(wrapper);
    }


    /**
     * 删除
     *
     * @return
     */
    @Override
    public int deleteById(Long id) {
        return voteRegistrationFormsMapper.deleteById(id);
    }

    @Override
    public int editVoteRegistrationForms(VoteRegistrationForms voteRegistrationForms) {
        extracted(voteRegistrationForms);
        return voteRegistrationFormsMapper.updateById(voteRegistrationForms);
    }

    /**
     * 获取JSON对象的个数
     *
     * @param formData JSON对象
     * @return 个数
     */
    public int countJsonObjects(String formData) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode rootNode = objectMapper.readTree(formData);
            if (rootNode.isObject()) {
                return 1;  // 根节点本身就是一个对象
            } else if (rootNode.isArray()) {
                int objectCount = 0;
                for (JsonNode node : rootNode) {
                    if (node.isObject()) {
                        objectCount++;
                    }
                }
                return objectCount;
            } else {
                return 0;  // 根节点既不是对象也不是数组
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("json解析失败", e);
        }
    }


    private void extracted(VoteRegistrationForms voteRegistrationForms) {
        // 获取当前表单
        VoteRegistrationForms existingForm = voteRegistrationFormsMapper.selectById(voteRegistrationForms.getId());

        // 如果表单名称未修改，不需要进一步校验
        if (existingForm != null) {
            if (existingForm.getFormName().equals(voteRegistrationForms.getFormName())) {
                return;
            }
        }

        // 判断新的表单名称是否存在
        LambdaQueryWrapper<VoteRegistrationForms> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteRegistrationForms::getFormName, voteRegistrationForms.getFormName());

        List<VoteRegistrationForms> registrationForms = voteRegistrationFormsMapper.selectList(wrapper);
        if (!registrationForms.isEmpty()) {
            throw new RuntimeException("存在重复报名表单，修改失败");
        }
    }

}




