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.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.org.apache.bcel.internal.generic.NEW;
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.VoteDataStorage;
import com.vote.system.domain.VoteRule;
import com.vote.system.domain.VoteSubmissionForm;
import com.vote.system.mapper.VoteDataStorageMapper;
import com.vote.system.service.VoteSubmissionFormService;
import com.vote.system.mapper.VoteSubmissionFormMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;


/**
 * @author MacBook
 * @description 针对表【vote_submission_form(提交作品表单模板表)】的数据库操作Service实现
 * @createDate 2024-08-11 15:10:00
 */
@Service
public class VoteSubmissionFormServiceImpl extends ServiceImpl<VoteSubmissionFormMapper, VoteSubmissionForm>
        implements VoteSubmissionFormService {

    @Autowired
    private VoteSubmissionFormMapper voteSubmissionFormMapper;


    @Autowired
    private VoteDataStorageMapper voteDataStorageMapper;

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

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

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

        // 关键字检查
        String keyword = voteSubmissionForm.getKeyword();
        if (keyword != null && !keyword.trim().isEmpty()) {
            wrapper.like(VoteSubmissionForm::getFormName, keyword.trim());
        }
        wrapper.orderByDesc(VoteSubmissionForm::getUpdatedAt);
        // 使用流API处理内容项数量
        List<VoteSubmissionForm> forms = voteSubmissionFormMapper.selectList(wrapper);
        ObjectMapper objectMapper = new ObjectMapper();
        forms.forEach(item -> {
            try {
                item.setCount(objectMapper.readValue(item.getFormData(), new TypeReference<List<Map<String, Object>>>() {
                }).size());
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        });

        mpPage.setRecords(forms);
        return mpPage;
    }


    /**
     * 保存提交作品表单
     *
     * @param voteSubmissionForm
     * @return
     */
    @Override
    @Transactional
    public int add(VoteSubmissionForm voteSubmissionForm) {
        List<Map<String, String>> maps = extracted(voteSubmissionForm);
        // 插入新表单
        voteSubmissionFormMapper.insert(voteSubmissionForm);
        for (Map<String, String> map : maps) {
            VoteDataStorage storage = new VoteDataStorage();
            storage.setSubmissionFormTemplateId(voteSubmissionForm.getId())
                    .setKeyName(map.get("vModel"))
                    .setExplanation(map.get("label"))
                    .setCreatedAt(new Date());
            voteDataStorageMapper.insert(storage);
        }
        return 1;
    }

    private List<Map<String, String>> extracted(VoteSubmissionForm voteSubmissionForm) {
        // 解析 JSON 字段
        String formData = voteSubmissionForm.getFormData();
        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String, Object>> formDataList;
        try {
            // 将前端传入的 JSON 转换为 List<Map<String, Object>>
            formDataList = objectMapper.readValue(formData, new TypeReference<List<Map<String, Object>>>() {
            });
        } catch (Exception e) {
            throw new RuntimeException("解析 formData 字段失败", e);
        }
        //用于存储解析后的字段名
        List<Map<String, String>> maps = new ArrayList<>();
        // 检查 JSON 中 vModel 的值是否重复
        Set<String> vModelSet = new HashSet<>();
        for (Map<String, Object> formField : formDataList) {
            String vModel = (String) formField.get("vModel");
            String label = (String) formField.get("label");
            if (vModel != null) {
                if (!vModelSet.add(vModel)) {
                    throw new RuntimeException("JSON 中存在重复的 vModel 值，添加失败");
                }
                //将字段名和字段解释添加到心底数据格式中
                Map<String, String> map = new HashMap<>();
                map.put("label", label);
                map.put("vModel", vModel);
                maps.add(map);
            }
        }

        // 检查数据库中是否存在重复的作品表单
        LambdaQueryWrapper<VoteSubmissionForm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(VoteSubmissionForm::getFormName, voteSubmissionForm.getFormName().trim());
        List<VoteSubmissionForm> submissionForms = voteSubmissionFormMapper.selectList(wrapper);
        if (!submissionForms.isEmpty()) {
            throw new RuntimeException("存在重复作品表单，添加失败");
        }

        return maps;
    }

    /**
     * 查询回显列表
     *
     * @param date
     * @return
     */
    @Override
    public List<VoteSubmissionForm> getSubmission(String date) {
        LambdaQueryWrapper<VoteSubmissionForm> wrapper = new LambdaQueryWrapper<>();
        if (date == null || date.isEmpty()) {
            wrapper.orderByDesc(VoteSubmissionForm::getUpdatedAt);
        } else {
            wrapper.like(VoteSubmissionForm::getFormName, date);
        }
        List<VoteSubmissionForm> voteSubmissionForms = voteSubmissionFormMapper.selectList(wrapper);
        return voteSubmissionForms.size() > 20 ? voteSubmissionForms.subList(0, 20) : voteSubmissionForms;
    }

    @Override
    @Transactional
    public int editById(VoteSubmissionForm voteSubmissionForm) {
        extracted(voteSubmissionForm);
        return voteSubmissionFormMapper.updateById(voteSubmissionForm);
    }


    /**
     * 获取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()) {
                return (int) rootNode.elements().next().spliterator().getExactSizeIfKnown();
            } else {
                return 0; // 根节点既不是对象也不是数组
            }
        } catch (IOException e) {
            throw new RuntimeException("json解析失败", e);
        }
    }
}



