package com.hotent.surveyinfo.controller;


import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.controller.BaseController;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import com.hotent.surveyinfo.dao.CostSurveyFdTemplateHeadersDao;
import com.hotent.surveyinfo.dao.CostSurveyFdTemplateItemsDao;
import com.hotent.surveyinfo.dao.CostSurveyTemplateItemsDao;
import com.hotent.surveyinfo.manager.*;
import com.hotent.surveyinfo.model.*;
import com.hotent.surveyinfo.model.dto.CostItemData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 指标项子表 前端控制器
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-19
 */
@RestController
@RequestMapping("/costSurveyFdTemplateItems/v1/")
@Api(tags = "财务数据指标项")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostSurveyFdTemplateItemsController extends BaseController<CostSurveyFdTemplateItemsManager, CostSurveyFdTemplateItems> {
	@Autowired
	CostSurveyFdTemplateItemsDao costSurveyTemplateItemsDao;
	@Autowired
	CostSurveyFdTemplateVersionManager costSurveyTemplateVersionManager;
	@Autowired
	CostSurveyFdTemplateHeadersDao costSurveyTemplateHeadersDao;

	@Autowired
	CostSurveyFdTemplateHeadersManager costSurveyFdTemplateHeadersManager;
	/**
	 * 根据survey_template_id获取所有指标项数据
	 * @param surveyTemplateId 关联的财务数据调查表ID
	 * @return 指标项列表
	 */
	@GetMapping(value = "/listByTemplateId")
	@ApiOperation(value = "根据财务数据调查表ID获取所有指标项数据", httpMethod = "GET", notes = "根据财务数据调查表ID获取所有指标项数据")
	public CommonResult<List<CostSurveyFdTemplateItems>> listByTemplateId(
			@ApiParam(name = "surveyTemplateId", value = "关联的财务数据调查表ID", required = true)
			@RequestParam(required = true) String surveyTemplateId) throws Exception {

		List<CostSurveyFdTemplateItems> items = costSurveyTemplateItemsDao.selectBySurveyTemplateId(surveyTemplateId);
		return CommonResult.<List<CostSurveyFdTemplateItems>>ok().value(items);
	}
	/**
	 * 根据财务数据调查表id、版本号和表头id获取指标项数据列表
	 * @param surveyTemplateId 财务数据调查表id
	 * @param version 版本号
	 * @param headersId 表头id
	 * @return 指标项数据列表
	 */
	@GetMapping(value = "/listByTemplateIdAndVersionAndHeadersId")
	@ApiOperation(value = "根据财务数据调查表ID、版本id和表头ID获取指标项数据列表", httpMethod = "GET", notes = "根据财务数据调查表ID、版本号和表头ID获取指标项数据列表")
	public CommonResult<List<CostSurveyFdTemplateItems>> listByTemplateIdAndVersionAndHeadersId(
			@ApiParam(name = "surveyTemplateId", value = "关联的财务数据调查表ID", required = true)
			@RequestParam(required = true) String surveyTemplateId,
			@ApiParam(name = "version", value = "版本id", required = true)
			@RequestParam(required = true) String version,
			@ApiParam(name = "headersId", value = "表头ID", required = true)
			@RequestParam(required = true) String headersId) throws Exception {

		List<CostSurveyFdTemplateItems> items = costSurveyTemplateItemsDao.selectBySurveyTemplateIdAndVersionAndHeadersId(surveyTemplateId, version, headersId);
		return CommonResult.<List<CostSurveyFdTemplateItems>>ok().value(items);
	}

	/**
	 * 根据财务数据调查表id和版本号获取指标项数据列表
	 * @param surveyTemplateId 财务数据调查表id
	 * @param version 版本号
	 * @return 指标项数据列表
	 */
	@GetMapping(value = "/listByTemplateIdAndVersion")
	@ApiOperation(value = "根据财务数据调查表ID和版本id获取指标项数据列表（带key-value拼接）", httpMethod = "GET", notes = "根据财务数据调查表ID和版本号获取指标项数据列表（带key-value拼接）")
	public CommonResult<CostItemData> listByTemplateIdAndVersion(
			@ApiParam(name = "surveyTemplateId", value = "关联的财务数据调查表ID", required = true)
			@RequestParam(required = true) String surveyTemplateId,
			@ApiParam(name = "version", value = "版本id", required = true)
			@RequestParam(required = true) String version) throws Exception {

		List<CostSurveyFdTemplateItems> items = costSurveyTemplateItemsDao.selectBySurveyTemplateIdAndVersion(surveyTemplateId, version);
		List<CostSurveyFdTemplateHeaders> heardlist = costSurveyFdTemplateHeadersManager.listVisibleBySurveyTemplateIdAndVersion(surveyTemplateId, version);
		//使用逗号拼接 filename 值 循环遍历heardlist
		String filename = heardlist.stream().map(CostSurveyFdTemplateHeaders::getFieldName).collect(Collectors.joining(","));
		String fileids = heardlist.stream().map(CostSurveyFdTemplateHeaders::getId).collect(Collectors.joining(","));


		// 按 headersId 分组
		Map<Integer, List<CostSurveyFdTemplateItems>> groupedByHeadersId = items.stream()
				.collect(Collectors.groupingBy(CostSurveyFdTemplateItems::getOrderNum));

		List<Map<String, String>> result = new ArrayList<>();

		for (Map.Entry<Integer, List<CostSurveyFdTemplateItems>> entry : groupedByHeadersId.entrySet()) {
			List<CostSurveyFdTemplateItems> group = entry.getValue();
			if (group.isEmpty()) continue;

			// 主项（可以取第一个）
			CostSurveyFdTemplateItems mainItem = group.get(0);

			String headersIds = "";
			String itemIds="";
			// 构造 key-value 映射
			// 构造 key-value 映射
			Map<String, String> keyValueMap = new HashMap<>();


			for (CostSurveyFdTemplateItems item : group) {
				if (item.getRkey() != null && item.getRvalue() != null) {
					keyValueMap.put(item.getRkey(), item.getRvalue());
					headersIds+=item.getHeadersId()+",";
					itemIds+=item.getId()+",";
				}
			}
			if (!StringUtil.isEmpty(headersIds))
				headersIds = headersIds.substring(0, headersIds.length() - 1);
			if( !StringUtil.isEmpty(itemIds))
				itemIds = itemIds.substring(0, itemIds.length() - 1);
			//mainItem 放入到keyValueMap中 除了 key value 这两个字段
			keyValueMap.put("id", mainItem.getId());
			keyValueMap.put("surveyTemplateId", mainItem.getSurveyTemplateId());
			keyValueMap.put("versionId", mainItem.getVersionId());
			keyValueMap.put("headersId", mainItem.getHeadersId());
			keyValueMap.put("cellCode", mainItem.getCellCode());
			keyValueMap.put("calculationFormula", mainItem.getCalculationFormula());
			keyValueMap.put("unit", mainItem.getUnit());
			keyValueMap.put("orderNum", mainItem.getOrderNum().toString());
			keyValueMap.put("jsonStr", mainItem.getJsonStr());
			keyValueMap.put("headersIds", headersIds);
			keyValueMap.put("itemIds", itemIds);
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			keyValueMap.put("createTime", mainItem.getCreateTime() != null ? mainItem.getCreateTime().format(formatter) : null);
			keyValueMap.put("updateTime", mainItem.getUpdateTime() != null ? mainItem.getUpdateTime().format(formatter) : null);
			keyValueMap.put("createBy", mainItem.getCreateBy());
			keyValueMap.put("updateBy", mainItem.getUpdateBy());
			keyValueMap.put("projectId", mainItem.getProjectId());
			keyValueMap.put("orderText", mainItem.getOrderText());
			keyValueMap.put("calculationTemplateId", mainItem.getCalculationTemplateId());
			keyValueMap.put("rowid", mainItem.getRowid());
			keyValueMap.put("parentid", mainItem.getParentid());


			result.add(keyValueMap);
		}
		CostItemData data = new CostItemData();
		data.setFixedFields(filename);
		data.setItemlist(result);
        data.setFixedFieldids(fileids);


		return CommonResult.<CostItemData>ok().value(data);
	}

//	public CommonResult<List<Map<String, String>>> listByTemplateIdAndVersion(
//			@ApiParam(name = "surveyTemplateId", value = "关联的财务数据调查表ID", required = true)
//			@RequestParam(required = true) String surveyTemplateId,
//			@ApiParam(name = "version", value = "版本id", required = true)
//			@RequestParam(required = true) String version) throws Exception {
//
//		List<CostSurveyFdTemplateItems> items = costSurveyTemplateItemsDao.selectBySurveyTemplateIdAndVersion(surveyTemplateId, version);
//
//		// 按 headersId 分组
//		Map<Integer, List<CostSurveyFdTemplateItems>> groupedByHeadersId = items.stream()
//				.collect(Collectors.groupingBy(CostSurveyFdTemplateItems::getOrderNum));
//
//		List<Map<String, String>> result = new ArrayList<>();
//
//		for (Map.Entry<Integer, List<CostSurveyFdTemplateItems>> entry : groupedByHeadersId.entrySet()) {
//			List<CostSurveyFdTemplateItems> group = entry.getValue();
//			if (group.isEmpty()) continue;
//
//			// 主项（可以取第一个）
//			CostSurveyFdTemplateItems mainItem = group.get(0);
//
//			String headersIds = "";
//			// 构造 key-value 映射
//			Map<String, String> keyValueMap = new HashMap<>();
//			for (CostSurveyFdTemplateItems item : group) {
//				if (item.getRkey() != null && item.getRvalue() != null) {
//					keyValueMap.put(item.getRkey(), item.getRvalue());
//					headersIds+=item.getHeadersId()+",";
//				}
//			}
//            if (!StringUtil.isEmpty(headersIds))
//				headersIds = headersIds.substring(0, headersIds.length() - 1);
//			//mainItem 放入到keyValueMap中 除了 key value 这两个字段
//			keyValueMap.put("id", mainItem.getId());
//			keyValueMap.put("surveyTemplateId", mainItem.getSurveyTemplateId());
//			keyValueMap.put("versionId", mainItem.getVersionId());
//			keyValueMap.put("headersId", mainItem.getHeadersId());
//			keyValueMap.put("cellCode", mainItem.getCellCode());
//			keyValueMap.put("calculationFormula", mainItem.getCalculationFormula());
//			keyValueMap.put("unit", mainItem.getUnit());
//			keyValueMap.put("orderNum", mainItem.getOrderNum().toString());
//			keyValueMap.put("jsonStr", mainItem.getJsonStr());
//			keyValueMap.put("headersIds", headersIds);
//			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
//			keyValueMap.put("createTime", mainItem.getCreateTime() != null ? mainItem.getCreateTime().format(formatter) : null);
//			keyValueMap.put("updateTime", mainItem.getUpdateTime() != null ? mainItem.getUpdateTime().format(formatter) : null);
//			keyValueMap.put("createBy", mainItem.getCreateBy());
//			keyValueMap.put("updateBy", mainItem.getUpdateBy());
//			keyValueMap.put("projectId", mainItem.getProjectId());
//			keyValueMap.put("orderText", mainItem.getOrderText());
//
//
//
//			result.add(keyValueMap);
//		}
//
//		return CommonResult.<List<Map<String, String>>>ok().value(result);
//	}

	/**
	 * 根据财务数据调查表现行模板id获取指标项数据列表
	 * @param surveyTemplateId 财务数据调查表id
	 * @return 指标项数据列表
	 */
	@GetMapping(value = "/listByCurrentTemplateId")
	@ApiOperation(value = "根据财务数据调查表现行模板id获取指标项数据列表", httpMethod = "GET", notes = "根据财务数据调查表现行模板id获取指标项数据列表")
	public CommonResult<CostItemData> listByCurrentTemplateId(
			@ApiParam(name = "surveyTemplateId", value = "关联的财务数据调查表ID", required = true)
			@RequestParam(required = true) String surveyTemplateId) throws Exception {

		CostSurveyFdTemplateVersion currentVersion  =costSurveyTemplateVersionManager.selectCurrentVersion(surveyTemplateId);
		List<CostSurveyFdTemplateItems> items = costSurveyTemplateItemsDao.selectBySurveyTemplateIdAndVersion(surveyTemplateId, currentVersion.getId());

		List<CostSurveyFdTemplateHeaders> heardlist = costSurveyFdTemplateHeadersManager.listVisibleBySurveyTemplateIdAndVersion(surveyTemplateId, currentVersion.getId()	);

		// 使用逗号拼接 fieldName 值
		String filename = heardlist.stream()
				.map(CostSurveyFdTemplateHeaders::getFieldName)
				.filter(Objects::nonNull)
				.collect(Collectors.joining(","));
		String fileids = heardlist.stream()
				.map(CostSurveyFdTemplateHeaders::getId)
				.collect(Collectors.joining(","));

		// 按 orderNum 分组
		Map<Integer, List<CostSurveyFdTemplateItems>> groupedByHeadersId = items.stream()
				.collect(Collectors.groupingBy(CostSurveyFdTemplateItems::getOrderNum));

		List<Map<String, String>> result = new ArrayList<>();

		for (Map.Entry<Integer, List<CostSurveyFdTemplateItems>> entry : groupedByHeadersId.entrySet()) {
			List<CostSurveyFdTemplateItems> group = entry.getValue();
			if (group.isEmpty()) continue;

			// 主项（可以取第一个）
			CostSurveyFdTemplateItems mainItem = group.get(0);

			String headersIds = "";
			String itemIds="";
			// 构造 key-value 映射
			Map<String, String> keyValueMap = new HashMap<>();

			for (CostSurveyFdTemplateItems item : group) {
				if (item.getRkey() != null && item.getRvalue() != null) {
					keyValueMap.put(item.getRkey(), item.getRvalue());
					headersIds += item.getHeadersId() + ",";
					itemIds +=item.getId()+",";
				}
			}
			if (!StringUtil.isEmpty(headersIds))
				headersIds = headersIds.substring(0, headersIds.length() - 1);
			if( !StringUtil.isEmpty(itemIds))
				itemIds = itemIds.substring(0, itemIds.length() - 1);

			// 添加固定字段
			keyValueMap.put("id", mainItem.getId());
			keyValueMap.put("surveyTemplateId", mainItem.getSurveyTemplateId());
			keyValueMap.put("versionId", mainItem.getVersionId());
			keyValueMap.put("headersId", mainItem.getHeadersId());
			keyValueMap.put("cellCode", mainItem.getCellCode());
			keyValueMap.put("calculationFormula", mainItem.getCalculationFormula());
			keyValueMap.put("unit", mainItem.getUnit());
			keyValueMap.put("orderNum", mainItem.getOrderNum().toString());
			keyValueMap.put("jsonStr", mainItem.getJsonStr());
			keyValueMap.put("headersIds", headersIds);
			keyValueMap.put("itemIds", itemIds);
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			keyValueMap.put("createTime", mainItem.getCreateTime() != null ? mainItem.getCreateTime().format(formatter) : null);
			keyValueMap.put("updateTime", mainItem.getUpdateTime() != null ? mainItem.getUpdateTime().format(formatter) : null);
			keyValueMap.put("createBy", mainItem.getCreateBy());
			keyValueMap.put("updateBy", mainItem.getUpdateBy());
			keyValueMap.put("projectId", mainItem.getProjectId());
			keyValueMap.put("orderText", mainItem.getOrderText());
			keyValueMap.put("calculationTemplateId", mainItem.getCalculationTemplateId());
			keyValueMap.put("rowid", mainItem.getRowid());
			keyValueMap.put("parentid", mainItem.getParentid());

			result.add(keyValueMap);
		}

		CostItemData data = new CostItemData();
		data.setFixedFields(filename);
		data.setItemlist(result);
		data.setFixedFieldids(fileids);

		return CommonResult.<CostItemData>ok().value(data);
	}


	/**
	 * 根据id获取指标项子表数据详情
	 * @param id
	 * @return
	 * @throws Exception 
	 * ModelAndView
	 */
	@GetMapping(value="/getDetail")
	@ApiOperation(value="根据id获取指标项子表数据详情",httpMethod = "GET",notes = "根据id获取指标项子表数据详情")
	public CommonResult<CostSurveyFdTemplateItems> getDetail(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam(required=true) String id) throws Exception{
		return CommonResult.<CostSurveyFdTemplateItems>ok().value(baseService.getDetail(id));
	}
    /**
	 * 新增,更新指标项子表
	 * @param costSurveyTemplateItems
	 * @throws Exception 
	 * @return
	 * @exception 
	 */
	@PostMapping(value="/save")
	@ApiOperation(value = "新增,更新指标项子表数据", httpMethod = "POST", notes = "新增,更新指标项子表数据")
	public CommonResult<String> save(@ApiParam(name="CostSurveyTemplateItems",value="指标项子表对象", required = true)@RequestBody CostSurveyFdTemplateItems costSurveyTemplateItems) throws Exception{
		String msg = StringUtil.isEmpty(costSurveyTemplateItems.getId()) ? "添加指标项子表成功" : "更新指标项子表成功";
		baseService.createOrUpdate(costSurveyTemplateItems);
		return CommonResult.<String>ok().message(msg);
	}
	/**
	 * 批量删除指标项子表数据
	 * @param ids 指标项子表ID列表
	 * @return 删除结果
	 * @throws Exception
	 */
	@PostMapping(value="/batchDelete")
	@ApiOperation(value = "批量删除指标项子表数据", httpMethod = "POST", notes = "批量删除指标项子表数据")
	public CommonResult<String> batchDelete(@ApiParam(name="ids",value="指标项子表ID列表", required = true)@RequestBody List<String> ids) throws Exception{
		baseService.removeByIds(ids);
		return CommonResult.<String>ok().message("批量删除指标项子表成功");
	}


	/**
	 * 根据现行模板id获取所有指标编号数据
	 *
	 * @param surveyTemplateId 现行模板ID
	 * @return 指标编号列表
	 */
	@GetMapping(value = "/cellCodesByTemplateId")
	@ApiOperation(value = "根据现行模板id获取所有指标编号数据", httpMethod = "GET", notes = "根据现行模板id获取所有指标编号数据")
	public CommonResult<List<CostSurveyFdTemplateItems>> getCellCodesByTemplateId(
			@ApiParam(name = "surveyTemplateId", value = "现行模板ID", required = true)
			@RequestParam(required = true) String surveyTemplateId) {
		//获取现行版本模板
		CostSurveyFdTemplateVersion version = costSurveyTemplateVersionManager.selectCurrentVersion(surveyTemplateId);
		List<CostSurveyFdTemplateItems> cellCodes = baseService.getCellCodesBySurveyTemplateId(surveyTemplateId,version.getId());
		return CommonResult.<List<CostSurveyFdTemplateItems>>ok().value(cellCodes);
	}
}
