package com.hotent.surveyinfo.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.CostSurveyTemplateManager;
import com.hotent.surveyinfo.manager.CostSurveyTemplateVersionManager;
import com.hotent.surveyinfo.manager.CostVerifyTemplateManager;
import com.hotent.surveyinfo.model.*;
import com.hotent.surveyinfo.req.ConstSurveyFdPageParam;
import com.hotent.surveyinfo.req.ConstSurveyPageReq;
import com.hotent.surveyinfo.req.ConstVerifyPageParam;
import com.hotent.surveyinfo.req.ConstVerifyPageReq;
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.*;
import java.util.stream.Collectors;

/**
 * 成本核定表模板表 前端控制器
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-09-19
 */
@RestController
@RequestMapping("/costVerifyTemplate/v1/")
@Api(tags = "成本核定")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostVerifyTemplateController extends BaseController<CostVerifyTemplateManager, CostVerifyTemplate> {
	@Autowired
	 CostVerifyTemplateManager constbaseService;

	@Autowired
	CostVerifyTemplateDao costSurveyTemplateDao;
	@Autowired
	CostVerifyTemplateItemsDao costVerifyTemplateItemsDao;
	@Autowired
	CostVerifyTemplateHeadersDao costVerifyTemplateHeadersDao;

	@Autowired
	CostSurveyTemplateVersionManager costSurveyTemplateVersionMapper;

	@Autowired
	private UserManager userService;


	// 创建通用服务实例
	private final CrudService crudService = new CrudService();
	/**
	 * 获取所有成本核定表模板数据
	 * @return
	 * @throws Exception
	 */
	@GetMapping(value="/listAll")
	@ApiOperation(value="获取所有成本核定表模板数据", httpMethod = "GET", notes = "获取所有成本核定表模板数据集合")
	public PageResp<CostVerifyTemplate> listAll(ConstVerifyPageReq req) throws Exception{
		return crudService.pageQuery(req, constbaseService::getCostSurveyList);
	}

	@PostMapping(value="/listPage")
	@ApiOperation(value="获取所有成本核定表模板数据", httpMethod = "POST", notes = "获取所有成本核定表模板数据")
	public PageList<CostVerifyTemplate> listPage(@RequestBody ConstVerifyPageParam param) throws Exception{
		return constbaseService.listPage(param);
	}

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

		List<CostVerifyTemplate> enabledTemplates = costSurveyTemplateDao.selectByCondition(queryCondition);
		return CommonResult.<List<CostVerifyTemplate>>ok().value(enabledTemplates);
	}

	/**
	 * 生成核定模板数据
	 * @param templateId 模板ID
	 * @param templatename 模板类型：1-成本调查固定表，其他-成本核定表
	 * @param catalogId    监审id
	 * @return 核定模板数据（包含表头和数据项）
	 * @throws Exception
	 */
	@GetMapping(value="/generateTemplateData")
	@ApiOperation(value="生成核定模板数据", httpMethod = "GET", notes = "根据模板ID和模板类型生成核定模板数据")
	public CommonResult<CostVerifyTemplate> generateTemplateData(
			@ApiParam(name="templateId", value="模板ID", required = true)
			@RequestParam String templateId,
			@ApiParam(name="templatename", value="模板名称", required = true)
			 String templatename,@ApiParam(name="catalogId", value="监审id", required = true)
			 String taskId,@ApiParam(name="taskId", value="任务id", required = false)
			@RequestParam String catalogId) throws Exception {


        //根据模板ID获取核定模板数据
		CostVerifyTemplate template = costSurveyTemplateDao.selectById(templateId);
		String tid = UUID.randomUUID().toString();
		template.setIsDelete("0");
		template.setSurveyTemplateName(templatename);
		template.setSurveyTemplateId(tid);
		template.setCreateBy(ContextUtil.getCurrentUser().getAccount());
		template.setCreateTime( LocalDateTime.now());
		template.setCreatetemplateid(templateId);
		template.setVersionNo(constbaseService.generateVersionNumber());
		template.setCatalogId(catalogId);
		template.setCreatemode("2");
		template.setCreatetemplateid(templateId);
		//新增修改后的模板数据
		costSurveyTemplateDao.insert(template);
		List<CostVerifyTemplateItems> itemsList = costVerifyTemplateItemsDao.selectByVerifyTemplateId(templateId,taskId);
		List<CostVerifyTemplateItems> updateitemsList=new ArrayList<>();
		// 从成本核定表获取启用状态的表头和数据项
		List<CostVerifyTemplateHeaders> headersList = costVerifyTemplateHeadersDao.selectBySurveyTemplateId(templateId);
		//将 headersList 保存到数据库中
		for (CostVerifyTemplateHeaders header : headersList) {
			String headerId = UUID.randomUUID().toString();
			header.setId(headerId);
			header.setSurveyTemplateId(tid);
			header.setCreateBy(ContextUtil.getCurrentUser().getAccount());
			header.setCreateTime( LocalDateTime.now());
			costVerifyTemplateHeadersDao.insert(header);
			if (itemsList != null && !itemsList.isEmpty()) {
				for (CostVerifyTemplateItems items : itemsList)
				{
					if (items.getHeadersId().equals(header.getId())){
						items.setHeadersId(headerId);
						updateitemsList.add(items);
					}

				}
			}

		}
// 3. 将updateitemsList数据依次写入 CostVerifyTemplateItems 表中
		if (updateitemsList != null && !updateitemsList.isEmpty()) {
			for (CostVerifyTemplateItems items : updateitemsList)
			{
				String itemId = UUID.randomUUID().toString();
				items.setId(itemId);
				items.setSurveyTemplateId(tid);
				items.setCreateBy(ContextUtil.getCurrentUser().getAccount());
				items.setCreateTime( LocalDateTime.now());
				costVerifyTemplateItemsDao.insert(items);
			}
		}
		return CommonResult.<CostVerifyTemplate>ok().value(template);
	}



	/**
	 * 根据id获取成本核定表模板表数据详情
	 * @param id
	 * @return
	 * @throws Exception
	 * ModelAndView
	 */
	@GetMapping(value="/getDetail")
	@ApiOperation(value="根据id获取成本核定表模板表数据详情",httpMethod = "GET",notes = "根据id获取成本核定表模板表数据详情")
	public CommonResult<CostVerifyTemplate> getDetail(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam(required=true) String id) throws Exception{
		return CommonResult.<CostVerifyTemplate>ok().value(baseService.getDetail(id));
	}

	/**
	 * 根据id获取成本核定表模板表数据详情
	 * @param id
	 * @return
	 * @throws Exception
	 * ModelAndView
	 */
	@GetMapping(value="/getDetailByTaskId")
	@ApiOperation(value="根据id获取成本核定表模板表数据详情",httpMethod = "GET",notes = "根据id获取成本核定表模板表数据详情")
	public CommonResult<CostVerifyTemplate> getDetailByTaskId(@ApiParam(name="id",value="业务对象主键", required = true)@RequestParam(required=true) String id) throws Exception{
		return CommonResult.<CostVerifyTemplate>ok().value(baseService.getOne(
				new QueryWrapper<CostVerifyTemplate>().eq("task_id", id).orderByDesc("create_time").last("limit 1")
		));
	}
    /**
	 * 新增,更新成本核定表模板表
	 * @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 CostVerifyTemplate 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());
		}
		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);
		costVerifyTemplateItemsDao.deleteByCostVerifyTemplateId( id);
		costVerifyTemplateHeadersDao.deleteByCostVerifyTemplateId( 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);
			for (int i = 0; i <ids.size() ; i++) {
				costVerifyTemplateItemsDao.deleteByCostVerifyTemplateId(ids.get(i));
				costVerifyTemplateHeadersDao.deleteByCostVerifyTemplateId(ids.get(i));
			}
			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<CostVerifyTemplate>> listExcludeId(
			@ApiParam(name="surveyTemplateId", value="要排除的模板ID", required = false)
			@RequestParam(required = false) String surveyTemplateId) throws Exception {

		CostVerifyTemplate queryCondition = new CostVerifyTemplate();
		queryCondition.setStatus("0");//启用状态的成本核定表模板

		IUser user = ContextUtil.getCurrentUser();
		queryCondition.setCreateBy(user.getAccount());
		// 这里可以根据业务需要设置其他查询条件
		List<CostVerifyTemplate> 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<CostVerifyTemplate>>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,
			@RequestParam String taskId,
			HttpServletResponse response) throws Exception {

		// 获取成本核定模板
		CostVerifyTemplate template = costSurveyTemplateDao.selectById(templateId);

		if (template == null) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "未找到指定的模板");
			return;
		}

		// 获取表头信息
		List<CostVerifyTemplateHeaders> headersList = costVerifyTemplateHeadersDao.selectBySurveyTemplateId(templateId);

		// 获取数据项信息
		List<CostVerifyTemplateItems> itemsList = costVerifyTemplateItemsDao.selectByVerifyTemplateId(templateId,taskId);

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

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

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

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

		// 按orderNum排序数据项
		itemsList.sort(Comparator.comparing(CostVerifyTemplateItems::getOrderNum,
				Comparator.nullsLast(Comparator.naturalOrder())));

		// 创建数据行（按orderNum分组）
		Map<Integer, List<CostVerifyTemplateItems>> itemsByOrder = itemsList.stream()
				.collect(Collectors.groupingBy(CostVerifyTemplateItems::getOrderNum));

		int rowNum = 1;
		for (Map.Entry<Integer, List<CostVerifyTemplateItems>> entry : itemsByOrder.entrySet()) {
			Row dataRow = sheet.createRow(rowNum++);

			for (int i = 0; i < headersList.size(); i++) {
				CostVerifyTemplateHeaders header = headersList.get(i);
				Cell cell = dataRow.createCell(i);

				// 查找对应的数据项
				for (CostVerifyTemplateItems item : entry.getValue()) {
					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(template.getSurveyTemplateName(), "UTF-8") + ".xlsx");

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

//
//	// 数据录入
//	@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());
//		}
//
//	}



	/**
	 * 状态切换方法
	 * 当状态为-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 {

		CostVerifyTemplate 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 = "成本核定表模板启用成功";
		} 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);
	}



}
