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.PinyinUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.surveyinfo.dao.CostSurveyTemplateHeadersDao;
import com.hotent.surveyinfo.dao.CostVerifyTemplateHeadersDao;
import com.hotent.surveyinfo.manager.*;
import com.hotent.surveyinfo.model.*;
import com.hotent.surveyinfo.model.dto.BatchHeadersItemsRequest;
import com.hotent.surveyinfo.model.dto.BatchVerifyHeadersItemsRequest;
import com.hotent.uc.api.model.IUser;
import com.hotent.uc.util.ContextUtil;
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.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 成本核定表头子表 前端控制器
 *
 * @author 超级管理员
 * @company 山西清众科技股份有限公司
 * @since 2025-09-19
 */
@RestController
@RequestMapping("/costVerifyTemplateHeaders/v1/")
@Api(tags = "成本核定表头")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostVerifyTemplateHeadersController extends BaseController<CostVerifyTemplateHeadersManager, CostVerifyTemplateHeaders> {
    @Autowired
    CostVerifyTemplateHeadersDao costSurveyTemplateHeadersDao;
    @Autowired
    CostVerifyTemplateManager basemanager;
    @Autowired
    private CostVerifyTemplateItemsManager costSurveyTemplateItemsManager;
    @Autowired
    CostVerifyTemplateHeadersManager costVerifyTemplateHeadersManager;

    /**
     * 根据成本核定表id获取成本核定表头子表数据列表
     *
     * @param surveyTemplateId
     * @return
     */
    @ApiOperation(value = "根据成本核定表id获取成本核定表头子表数据列表", httpMethod = "GET", notes = "根据成本核定表id获取成本核定表头子表数据列表")
    @GetMapping("/getlistBySurveyTemplateId")
    public CommonResult<List<CostVerifyTemplateHeaders>> getlistBySurveyTemplateId(@RequestParam String surveyTemplateId) {

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

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


    /**
     * 根据成本核定表id和版本号获取表头数据列表
     *
     * @param surveyTemplateId 成本核定表id
     * @param version          版本号
     * @return 表头数据列表
     */
    @ApiOperation(value = "根据成本核定表id和版本号获取表头数据列表", httpMethod = "GET", notes = "根据成本核定表id和版本号获取表头数据列表")
    @GetMapping("/getlistBySurveyTemplateIdAndVersion")
    public CommonResult<List<CostVerifyTemplateHeaders>> getlistBySurveyTemplateIdAndVersion(@ApiParam(name = "surveyTemplateId", value = "成本核定表id", required = true) @RequestParam String surveyTemplateId, @ApiParam(name = "version", value = "版本号", required = true) @RequestParam String version) {

        List<CostVerifyTemplateHeaders> headersList = costSurveyTemplateHeadersDao.selectBySurveyTemplateIdAndVersion(surveyTemplateId, version);

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

    /**
     * 根据成本核定表id获取现行版的表头数据列表
     * @param surveyTemplateId 成本核定表id
     * @return 表头数据列表
     */
//	@ApiOperation(value="根据成本核定表id获取现行版的表头数据列表", httpMethod = "GET", notes = "根据成本核定表id和版本号获取表头数据列表")
//	@GetMapping("/getlistBySurveyTemplateIdcurrentversion")
//	public CommonResult<List<CostVerifyTemplateHeaders>> 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<CostVerifyTemplateHeaders> getDetail(@ApiParam(name = "id", value = "业务对象主键", required = true) @RequestParam(required = true) String id) throws Exception {
        return CommonResult.<CostVerifyTemplateHeaders>ok().value(baseService.getDetail(id));
    }

    /**
     * 新增,更新成本核定表头子表
     *
     * @param costSurveyTemplateHeaders
     * @return
     * @throws Exception
     * @throws
     */
    @PostMapping(value = "/save")
    @ApiOperation(value = "新增或更新成本核定表头子表数据", httpMethod = "POST", notes = "新增或更新成本核定表头子表数据")
    public CommonResult<String> save(@ApiParam(name = "CostSurveyTemplateHeaders", value = "成本核定表头子表对象", required = true) @RequestBody CostVerifyTemplateHeaders 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 BatchVerifyHeadersItemsRequest request) throws Exception {

        String costVerifyTemplateId = request.getCostVerifyTemplateId();


        List<CostVerifyTemplateHeaders> headersList = request.getHeadersList();
        List<CostVerifyTemplateItems> itemsList = request.getItemsList();
        List<CostVerifyTemplateHeaders> 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 (CostVerifyTemplateHeaders 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 (CostVerifyTemplateHeaders header : deleteHeadersList) {
                if (StringUtil.isNotEmpty(header.getId())) {
                    baseService.remove(header.getId());

                }
            }
        }


        // 处理指标项数据，动态设置 headersId
        if (itemsList != null && !itemsList.isEmpty()) {
            if (itemsList.size() > 0) {
                costSurveyTemplateItemsManager.deleteBySurveyTemplateId(costVerifyTemplateId);
            }


            for (CostVerifyTemplateItems item : itemsList) {
                // 检查是否已设置 headersId
                if (StringUtil.isEmpty(item.getHeadersId())) {
                    item.setHeadersId(headersList.stream().filter(h -> h.getFieldName().equals(item.getRkey())).findFirst().map(CostVerifyTemplateHeaders::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<CostVerifyTemplateHeaders> costSurveyTemplateHeadersList) throws Exception {

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

    /**
     * 根据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层方法删除数据
        costSurveyTemplateHeadersDao.deleteByCostVerifyTemplateId(costVerifyTemplateId);

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

}
