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.query.PageList;
import com.hotent.base.util.StringUtil;
import com.hotent.common.CrudService;
import com.hotent.resp.PageResp;
import com.hotent.surveyinfo.dao.*;
import com.hotent.surveyinfo.manager.CostSurveyFdTemplateManager;
import com.hotent.surveyinfo.manager.CostSurveyFdTemplateVersionManager;
import com.hotent.surveyinfo.manager.CostSurveyTemplateManager;
import com.hotent.surveyinfo.manager.CostSurveyTemplateVersionManager;
import com.hotent.surveyinfo.model.*;
import com.hotent.surveyinfo.req.ConstSurveyFdPageParam;
import com.hotent.surveyinfo.req.ConstSurveyFdPageReq;
import com.hotent.surveyinfo.req.ConstSurveyPageReq;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.manager.UserManager;
import com.hotent.uc.model.User;
import com.hotent.uc.util.ContextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 财务数据表模板表 前端控制器
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-19
 */
@RestController
@RequestMapping("/costSurveyFdTemplate/v1/")
@Api(tags = "财务数据表")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostSurveyFdTemplateController extends BaseController<CostSurveyFdTemplateManager, CostSurveyFdTemplate> {
	@Autowired
	 CostSurveyFdTemplateManager constbaseService;
	@Autowired
	CostSurveyFdTemplateVersionManager costSurveyTemplateVersionMapper;
	@Autowired
	CostSurveyFdTemplateDao costSurveyTemplateDao;

	@Autowired
	CostSurveyFdTemplateHeadersDao costSurveyTemplateHeadersDao;
	@Autowired
	CostSurveyFdTemplateItemsDao costSurveyTemplateItemsDao;

	@Autowired
	private UserManager userService;
	// 创建通用服务实例
	private final CrudService crudService = new CrudService();
	/**
	 * 获取所有财务数据表模板数据
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/listAll")
	@ApiOperation(value="获取登录人创建的所有财务数据表模板数据", httpMethod = "GET", notes = "获取所有财务数据表模板数据集合")
	public PageResp<CostSurveyFdTemplate> listAll(ConstSurveyFdPageReq req) throws Exception{
		return crudService.pageQuery(req, constbaseService::getCostSurveyList);
	}

	@PostMapping(value="/listPage")
	@ApiOperation(value="获取登录人创建的所有财务数据表模板数据", httpMethod = "POST", notes = "获取所有财务数据表模板数据集合")
	public PageList<CostSurveyFdTemplate> listPage(@RequestBody ConstSurveyFdPageParam param) throws Exception{
		return constbaseService.listPage(param);
	}

	/**
	 * 获取所有现行版启用的财务数据表模板数据
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/allcurrentCostSurveyList")
	@ApiOperation(value="获取所有现行版启用的财务数据表模板数据", httpMethod = "GET", notes = "获取所有财务数据表模板数据集合")
	public PageResp<CostSurveyFdTemplate> allcurrentCostSurveyList(ConstSurveyFdPageReq req) throws Exception{
		return crudService.pageQuery(req, constbaseService::getAllcurrentCostSurveyList);
	}


	/**
	 * 根据id获取财务数据表模板表数据详情
	 * @param id
	 * @return
	 * @throws Exception
	 * ModelAndView
	 */

	@GetMapping(value="/getDetail")
	@ApiOperation(value="根据id获取财务数据表模板表数据详情",httpMethod = "GET",notes = "根据id获取财务数据表模板表数据详情")
	public CommonResult<CostSurveyFdTemplate> getDetail(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam(required=true) String id) throws Exception{
		return CommonResult.<CostSurveyFdTemplate>ok().value(baseService.getDetail(id));
	}
    /**
	 * 新增,更新财务数据表模板表
	 * @param costSurveyTemplate
	 * @throws Exception
	 * @return
	 * @exception
	 */
	@PostMapping(value="/save")
	@ApiOperation(value = "新增,更新财务数据表模板表数据", httpMethod = "POST", notes = "新增,更新财务数据表模板表数据")
	public CommonResult<String> save(@ApiParam(name="CostSurveyTemplate",value="财务数据表模板表对象", required = true)@RequestBody CostSurveyFdTemplate costSurveyTemplate) throws Exception{
		String msg = StringUtil.isEmpty(costSurveyTemplate.getSurveyTemplateId()) ? "添加财务数据表模板表成功" : "更新财务数据表模板表成功";
		if(StringUtil.isEmpty(costSurveyTemplate.getSurveyTemplateId()))
		{
			IUser user = ContextUtil.getCurrentUser();
			costSurveyTemplate.setCreateBy(user.getAccount());
			costSurveyTemplate.setCreateTime(LocalDateTime.now());
			costSurveyTemplate.setIsDelete( "0");
			costSurveyTemplate.setStatus("-1");
		}
		else{
			costSurveyTemplate.setUpdateBy(ContextUtil.getCurrentUser().getAccount());
			costSurveyTemplate.setUpdateTime(LocalDateTime.now());
		}
		User currentUser = ContextUtil.getCurrentUser();
		currentUser = userService.get(currentUser.getUserId());
		Integer dataScope = currentUser.getDataScope();
		if (dataScope == 0) {
			costSurveyTemplate.setAreaLevel("0");
			costSurveyTemplate.setAreaCode(currentUser.getProvinceCode());
		} else if (dataScope == 1){
			costSurveyTemplate.setAreaLevel("1");
			costSurveyTemplate.setAreaCode(currentUser.getCityCode());
		}else{
			costSurveyTemplate.setAreaLevel("2");
			costSurveyTemplate.setAreaCode(currentUser.getCountyCode());
		}
		baseService.createOrUpdate(costSurveyTemplate);
		return CommonResult.<String>ok().message(msg);
	}

	/**
	 * 根据id删除财务数据表模板数据
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "根据id删除财务数据表模板数据", httpMethod = "GET", 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 ids 要删除的ID列表
	 * @return 操作结果
	 * @throws Exception
	 */
	@ApiOperation(value = "批量删除财务数据表模板数据", httpMethod = "POST", notes = "批量删除财务数据表模板数据")
	@PostMapping(value = "/batchRemove")
	public CommonResult<String> batchRemove(@ApiParam(name = "ids", value = "业务对象主键列表", required = true) @RequestBody List<String> ids) throws Exception {
		if (ids == null || ids.isEmpty()) {
			return CommonResult.<String>error().message("删除失败：未选择任何数据");
		}

		try {
			baseService.batchRemove(ids);
			return CommonResult.<String>ok().message("成功删除" + ids.size() + "条数据");
		} catch (Exception e) {
			return CommonResult.<String>error().message("删除失败：" + e.getMessage());
		}
	}

	/**
	 * 获取除去指定ID外的所有财务数据表模板列表
	 * @param surveyTemplateId 要排除的模板ID
	 * @return 财务数据表模板列表
	 * @throws Exception
	 */
	@GetMapping(value="/listExcludeId")
	@ApiOperation(value="计算公式-选择财务数据表", httpMethod = "GET", notes = "获取除去指定ID外的所有财务数据表模板列表")
	public CommonResult<List<CostSurveyFdTemplate>> listExcludeId(
			@ApiParam(name="surveyTemplateId", value="要排除的模板ID", required = false)
			@RequestParam(required = false) String surveyTemplateId) throws Exception {

		CostSurveyFdTemplate queryCondition = new CostSurveyFdTemplate();
		queryCondition.setStatus("0");//启用状态的财务数据表模板
		queryCondition.setTemplateType("2"); // 模板类型为固定表
//		IUser user = ContextUtil.getCurrentUser();
//		queryCondition.setCreateBy(user.getAccount());
		// 这里可以根据业务需要设置其他查询条件
		List<CostSurveyFdTemplate> allTemplates = costSurveyTemplateDao.selectByCondition(queryCondition);

		// 如果提供了excludeId，则过滤掉该ID的记录
		if (surveyTemplateId != null && !surveyTemplateId.isEmpty()) {
			allTemplates = allTemplates.stream()
					.filter(template -> !surveyTemplateId.equals(template.getSurveyTemplateId()))
					.collect(Collectors.toList());
		}

		return CommonResult.<List<CostSurveyFdTemplate>>ok().value(allTemplates);
	}

	/**
	 * 导出财务数据表Excel模板
	 * @param templateId 模板ID
	 * @param response HTTP响应对象
	 * @throws Exception 异常
	 */
	@GetMapping(value="/exportExcelTemplate")
	@ApiOperation(value="导出财务数据表Excel模板", httpMethod = "GET", notes = "导出Excel模板并填充内容")
	public void exportExcelTemplate(
			@ApiParam(name="templateId", value="模板ID", required = true)
			@RequestParam String templateId,
			HttpServletResponse response) throws Exception {

		// 获取当前启用版本
		CostSurveyFdTemplateVersion currentVersion = costSurveyTemplateVersionMapper.selectCurrentVersion(templateId);

		if (currentVersion == null) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "未找到启用的模板版本");
			return;
		}

		// 获取表头信息
		List<CostSurveyFdTemplateHeaders> headersList = costSurveyTemplateHeadersDao.selectBySurveyTemplateIdAndVersion(templateId, currentVersion.getId());

		// 获取数据项信息
		List<CostSurveyFdTemplateItems> itemsList = costSurveyTemplateItemsDao.selectBySurveyTemplateIdAndVersion(templateId, currentVersion.getId());

		// 创建Excel工作簿
		Workbook workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet(currentVersion.getSurveyTemplateName());

		// 创建表头行
		Row headerRow = sheet.createRow(0);

		// 按照orderNum排序表头
		headersList.sort(Comparator.comparing(CostSurveyFdTemplateHeaders::getOrderNum,
				Comparator.nullsLast(Comparator.naturalOrder())));

		// 根据表头信息创建Excel列标题
		for (int i = 0; i < headersList.size(); i++) {
			CostSurveyFdTemplateHeaders header = headersList.get(i);
			Cell cell = headerRow.createCell(i);
			cell.setCellValue(header.getFieldName());
		}

		// 填充数据行（示例数据）
		if (!itemsList.isEmpty()) {
			// 按orderNum排序数据项
			itemsList.sort(Comparator.comparing(CostSurveyFdTemplateItems::getOrderNum,
					Comparator.nullsLast(Comparator.naturalOrder())));

			// 创建示例行
			Row dataRow = sheet.createRow(1);
			for (int i = 0; i < headersList.size(); i++) {
				CostSurveyFdTemplateHeaders header = headersList.get(i);
				Cell cell = dataRow.createCell(i);

				// 查找对应的数据项
				for (CostSurveyFdTemplateItems item : itemsList) {
					if (item.getHeadersId().equals(header.getId())) {
						cell.setCellValue(item.getRvalue() != null ? item.getRvalue() : "");
						break;
					}
				}
			}
		}

		// 自动调整列宽
		for (int i = 0; i < headersList.size(); i++) {
			sheet.autoSizeColumn(i);
		}

		// 设置响应头
		response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Disposition", "attachment; filename=" +
				URLEncoder.encode(currentVersion.getSurveyTemplateName(), "UTF-8") + ".xlsx");

		// 写入响应输出流
		workbook.write(response.getOutputStream());
		workbook.close();
	}

	/**
	 * 根据监管目录ID查询所有现行版本的所有财务数据表模板信息
	 * @param catalogId 监管目录ID
	 * @return 财务数据表模板列表
	 * @throws Exception
	 */
	@GetMapping(value="/listByCatalogId")
	@ApiOperation(value="根据监管目录ID查询所有现行版本的财务数据表模板", httpMethod = "GET", notes = "根据监管目录ID查询所有现行版本的财务数据表模板信息")
	public CommonResult<List<CostSurveyFdTemplate>> listByCatalogId(
			@ApiParam(name="catalogId", value="监管目录ID", required = true)
			@RequestParam String catalogId) throws Exception {

		// 查询指定目录下的所有启用状态的模板
		CostSurveyFdTemplate queryCondition = new CostSurveyFdTemplate();
		queryCondition.setCatalogId(catalogId);
		queryCondition.setStatus("0"); // 启用状态

		List<CostSurveyFdTemplate> templates = costSurveyTemplateDao.selectByCondition(queryCondition);

		// 为每个模板获取其现行版本信息
//		for (CostSurveyFdTemplate template : templates) {
//			CostSurveyFdTemplateVersion currentVersion = costSurveyTemplateVersionMapper.selectCurrentVersion(template.getSurveyTemplateId());
//			if (currentVersion != null) {
//				template.setVersionNo(currentVersion.getVersionNo());
//			}
//		}

		return CommonResult.<List<CostSurveyFdTemplate>>ok().value(templates);
	}

	/**
	 * 状态切换方法
	 * 当状态为-1(草稿)时启用为0(启用)
	 * 当状态为0(启用)或1(停用)时可以相互切换
	 * @param id 财务数据表模板ID
	 * @return 操作结果
	 * @throws Exception
	 */
	@ApiOperation(value = "状态切换", httpMethod = "POST", notes = "根据当前状态进行切换：草稿(-1)可启用为启用(0)，启用(0)和停用(1)可相互切换")
	@PostMapping(value = "/enable")
	public CommonResult<String> enable(
			@ApiParam(name = "id", value = "财务数据表模板ID", required = true)
			@RequestParam String id) throws Exception {

		CostSurveyFdTemplate template = baseService.get(id);
		if (template == null) {
			return CommonResult.<String>error().message("未找到指定的财务数据表模板");
		}

		String currentStatus = template.getStatus();
		String newStatus = null;
		String message = null;

		// 根据当前状态决定切换到什么状态
		if ("-1".equals(currentStatus)) {
			// 草稿状态切换到启用状态
			newStatus = "0";
			message = "财务数据表模板启用成功";

			// 检查是否已经有现行版本
			CostSurveyFdTemplateVersion currentVersion = costSurveyTemplateVersionMapper.selectCurrentVersion(id);
			if (currentVersion == null) {
				return CommonResult.<String>error().message("启用失败：该模板没有现行版本");
			}
		} else if ("0".equals(currentStatus)) {
			// 启用状态切换到停用状态
			newStatus = "1";
			message = "财务数据表模板停用成功";
		} else if ("1".equals(currentStatus)) {
			// 停用状态切换到启用状态
			newStatus = "0";
			message = "财务数据表模板启用成功";
		} else {
			return CommonResult.<String>error().message("不支持的状态切换操作");
		}

		// 更新状态
		template.setStatus(newStatus);
		template.setUpdateTime(LocalDateTime.now());
		template.setUpdateBy(ContextUtil.getCurrentUser().getAccount());

		baseService.createOrUpdate(template);

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



	/**
	 * 获取所有模板类型为固定表的所有启用成本调查表数据
	 * @return 启用的固定表类型成本调查表列表
	 * @throws Exception
	 */
	@GetMapping(value="/listFixedEnabled")
	@ApiOperation(value="获取所有模板类型为固定表的所有启用成本调查表数据", httpMethod = "GET", notes = "获取所有模板类型为固定表的所有启用成本调查表数据")
	public CommonResult<List<CostSurveyFdTemplate>> listFixedEnabled() throws Exception {
		CostSurveyFdTemplate queryCondition = new CostSurveyFdTemplate();
		queryCondition.setStatus("0"); // 启用状态
		queryCondition.setTemplateType("2"); // 模板类型为固定表

		List<CostSurveyFdTemplate> templates = costSurveyTemplateDao.selectByCondition(queryCondition);
		return CommonResult.<List<CostSurveyFdTemplate>>ok().value(templates);
	}
//
//	// 数据录入
//	@PostMapping("/save-data")
//	@ApiOperation(value = "数据录入", httpMethod = "POST", notes = "数据录入")
//	public CommonResult<String> saveSurveyData(@RequestBody CostSurveyData data) {
//
//
//		try {
//			baseService.saveSurveyData(data);
//			return CommonResult.<String>ok().message("数据录入成功");
//		} catch (Exception e) {
//			return CommonResult.<String>error().message("数据录入失败：" + e.getMessage());
//		}
//
//	}





}
