package com.hotent.enterpriseDeclare.manager.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hotent.base.manager.impl.BaseManagerImpl;
import com.hotent.base.util.StringUtil;
import com.hotent.enterpriseDeclare.dao.CostSurveyTemplateUploadDataDao;
import com.hotent.enterpriseDeclare.manager.CostSurveyTemplateUploadDataManager;
import com.hotent.enterpriseDeclare.model.CostSurveyTemplateUploadData;
import com.hotent.project.req.ComprehensiveStatisticsReq;
import com.hotent.project.vo.CostSurveysVo;
import com.hotent.surveyinfo.manager.CostSurveyTemplateUploadManager;
import com.hotent.surveyinfo.model.CostSurveyTemplateUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 成本调查表模板上传数据表 服务实现类
 *
 * @company 山西清众科技股份有限公司
 * @author 超级管理员
 * @since 2025-01-XX
 */
@Service
public class CostSurveyTemplateUploadDataManagerImpl extends BaseManagerImpl<CostSurveyTemplateUploadDataDao, CostSurveyTemplateUploadData> implements CostSurveyTemplateUploadDataManager {

    @Autowired
    private CostSurveyTemplateUploadDataDao costSurveyTemplateUploadDataDao;

    @Autowired
    private CostSurveyTemplateUploadManager costSurveyTemplateUploadManager;

    @Override
    public CostSurveyTemplateUploadData getDetail(String id) {
        CostSurveyTemplateUploadData data = this.get(id);
        return data;
    }

    @Override
    @Transactional
    public void createOrUpdate(CostSurveyTemplateUploadData costSurveyTemplateUploadData) {
        //新建或更新
        this.saveOrUpdate(costSurveyTemplateUploadData);
    }

    @Override
    public List<CostSurveyTemplateUploadData> listByUploadId(String uploadId) {
        return costSurveyTemplateUploadDataDao.selectByUploadId(uploadId);
    }

    @Override
    public List<CostSurveyTemplateUploadData> listByUploadIdAndAuditedUnitId(String uploadId, String periodRecordId) {
        return costSurveyTemplateUploadDataDao.selectByUploadIdAndAuditedUnitId(uploadId, periodRecordId);
    }

    @Override
    public List<CostSurveyTemplateUploadData> listByRowid(String rowid) {
        return costSurveyTemplateUploadDataDao.selectByRowid(rowid);
    }

    @Override
    @Transactional
    public void saveData(List<CostSurveyTemplateUploadData> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return;
        }

        // 从第一条数据中提取信息
        CostSurveyTemplateUploadData firstData = dataList.get(0);
        String refId = firstData.getUploadId();
        if(refId==null){
            refId = firstData.getRefId();
        }
        if (refId==null){
            refId = firstData.getTaskId();
        }
        String type = firstData.getType();
        String taskId = firstData.getTaskId();

        // 获取periodRecordId（动态表使用）
        String periodRecordId = firstData.getPeriodRecordId();
        
        // 先删除该refId下的数据
        if (StringUtil.isNotEmpty(periodRecordId)) {
            // 动态表：删除指定periodRecordId的数据
            deleteByRefIdAndPeriodRecordId(refId, type, periodRecordId);
        } else {
            // 固定表和单记录：删除所有数据
            deleteByRefId(refId, type);
        }

        // 设置公共字段并保存新数据
        List<CostSurveyTemplateUploadData> saveList = new ArrayList<>();
        for (CostSurveyTemplateUploadData data : dataList) {
            if (data.getRowid() == null || data.getRowid().isEmpty() || 
                data.getRkey() == null || data.getRkey().isEmpty()) {
                continue;
            }

            // 设置refId
            data.setRefId(refId);
            data.setTaskId(taskId);
            data.setType(type);
            if (StringUtil.isNotEmpty(periodRecordId)) {
                data.setPeriodRecordId(periodRecordId);
            }
            if (data.getIsDeleted() == null) {
                data.setIsDeleted("0");
            }
            if (data.getRvalue() == null) {
                data.setRvalue("");
            }
            saveList.add(data);
        }

        // 批量保存
        if (!saveList.isEmpty()) {
            this.saveBatch(saveList);
        }
    }


    @Override
    @Transactional
    public void deleteByUploadId(String uploadId) {
        deleteByRefId(uploadId, "1");
    }

    @Override
    public List<CostSurveysVo> analyze(List<String> taskIds) {

        return costSurveyTemplateUploadDataDao.analyze(taskIds);
    }

    /**
     * 根据refId删除数据
     * @param refId 关联ID
     * @param type 类型
     */
    private void deleteByRefId(String refId, String type) {
        QueryWrapper<CostSurveyTemplateUploadData> wrapper = new QueryWrapper<>();
        wrapper.eq("ref_id", refId);
        wrapper.eq("type", type);
        wrapper.eq("is_deleted", "0");
        this.remove(wrapper);
    }

    /**
     * 根据refId和监审期间记录ID删除数据
     * @param refId 关联ID
     * @param type 类型
     * @param periodRecordId 监审期间记录ID
     */
    private void deleteByRefIdAndPeriodRecordId(String refId, String type, String periodRecordId) {
        QueryWrapper<CostSurveyTemplateUploadData> wrapper = new QueryWrapper<>();
        wrapper.eq("ref_id", refId);
        wrapper.eq("type", type);
        wrapper.eq("period_record_id", periodRecordId);
        wrapper.eq("is_deleted", "0");
        this.remove(wrapper);
    }
}

