package com.hotent.surveyinfo.controller;


import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.util.PinyinUtil;
import com.hotent.surveyinfo.dao.CostSurveyFdTemplateHeadersDao;
import com.hotent.surveyinfo.dao.CostSurveyTemplateHeadersDao;
import com.hotent.surveyinfo.manager.CostSurveyTemplateItemsManager;
import com.hotent.surveyinfo.manager.CostSurveyTemplateManager;
import com.hotent.surveyinfo.manager.CostSurveyTemplateVersionManager;
import com.hotent.surveyinfo.model.CostSurveyFdTemplateHeaders;
import com.hotent.surveyinfo.model.CostSurveyTemplateItems;
import com.hotent.surveyinfo.model.CostSurveyTemplateVersion;
import com.hotent.surveyinfo.model.dto.BatchHeadersItemsRequest;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.util.ContextUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RestController;
import com.hotent.base.controller.BaseController;
import com.hotent.surveyinfo.model.CostSurveyTemplateHeaders;
import com.hotent.surveyinfo.manager.CostSurveyTemplateHeadersManager;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * 成本调查表头子表 前端控制器
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-19
 */
@RestController
@RequestMapping("/costSurveyTemplateHeaders/v1/")
@Api(tags = "成本调查表头")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostSurveyTemplateHeadersController extends BaseController<CostSurveyTemplateHeadersManager, CostSurveyTemplateHeaders> {
	@Autowired
	CostSurveyTemplateHeadersDao costSurveyTemplateHeadersDao;
	@Autowired
	CostSurveyTemplateManager basemanager;
	@Autowired
	private CostSurveyTemplateItemsManager costSurveyTemplateItemsManager;
	@Autowired
	CostSurveyTemplateVersionManager costSurveyTemplateVersionManager;

	@Autowired
	CostSurveyFdTemplateHeadersDao costSurveyFdTemplateHeadersDao;
	/**
	 * 根据成本调查表id获取成本调查表头子表数据列表
	 * @param surveyTemplateId
	 * @return
	 */
	@ApiOperation(value="根据成本调查表id获取成本调查表头子表数据列表", httpMethod = "GET", notes = "根据成本调查表id获取成本调查表头子表数据列表")
	@GetMapping("/getlistBySurveyTemplateId")
	public CommonResult<List<CostSurveyTemplateHeaders>> getlistBySurveyTemplateId(
			@RequestParam String surveyTemplateId) {

		List<CostSurveyTemplateHeaders> headersList =
				costSurveyTemplateHeadersDao.selectBySurveyTemplateId(surveyTemplateId
						);

		return CommonResult.<List<CostSurveyTemplateHeaders>>ok().value(headersList);
	}


	/**
	 * 根据成本调查表id和版本号获取表头数据列表
	 * @param surveyTemplateId 成本调查表id
	 * @param versionId 版本号
	 * @return 表头数据列表
	 */
	@ApiOperation(value="根据成本调查表id和版本id获取表头数据列表", httpMethod = "GET", notes = "根据成本调查表id和版本号获取表头数据列表")
	@GetMapping("/getlistBySurveyTemplateIdAndVersion")
	public CommonResult<List<?>> xgetlistBySurveyTemplateIdAndVersion(
			@ApiParam(name="surveyTemplateId",value="成本调查表id", required = true) @RequestParam String surveyTemplateId,
			@ApiParam(name="versionId",value="版本id", required = false) @RequestParam(required = false) String versionId,
			@ApiParam(name="type",value="版本id", required = false) @RequestParam(required = false,defaultValue = "1") String type
	) {
		if ("1".equals(type)) {
			List<CostSurveyTemplateHeaders> headersList =
					costSurveyTemplateHeadersDao.selectBySurveyTemplateIdAndVersion(surveyTemplateId, versionId);
			return CommonResult.<List<?>>ok().value(headersList);
		}else{

			List<CostSurveyFdTemplateHeaders> headersList =
					costSurveyFdTemplateHeadersDao.selectBySurveyTemplateId(surveyTemplateId);
			return CommonResult.<List<?>>ok().value(headersList);
		}
	}

	/**
	 * 根据成本调查表id获取现行版的表头数据列表
	 * @param surveyTemplateId 成本调查表id
	 * @return 表头数据列表
	 */
	@ApiOperation(value="根据成本调查表id获取现行版的表头数据列表", httpMethod = "GET", notes = "根据成本调查表id和版本号获取表头数据列表")
	@GetMapping("/getlistBySurveyTemplateIdcurrentversion")
	public CommonResult<List<CostSurveyTemplateHeaders>> getlistBySurveyTemplateIdcurrentversion(
			@ApiParam(name="surveyTemplateId",value="成本调查表id", required = true) @RequestParam String surveyTemplateId) {

		//获取现行版本号
		CostSurveyTemplateVersion version = costSurveyTemplateVersionManager.selectCurrentVersion(surveyTemplateId);
		List<CostSurveyTemplateHeaders> headersList =
				costSurveyTemplateHeadersDao.selectBySurveyTemplateIdAndVersion(surveyTemplateId, version.getId());

		return CommonResult.<List<CostSurveyTemplateHeaders>>ok().value(headersList);
	}


	/**
	 * 根据id获取成本调查表头子表数据详情
	 * @param id
	 * @return
	 * @throws Exception 
	 * ModelAndView
	 */
	@GetMapping(value="/getDetail")
	@ApiOperation(value="根据id获取成本调查表头子表数据详情",httpMethod = "GET",notes = "根据id获取成本调查表头子表数据详情")
	public CommonResult<CostSurveyTemplateHeaders> getDetail(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam(required=true) String id) throws Exception{
		return CommonResult.<CostSurveyTemplateHeaders>ok().value(baseService.getDetail(id));
	}
    /**
	 * 新增,更新成本调查表头子表
	 * @param costSurveyTemplateHeaders
	 * @throws Exception 
	 * @return
	 * @exception 
	 */
	@PostMapping(value="/save")
	@ApiOperation(value = "新增或更新成本调查表头子表数据", httpMethod = "POST", notes = "新增或更新成本调查表头子表数据")
	public CommonResult<String> save(@ApiParam(name="CostSurveyTemplateHeaders",value="成本调查表头子表对象", required = true)@RequestBody CostSurveyTemplateHeaders costSurveyTemplateHeaders) throws Exception{
		String msg = StringUtil.isEmpty(costSurveyTemplateHeaders.getId()) ? "添加成本调查表头子表成功" : "更新成本调查表头子表成功";
		baseService.createOrUpdate(costSurveyTemplateHeaders);


		return CommonResult.<String>ok().message(msg);
	}

	/**
	 * 批量新增或更新成本调查表头及指标项数据
	 * 动态处理 headersId 的生成和关联
	 * @param request 包含表头列表和指标项列表的请求对象
	 * @return 操作结果
	 * @throws Exception 异常信息
	 */
	@ApiOperation(value = "批量新增或更新成本调查表头及指标项数据", httpMethod = "POST", notes = "批量新增或更新成本调查表头及指标项数据")
	@PostMapping(value = "/batchSaveOrUpdate")
	public CommonResult<String> batchSaveOrUpdate(
			@ApiParam(name = "request", value = "包含表头列表和指标项列表的请求对象", required = true)
			@RequestBody BatchHeadersItemsRequest request) throws Exception {

		List<CostSurveyTemplateHeaders> headersList = request.getHeadersList();
		List<CostSurveyTemplateItems> itemsList = request.getItemsList();
		List<CostSurveyTemplateHeaders> deleteHeadersList = request.getDeleteheadersList();

		// 检查输入列表是否为空
		if ((headersList == null || headersList.isEmpty()) &&
				(itemsList == null || itemsList.isEmpty()) &&
				(deleteHeadersList == null || deleteHeadersList.isEmpty())) {
			return CommonResult.<String>error().message("批量操作失败，数据列表为空");
		}

		IUser user = ContextUtil.getCurrentUser();

		// 先处理表头数据，确保所有表头都有ID
		if (headersList != null && !headersList.isEmpty()) {
			for (CostSurveyTemplateHeaders header : headersList) {
				boolean isHeaderCreate = StringUtil.isEmpty(header.getId());
				header.setFieldEname(PinyinUtil.getPinyin(header.getFieldName()));

				if(StringUtil.isEmpty(header.getId()))
				{

					header.setId(UUID.randomUUID().toString());
					header.setCreateBy(user.getAccount());
					header.setCreateTime( LocalDateTime.now());
					baseService.create(header);
				}
				else {
					header.setUpdateBy(user.getAccount());
					header.setUpdateTime( LocalDateTime.now());
					baseService.update(header);
				}



			}
		}

		// 处理需要删除的表头
		if (deleteHeadersList != null && !deleteHeadersList.isEmpty()) {
			for (CostSurveyTemplateHeaders header : deleteHeadersList) {
				if (StringUtil.isNotEmpty(header.getId())) {
					baseService.remove(header.getId());

				}
			}
		}

		// 处理指标项数据，动态设置 headersId
		if (itemsList != null && !itemsList.isEmpty()) {
			if(itemsList.size()>0)
			{
				costSurveyTemplateItemsManager.deleteBySurveyTemplateIdAndVersionId( itemsList.get(0).getSurveyTemplateId(), itemsList.get(0).getVersionId());

			}

			for (CostSurveyTemplateItems item : itemsList) {
				// 检查是否已设置 headersId
				if (StringUtil.isEmpty(item.getHeadersId())) {
					item.setHeadersId(
							headersList.stream()
									.filter(h -> h.getFieldName().equals(item.getRkey() ))
									.findFirst()
									.map(CostSurveyTemplateHeaders::getId)
									.orElse(null)
					);
				}
				item.setId(UUID.randomUUID().toString());
				item.setCreateBy(user.getAccount());
				item.setCreateTime( LocalDateTime.now());
				item.setUpdateBy(user.getAccount());
				item.setUpdateTime( LocalDateTime.now());
				costSurveyTemplateItemsManager.create(  item);


			}
		}

		return CommonResult.<String>ok().message(
				"批量操作成功");
	}





	/**
	 * 根据id删除成本调查表头子表数据
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "根据id删除成本调查表头子表数据", httpMethod = "DELETE", notes = "根据id删除成本调查表头子表数据")
	@GetMapping(value = "/remove")
	public CommonResult<String> remove(@ApiParam(name = "id", value = "业务对象主键", required = true) @RequestParam(required = true) String id) throws Exception {
		baseService.remove(id);
		return CommonResult.<String>ok().message("删除成本调查表头子表成功");
	}
	/**
	 * 批量新增成本调查表头子表数据
	 * @param costSurveyTemplateHeadersList
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "批量新增成本调查表头子表数据", httpMethod = "POST", notes = "批量新增成本调查表头子表数据")
	@PostMapping(value = "/batchSave")
	public CommonResult<String> batchSave(@ApiParam(name = "costSurveyTemplateHeadersList", value = "成本调查表头子表对象列表", required = true)
										  @RequestBody List<CostSurveyTemplateHeaders> costSurveyTemplateHeadersList) throws Exception {

		return CommonResult.<String>ok().message("批量新增成本调查表头子表数据成功");
	}

}
