package com.hotent.enterpriseDeclare.controller.material;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.annotation.ApiGroup;
import com.hotent.base.constants.ApiGroupConsts;
import com.hotent.base.model.CommonResult;
import com.hotent.base.util.PinyinUtil;
import com.hotent.base.util.StringUtil;
import com.hotent.enterpriseDeclare.manager.CostAuditPeriodRecordManager;
import com.hotent.enterpriseDeclare.manager.CostSurveyTemplateUploadDataManager;
import com.hotent.enterpriseDeclare.model.CostAuditPeriodRecord;
import com.hotent.enterpriseDeclare.model.CostSurveyTemplateUploadData;
import com.hotent.project.manager.CostProjectApprovalManager;
import com.hotent.project.manager.CostProjectTaskManager;
import com.hotent.project.manager.CostProjectTaskMaterialManager;
import com.hotent.project.model.CostProjectApproval;
import com.hotent.project.model.CostProjectTask;
import com.hotent.surveyinfo.dao.CostSurveyTemplateHeadersDao;
import com.hotent.surveyinfo.dao.CostSurveyTemplateItemsDao;
import com.hotent.surveyinfo.dao.CostVerifyTemplateHeadersDao;
import com.hotent.surveyinfo.manager.*;
import com.hotent.surveyinfo.model.*;
import com.hotent.surveyinfo.model.dto.BatchVerifyHeadersItemsRequest;
import com.hotent.surveyinfo.model.dto.CostItemData;
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.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 核定表
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-01-27
 */
@RestController
@RequestMapping("/api/verify/Template/v1/")
@Api(tags = "成本调查表")
@ApiGroup(group = {ApiGroupConsts.GROUP_COST})
public class CostProjectTaskVerifyTemplateController {

    @Autowired
    private CostVerifyTemplateItemsManager costSurveyTemplateItemsManager;
    @Autowired
    CostVerifyTemplateHeadersManager costVerifyTemplateHeadersManager;



    @ApiOperation(value = "批量新增成本核定表头及指标项数据", httpMethod = "POST", notes = "先删除旧数据，再批量新增表头和指标项")
    @PostMapping(value = "/batchSaveOrUpdate")
    public CommonResult<String> batchSave(@RequestBody BatchVerifyHeadersItemsRequest request) throws Exception {

        String costVerifyTemplateId = request.getCostVerifyTemplateId();
        List<CostVerifyTemplateHeaders> headersList = request.getHeadersList();
        List<CostVerifyTemplateItems> itemsList = request.getItemsList();
        IUser user = ContextUtil.getCurrentUser();

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

        // 删除表头
        LambdaQueryWrapper<CostVerifyTemplateHeaders> headersWrapper = new LambdaQueryWrapper<>();
        headersWrapper.eq(CostVerifyTemplateHeaders::getSurveyTemplateId, costVerifyTemplateId);
        costVerifyTemplateHeadersManager.remove(headersWrapper);

        // 删除指标项
        LambdaQueryWrapper<CostVerifyTemplateItems> itemsWrapper = new LambdaQueryWrapper<>();
        itemsWrapper.eq(CostVerifyTemplateItems::getSurveyTemplateId, costVerifyTemplateId);
        costSurveyTemplateItemsManager.remove(itemsWrapper);

        // 新增表头（批量）
        if (headersList != null && !headersList.isEmpty()) {
            LocalDateTime now = LocalDateTime.now();
            for (CostVerifyTemplateHeaders header : headersList) {
                header.setId(UUID.randomUUID().toString());
                header.setFieldEname(PinyinUtil.getPinyin(header.getFieldName()));
                header.setCreateBy(user.getAccount());
                header.setCreateTime(now);
                header.setUpdateBy(user.getAccount());
                header.setUpdateTime(now);
                header.setSurveyTemplateId(costVerifyTemplateId);
            }
            costVerifyTemplateHeadersManager.saveBatch(headersList);
        }

        // 新增指标项（批量）
        if (itemsList != null && !itemsList.isEmpty()) {
            LocalDateTime now = LocalDateTime.now();
            // 先构建 fieldName -> id 映射
            Map<String, String> headerMap = headersList.stream()
                    .collect(Collectors.toMap(CostVerifyTemplateHeaders::getFieldName, CostVerifyTemplateHeaders::getId));

            for (CostVerifyTemplateItems item : itemsList) {
                item.setHeadersId(headerMap.get(item.getRkey()));
                item.setId(UUID.randomUUID().toString());
                item.setCreateBy(user.getAccount());
                item.setCreateTime(now);
                item.setUpdateBy(user.getAccount());
                item.setUpdateTime(now);
                item.setSurveyTemplateId(costVerifyTemplateId);
            }
            costSurveyTemplateItemsManager.saveBatch(itemsList);
        }

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



}

