package com.hotent.surveyinfo.manager.impl;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.surveyinfo.calculator.CostSurveyFormulaCalculator;
import com.hotent.surveyinfo.dao.CostSurveyFdTemplateDao;
import com.hotent.surveyinfo.dao.CostSurveyFdTemplateItemsDao;
import com.hotent.surveyinfo.dao.CostSurveyTemplateDao;
import com.hotent.surveyinfo.dao.CostSurveyTemplateItemsDao;
import com.hotent.surveyinfo.manager.CostSurveyFdTemplateItemsManager;
import com.hotent.surveyinfo.manager.CostSurveyFdTemplateManager;
import com.hotent.surveyinfo.manager.CostSurveyTemplateItemsManager;
import com.hotent.surveyinfo.manager.CostSurveyTemplateManager;
import com.hotent.surveyinfo.model.CostSurveyFdTemplate;
import com.hotent.surveyinfo.model.CostSurveyFdTemplateItems;
import com.hotent.surveyinfo.model.CostSurveyTemplate;
import com.hotent.surveyinfo.model.CostSurveyTemplateItems;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 指标项子表 服务实现类
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-19
 */
@Service
public class CostSurveyFdTemplateItemsManagerImpl extends BaseManagerImpl<CostSurveyFdTemplateItemsDao, CostSurveyFdTemplateItems> implements CostSurveyFdTemplateItemsManager {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	CostSurveyFdTemplateDao costSurveyTemplateDao;
	@Override
	public CostSurveyFdTemplateItems getDetail(String id) {
		CostSurveyFdTemplateItems costSurveyTemplateItems = this.get(id);
    	

		return costSurveyTemplateItems;
	}
	@Override
	@Transactional
	public void createOrUpdate(CostSurveyFdTemplateItems costSurveyTemplateItems) {
		//新建或更新
		this.saveOrUpdate(costSurveyTemplateItems);
	}

	@Override
	public List<CostSurveyFdTemplateItems> selectBySurveyTemplateId(String surveyTemplateId) {
		return null;
	}

	@Override
	public boolean validateFormula(CostSurveyFdTemplateItems item, Map<String, Object> data) {
		try {
			// 获取所有相关表数据
			Map<String, Map<String, Object>> allTableData = getAllRelatedTableData(item.getSurveyTemplateId());

			// 创建计算器
			CostSurveyFormulaCalculator calculator = new CostSurveyFormulaCalculator(
					data, allTableData
			);

			// 计算公式结果
			Double calculatedValue = calculator.calculate(item.getCalculationFormula());

			// 获取实际值
			Object actualValue = data.get(item.getCellCode());
			Double actualDoubleValue = actualValue instanceof Number ?
					((Number) actualValue).doubleValue() : null;

			// 比较结果（允许一定误差）
			if (actualDoubleValue == null) {
				return false;
			}

			double tolerance = 0.0001; // 0.01%的误差
			return Math.abs(calculatedValue - actualDoubleValue) < tolerance;

		} catch (Exception e) {
			// 公式计算失败，视为验证不通过
			return false;
		}
	}

	@Override
	public List<CostSurveyFdTemplateItems> getCellCodesBySurveyTemplateId(String templateId, String versionId) {
		QueryWrapper<CostSurveyFdTemplateItems> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("survey_template_id", templateId);
		queryWrapper.eq("version_id", versionId);

		List<CostSurveyFdTemplateItems> items = this.list(queryWrapper);

		return items;
	}

	/**
	 * 获取所有相关表数据
	 */
	private Map<String, Map<String, Object>> getAllRelatedTableData(String templateId) {
		Map<String, Map<String, Object>> result = new HashMap<>();

		// 查询当前模板的所有关联表
		CostSurveyFdTemplate conditions = new CostSurveyFdTemplate();
		conditions.setSurveyTemplateId(templateId);
		conditions.setStatus("0");
		List<CostSurveyFdTemplate> relatedTemplates = costSurveyTemplateDao.selectByCondition(conditions
		);

		for (CostSurveyFdTemplate template : relatedTemplates) {
			// 获取该模板的数据
			Map<String, Object> tableData = getTableData(template.getStorageTable());
			result.put(template.getSurveyTemplateNameYw(), tableData);
		}

		return result;
	}

	/**
	 * 获取指定表的数据
	 */
	private Map<String, Object> getTableData(String tableName) {
		// 根据表名查询数据
		// 这里需要根据具体的数据存储方式实现
		// 对于固定表，可能需要查询特定的存储表
		// 对于动态表，可能需要查询JSON数据

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

		// 示例：查询固定表数据
		if (tableName.startsWith("fixed_")) {
			// 查询固定表数据
			List<Map<String, Object>> rows = jdbcTemplate.queryForList(
					"SELECT * FROM " + tableName + " WHERE status = '0'"
			);

			for (Map<String, Object> row : rows) {
				String cellCode = row.get("cell_code").toString();
				Object value = row.get("value");
				if (value != null && value instanceof Number) {
					data.put(cellCode, value);
				}
			}
		}

		// 示例：查询动态表数据
		else if (tableName.startsWith("dynamic_")) {
			// 查询动态表数据
			List<Map<String, Object>> rows = jdbcTemplate.queryForList(
					"SELECT * FROM " + tableName + " WHERE status = '0'"
			);

			for (Map<String, Object> row : rows) {
				String cellCode = row.get("cell_code").toString();
				Object value = row.get("data_json");
				if (value != null && value instanceof String) {
					try {
						JSONObject json =  JSONObject.parseObject((String) value);
						data.put(cellCode, json.getDouble("value"));
					} catch (JSONException e) {
						// 忽略解析错误
					}
				}
			}
		}

		return data;
	}

	@Override
	public void deleteBySurveyTemplateIdAndVersionId(String surveyTemplateId, String versionId) {
		com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<CostSurveyFdTemplateItems> queryWrapper =
				new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
		queryWrapper.eq("survey_template_id", surveyTemplateId);
		queryWrapper.eq("version_id", versionId);
		this.remove(queryWrapper);
	}

}
