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.CostSurveyTemplateItemsDao;
import com.hotent.surveyinfo.dao.CostVerifyTemplateHeadersDao;
import com.hotent.surveyinfo.dao.CostVerifyTemplateItemsDao;
import com.hotent.surveyinfo.manager.CostSurveyFdTemplateVersionManager;
import com.hotent.surveyinfo.manager.CostSurveyTemplateItemsManager;
import com.hotent.surveyinfo.manager.CostVerifyTemplateHeadersManager;
import com.hotent.surveyinfo.manager.CostVerifyTemplateItemsManager;
import com.hotent.surveyinfo.model.CostSurveyFdTemplateHeaders;
import com.hotent.surveyinfo.model.CostSurveyTemplateItems;
import com.hotent.surveyinfo.model.CostVerifyTemplateHeaders;
import com.hotent.surveyinfo.model.CostVerifyTemplateItems;
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("/costVerifyTemplateItems/v1/")
@Api(tags = "成本核定指标项")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostVerifyTemplateItemsController extends BaseController<CostVerifyTemplateItemsManager, CostVerifyTemplateItems> {
	@Autowired
	CostVerifyTemplateItemsDao costSurveyTemplateItemsDao;

	@Autowired
	CostVerifyTemplateHeadersDao  costSurveyTemplateheadDao;

	@Autowired
	CostVerifyTemplateHeadersManager costSurveyTemplateheadManager;

//	/**
//	 * 根据survey_template_id获取所有指标项数据
//	 * @param surveyTemplateId 关联的成本核定表ID
//	 * @return 指标项列表
//	 */
//	@GetMapping(value = "/listByTemplateId")
//	@ApiOperation(value = "根据成本核定表ID获取所有指标项数据", httpMethod = "GET", notes = "根据成本核定表ID获取所有指标项数据")
//	public CommonResult<List<CostVerifyTemplateItems>> listByTemplateId(
//			@ApiParam(name = "surveyTemplateId", value = "关联的成本核定表ID", required = true)
//			@RequestParam(required = true) String surveyTemplateId) throws Exception {
//
//		List<CostVerifyTemplateItems> items = costSurveyTemplateItemsDao.selectBySurveyTemplateId(surveyTemplateId);
//		return CommonResult.<List<CostVerifyTemplateItems>>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<CostVerifyTemplateItems>> 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<CostVerifyTemplateItems> items = costSurveyTemplateItemsDao.selectBySurveyTemplateIdAndVersionAndHeadersId(surveyTemplateId, version, headersId);
		return CommonResult.<List<CostVerifyTemplateItems>>ok().value(items);
	}

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

		List<CostVerifyTemplateItems> items = costSurveyTemplateItemsDao.selectByVerifyTemplateId(surveyTemplateId,taskId);
		if (!items.isEmpty() && StringUtil.isEmpty(surveyTemplateId)){
			surveyTemplateId=items.get(0).getSurveyTemplateId();
		}
		List<CostVerifyTemplateHeaders> heardlist = costSurveyTemplateheadManager.listVisibleBySurveyTemplateId(surveyTemplateId);
		String filename = heardlist.stream().map(CostVerifyTemplateHeaders::getFieldName).collect(Collectors.joining(","));
		String fileids = heardlist.stream().map(CostVerifyTemplateHeaders::getId).collect(Collectors.joining(","));

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

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

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

			CostVerifyTemplateItems mainItem = new CostVerifyTemplateItems();

			// 主项（可以取第一个）

			 mainItem = group.stream()
					.filter(item -> item.getParentid() != null )
					.findFirst()
					.orElse(null);

			if(mainItem == null){
				 mainItem = group.get(0);
			}


			String headersIds = "";
			String itemIds="";
			// 构造 key-value 映射
			Map<String, String> keyValueMap = new HashMap<>();
			for (CostVerifyTemplateItems 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);
	}



	/**
	 * 根据id获取指标项子表数据详情
	 * @param id
	 * @return
	 * @throws Exception 
	 * ModelAndView
	 */
	@GetMapping(value="/getDetail")
	@ApiOperation(value="根据id获取指标项子表数据详情",httpMethod = "GET",notes = "根据id获取指标项子表数据详情")
	public CommonResult<CostVerifyTemplateItems> getDetail(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam(required=true) String id) throws Exception{
		return CommonResult.<CostVerifyTemplateItems>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 CostVerifyTemplateItems costSurveyTemplateItems) throws Exception{
		String msg = StringUtil.isEmpty(costSurveyTemplateItems.getId()) ? "添加指标项子表成功" : "更新指标项子表成功";
		baseService.createOrUpdate(costSurveyTemplateItems);
		return CommonResult.<String>ok().message(msg);
	}


	/**
	 * 根据costVerifyTemplateId删除指标项子表数据
	 * @param costVerifyTemplateId 成本核定模板ID
	 * @return 删除结果
	 * @throws Exception
	 */
	@DeleteMapping(value = "/deleteByCostVerifyTemplateId")
	@ApiOperation(value = "根据costVerifyTemplateId删除指标项子表数据", httpMethod = "DELETE", notes = "根据costVerifyTemplateId删除指标项子表数据")
	public CommonResult<String> deleteByCostVerifyTemplateId(
			@ApiParam(name = "costVerifyTemplateId", value = "成本核定模板ID", required = true)
			@RequestParam(required = true) String costVerifyTemplateId) throws Exception {

		// 调用service层方法删除数据
		costSurveyTemplateItemsDao.deleteByCostVerifyTemplateId(costVerifyTemplateId);

		return CommonResult.<String>ok().message("删除成功");
	}

	/**
	 * 根据成本核定表现行模板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 = false)
			@RequestParam(value = "surveyTemplateId" ,required = false) String surveyTemplateId,
			@RequestParam(required = false) String taskId) throws Exception {


		// 查询当前模板的所有指标项数据
		List<CostVerifyTemplateItems> items = costSurveyTemplateItemsDao.selectByVerifyTemplateId(surveyTemplateId,taskId);

		// 查询当前模板的所有表头信息
		List<CostVerifyTemplateHeaders> heardlist = costSurveyTemplateheadManager.listVisibleBySurveyTemplateId(surveyTemplateId);

		// 使用逗号拼接 fieldName 值
		String filename = heardlist.stream()
				.map(CostVerifyTemplateHeaders::getFieldName)
				.filter(fieldName -> fieldName != null && !fieldName.isEmpty())
				.collect(Collectors.joining(","));
		String fileids = heardlist.stream()
				.map(CostVerifyTemplateHeaders::getId)
				.collect(Collectors.joining(","));
		// 按 orderNum 分组
		Map<Integer, List<CostVerifyTemplateItems>> groupedByHeadersId = items.stream()
				.collect(Collectors.groupingBy(CostVerifyTemplateItems::getOrderNum));

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

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

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

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

			for (CostVerifyTemplateItems 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);
	}

	/**
	 * 批量删除指标项子表数据
	 * @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 verifyTemplateId 核定模板ID
	 * @return 指标数据信息
	 */
	@GetMapping(value = "/listByVerifyTemplateId")
	@ApiOperation(value = "根据核定模板ID获取指标数据信息", httpMethod = "GET", notes = "根据核定模板ID获取指标数据信息")
	public CommonResult<List<CostVerifyTemplateItems>> listByVerifyTemplateId(
			@ApiParam(name = "verifyTemplateId", value = "核定模板ID", required = true)
			@RequestParam(required = true) String verifyTemplateId,
			@RequestParam(required = false) String taskId
			) throws Exception {

		List<CostVerifyTemplateItems> items = costSurveyTemplateItemsDao.selectByVerifyTemplateId(verifyTemplateId,taskId);
		//CostVerifyTemplateItems orderunm 去重

		return CommonResult.<List<CostVerifyTemplateItems>>ok().value(items);
	}


}
