package com.hotent.surveyinfo.controller;


import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.surveyinfo.manager.CostSurveyTemplateManager;
import com.hotent.surveyinfo.model.CostSurveyTemplate;
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.*;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.StringUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.hotent.base.controller.BaseController;
import com.hotent.surveyinfo.model.CostSurveyTemplateVersion;
import com.hotent.surveyinfo.manager.CostSurveyTemplateVersionManager;

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

/**
 * 成本调查表版本 前端控制器
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-19
 */
@RestController
@RequestMapping("/costSurveyTemplateVersion/v1/")
@Api(tags = "成本调查历史版本")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostSurveyTemplateVersionController extends BaseController<CostSurveyTemplateVersionManager, CostSurveyTemplateVersion> {
	@Autowired
	CostSurveyTemplateVersionManager costSurveyTemplateVersionMapper;
	@Autowired
	CostSurveyTemplateManager costSurveyTemplateMapper;
	/**
	 * 根据模板ID和状态查询版本数据
	 * @param surveyTemplateId 关联的成本调查表ID
	 * @param status 状态：-1草稿 0现行 1历史（默认为-1草稿状态）
	 * @return 版本列表
	 */
	@GetMapping(value = "/listByTemplateId")
	@ApiOperation(value = "根据模板ID和状态查询版本数据", httpMethod = "GET", notes = "根据模板ID和状态查询版本数据")
	public CommonResult<List<CostSurveyTemplateVersion>> listByTemplateId(
			@ApiParam(name = "surveyTemplateId", value = "关联的成本调查表ID", required = true)
			@RequestParam(required = true) String surveyTemplateId,
			@ApiParam(name = "status", value = "状态：-1草稿 0现行 1历史（默认为-1）", required = false)
			@RequestParam(required = false, defaultValue = "") String status) throws Exception {

		List<CostSurveyTemplateVersion> versions = baseService.selectByTemplateIdAndStatus(surveyTemplateId, status);
		return CommonResult.<List<CostSurveyTemplateVersion>>ok().value(versions);
	}



	/**
	 * 根据id获取成本调查表版本数据详情
	 * @param id
	 * @return
	 * @throws Exception 
	 * ModelAndView
	 */
	@GetMapping(value="/getDetail")
	@ApiOperation(value="根据id获取成本调查表版本数据详情",httpMethod = "GET",notes = "根据id获取成本调查表版本数据详情")
	public CommonResult<CostSurveyTemplateVersion> getDetail(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam(required=true) String id) throws Exception{
		return CommonResult.<CostSurveyTemplateVersion>ok().value(baseService.getDetail(id));
	}
    /**
	 * 新增,更新成本调查表版本
	 * @param costSurveyTemplateVersion
	 * @throws Exception 
	 * @return
	 * @exception 
	 */
	@PostMapping(value="/save")
	@ApiOperation(value = "新增,更新成本调查表版本数据", httpMethod = "POST", notes = "新增,更新成本调查表版本数据")
	public CommonResult<String> save(@ApiParam(name="CostSurveyTemplateVersion",value="成本调查表版本对象", required = true)@RequestBody CostSurveyTemplateVersion costSurveyTemplateVersion) throws Exception{
		String msg = StringUtil.isEmpty(costSurveyTemplateVersion.getId()) ? "添加成本调查表版本成功" : "更新成本调查表版本成功";
		if(StringUtil.isEmpty(costSurveyTemplateVersion.getId()))
		{
			IUser user = ContextUtil.getCurrentUser();
			costSurveyTemplateVersion.setId( UUID.randomUUID().toString());
			costSurveyTemplateVersion.setCreateTime(LocalDateTime.now());
			costSurveyTemplateVersion.setCreateBy(user.getAccount());
			costSurveyTemplateVersion.setStatus("-1");
			//获取版本号
			costSurveyTemplateVersion.setVersionNo(costSurveyTemplateVersionMapper.generateVersionNumber());
		}
		else{
			IUser user = ContextUtil.getCurrentUser();

			costSurveyTemplateVersion.setUpdateTime(LocalDateTime.now());
			costSurveyTemplateVersion.setUpdateBy(user.getAccount());
		}

		baseService.createOrUpdate(costSurveyTemplateVersion);
		return CommonResult.<String>ok().message(msg);
	}
	// 版本发布
	@PostMapping("/publish-version")
	@ApiOperation(value = "版本发布", httpMethod = "POST", notes = "版本发布")
	public CommonResult<String>  publishVersion(@RequestBody CostSurveyTemplateVersion version) {

// 1. 检查是否存在现行版本
		CostSurveyTemplateVersion currentVersion =
				costSurveyTemplateVersionMapper.selectCurrentVersion(version.getSurveyTemplateId());

		if (currentVersion != null) {
			// 2. 将现有现行版本状态改为"历史"
			currentVersion.setStatus("1"); // 1-历史
			currentVersion.setUpdateTime(LocalDateTime.now());
			costSurveyTemplateVersionMapper.updateById(currentVersion);
		}

		// 3. 设置新版本为"现行"
		version.setStatus("0"); // 0-现行
		version.setCreateTime(LocalDateTime.now());
		version.setUpdateTime(LocalDateTime.now());
		costSurveyTemplateVersionMapper.updateById(version);

		// 4. 更新模板状态
		CostSurveyTemplate template = costSurveyTemplateMapper.getDetail(version.getSurveyTemplateId());
		if (template != null) {
			template.setStatus("0"); // 启用
			template.setUpdateTime(LocalDateTime.now());
			costSurveyTemplateMapper.updateById(template);
		}

		return CommonResult.<String>ok().message("版本发布成功");
	}



	// 版本切换
	@PostMapping("/switch-version/{versionId}")
	@ApiOperation(value = "版本切换", httpMethod = "POST", notes = "版本切换")
	public CommonResult<String>  switchVersion(@PathVariable String versionId) {
		// 1. 获取要切换的版本
		CostSurveyTemplateVersion targetVersion =
				baseService.getDetail(versionId.toString());

		if (targetVersion == null) {
			throw new IllegalArgumentException("版本不存在");
		}

		// 2. 检查是否已是现行版本
		if ("0".equals(targetVersion.getStatus())) {
			return CommonResult.<String>ok().message("已是现行版本，无需切换"); // 已是现行版本，无需切换
		}

		// 3. 获取当前现行版本
		CostSurveyTemplateVersion currentVersion =
				costSurveyTemplateVersionMapper.selectCurrentVersion(targetVersion.getSurveyTemplateId());

		if (currentVersion != null) {
			// 4. 将当前现行版本改为"历史"
			currentVersion.setStatus("1"); // 1-历史
			currentVersion.setUpdateTime(LocalDateTime.now());
			costSurveyTemplateVersionMapper.updateById(currentVersion);
		}

		// 5. 将目标版本设置为"现行"
		targetVersion.setStatus("0"); // 0-现行
		targetVersion.setUpdateTime(LocalDateTime.now());
		costSurveyTemplateVersionMapper.updateById(targetVersion);

		// 6. 更新模板状态
		CostSurveyTemplate template = costSurveyTemplateMapper.getDetail(targetVersion.getSurveyTemplateId());
		if (template != null) {
			template.setStatus("0"); // 启用
			template.setUpdateTime(LocalDateTime.now());
			costSurveyTemplateMapper.updateById(template);
		}

		return CommonResult.<String>ok().message("版本切换成功");
	}


	/**
	 * 批量删除历史版本和草稿版本
	 * @param versionIds 版本ID列表
	 * @return 删除结果
	 */
	@PostMapping(value="/batchDelete")
	@ApiOperation(value = "批量删除历史版本和草稿版本", httpMethod = "POST", notes = "批量删除历史版本和草稿版本")
	public CommonResult<String> batchDelete(
			@ApiParam(name="versionIds",value="版本ID列表", required = true)
			@RequestBody List<String> versionIds) throws Exception {

		// 检查是否有版本ID传入
		if (versionIds == null || versionIds.isEmpty()) {
			return CommonResult.<String>error().message("请选择要删除的版本");
		}

		// 查询所有要删除的版本
		List<CostSurveyTemplateVersion> versions = baseService.listByIds(versionIds);

		// 过滤出可删除的版本（草稿状态-1 或 历史状态1）
		List<String> deleteIds = versions.stream()
				.filter(version -> "-1".equals(version.getStatus()) || "1".equals(version.getStatus()))
				.map(CostSurveyTemplateVersion::getId)
				.collect(java.util.stream.Collectors.toList());

		// 检查是否有可删除的版本
		if (deleteIds.isEmpty()) {
			return CommonResult.<String>error().message("没有可删除的草稿或历史版本");
		}

		// 检查是否尝试删除现行版本
		long currentVersionCount = versions.stream()
				.filter(version -> "0".equals(version.getStatus()))
				.count();

		// 执行批量删除操作
		baseService.removeByIds(deleteIds);

		String message = "成功删除" + deleteIds.size() + "个版本";
		if (currentVersionCount > 0) {
			message += "（已过滤掉" + currentVersionCount + "个现行版本）";
		}

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


}
