package com.fs.survey.service.impl;

import com.fs.common.exception.ServiceException;
import com.fs.common.utils.SecurityUtils;
import com.fs.common.utils.ip.IpUtils;
import com.fs.survey.domain.SurveyQuestionnaireVersion;
import com.fs.survey.mapper.DynamicTableMapper;
import com.fs.survey.mapper.SurveyQuestionnaireVersionMapper;
import com.fs.survey.service.ISurveyDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 问卷数据Service业务层处理
 *
 */
@Service
public class SurveyDataServiceImpl implements ISurveyDataService {

    @Autowired
    private DynamicTableMapper dynamicTableMapper;

    @Autowired
    private SurveyQuestionnaireVersionMapper versionMapper;

    @Autowired(required = false)
    private HttpServletRequest request;

    /**
     * 查询问卷数据列表
     *
     * @param params 查询参数
     * @return 问卷数据集合
     */
    @Override
    public List<Map<String, Object>> selectSurveyDataList(Map<String, Object> params) {
        Long versionId = Long.parseLong(params.get("versionId").toString());
        SurveyQuestionnaireVersion version = versionMapper.selectSurveyQuestionnaireVersionById(versionId);

        if (version == null || version.getTableName() == null) {
            throw new ServiceException("版本不存在或未发布");
        }

        return dynamicTableMapper.selectDataList(version.getTableName(), params);
    }

    /**
     * 查询问卷数据详情
     *
     * @param versionId 版本ID
     * @param id 数据ID
     * @return 问卷数据
     */
    @Override
    public Map<String, Object> selectSurveyDataById(Long versionId, Long id) {
        SurveyQuestionnaireVersion version = versionMapper.selectSurveyQuestionnaireVersionById(versionId);

        if (version == null || version.getTableName() == null) {
            throw new ServiceException("版本不存在或未发布");
        }

        return dynamicTableMapper.selectDataById(version.getTableName(), id);
    }

    /**
     * 提交问卷数据
     *
     * @param data 问卷数据
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int submitSurveyData(Map<String, Object> data) {
        Long versionId = Long.parseLong(data.get("versionId").toString());
        SurveyQuestionnaireVersion version = versionMapper.selectSurveyQuestionnaireVersionById(versionId);

        if (version == null || version.getTableName() == null) {
            throw new ServiceException("版本不存在或未发布");
        }

        // 添加提交信息
        data.put("company_id", version.getCompanyId());
        data.put("version_id", versionId);
        data.put("submit_time", new Date());

        // 获取当前用户信息
        try {
            data.put("user_id", SecurityUtils.getUserId());
            data.put("user_name", SecurityUtils.getUsername());
        } catch (Exception e) {
            // 匿名提交
            data.put("is_anonymous", 1);
        }

        // 获取IP和UA
        if (request != null) {
            data.put("ip_address", IpUtils.getIpAddr(request));
            data.put("user_agent", request.getHeader("User-Agent"));
        }

        return dynamicTableMapper.insertData(version.getTableName(), data);
    }

    /**
     * 修改问卷数据
     *
     * @param data 问卷数据
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSurveyData(Map<String, Object> data) {
        Long versionId = Long.parseLong(data.get("versionId").toString());
        SurveyQuestionnaireVersion version = versionMapper.selectSurveyQuestionnaireVersionById(versionId);

        if (version == null || version.getTableName() == null) {
            throw new ServiceException("版本不存在或未发布");
        }

        data.put("update_time", new Date());

        return dynamicTableMapper.updateData(version.getTableName(), data);
    }

    /**
     * 批量删除问卷数据
     *
     * @param versionId 版本ID
     * @param ids 需要删除的数据主键集合
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteSurveyDataByIds(Long versionId, Long[] ids) {
        SurveyQuestionnaireVersion version = versionMapper.selectSurveyQuestionnaireVersionById(versionId);

        if (version == null || version.getTableName() == null) {
            throw new ServiceException("版本不存在或未发布");
        }

        int count = 0;
        for (Long id : ids) {
            count += dynamicTableMapper.deleteData(version.getTableName(), id);
        }

        return count;
    }

    /**
     * 获取数据统计
     *
     * @param versionId 版本ID
     * @return 统计结果
     */
    @Override
    public Map<String, Object> getStatistics(Long versionId) {
        SurveyQuestionnaireVersion version = versionMapper.selectSurveyQuestionnaireVersionById(versionId);

        if (version == null || version.getTableName() == null) {
            throw new ServiceException("版本不存在或未发布");
        }

        Map<String, Object> statistics = new HashMap<>();

        // 查询总数据量
        Map<String, Object> params = new HashMap<>();
        params.put("versionId", versionId);
        List<Map<String, Object>> allData = dynamicTableMapper.selectDataList(version.getTableName(), params);

        statistics.put("total", allData.size());
        statistics.put("versionId", versionId);
        statistics.put("versionNo", version.getVersionNo());
        statistics.put("questionnaireId", version.getQuestionnaireId());

        return statistics;
    }
}
