
package com.lideeyunji.core.framework.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lideeyunji.core.framework.config.btncommand.param.ButtonParamImport;
import com.lideeyunji.core.framework.entity.ExcelFileDataEntity;
import com.lideeyunji.core.framework.entity.ExcelFileEntity;
import com.lideeyunji.core.framework.mapper.ExcelFileMapper;
import com.lideeyunji.core.framework.params.model.ExcelImportResultModel;
import com.lideeyunji.core.framework.service.IExcelFileDataService;
import com.lideeyunji.core.framework.service.IExcelFileService;
import com.lideeyunji.core.framework.service.IFormService;
import com.lideeyunji.core.framework.service.IFrameSqlService;
import com.lideeyunji.core.framework.utils.Func;
import com.lideeyunji.tool.framework.common.constant.lideeYunJiBaseConstant;
import com.lideeyunji.tool.framework.yunji.adapter.IlideeYunjiAdapter;
import com.lideeyunji.tool.framework.yunji.constant.lideeYunjiCodeConstant;
import com.lideeyunji.tool.framework.yunji.enums.YNEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * Excel文件相关
 */
@Service
public class ExcelFileServiceImpl extends ServiceImpl<ExcelFileMapper, ExcelFileEntity> implements IExcelFileService {

    @Autowired
    private IExcelFileDataService excelFileDataService;

    @Autowired
    private IFormService formService;

    @Autowired
    private IFrameSqlService sqlService;

    @Autowired
    private IlideeYunjiAdapter lideeYunJiAdapter;

    //保存Excel数据
    @Async("asyncPoolTaskExecutor")
    @Override
    public void saveExcelSync( long fileId,ButtonParamImport param) {
        IExcelFileService proxyService = SpringUtil.getBean(IExcelFileService.class);
        proxyService.saveExcel(fileId, param);
    }

    @DS(lideeYunJiBaseConstant.DS_lideeyunji)
    @DSTransactional(rollbackFor = Exception.class)
    public ExcelImportResultModel saveExcel(long fileId, ButtonParamImport param) {
        Long tenantId = lideeYunJiAdapter.getTenantId();
        Long onlineUserId = lideeYunJiAdapter.getOnlineUserId();
        Long onlineUserDeptId = lideeYunJiAdapter.getOnlineUserDeptId();
        LocalDateTime now = LocalDateTime.now();

        Long dbFormId = param.getDbFormId();
        List<Map<String, Object>> dataMapList = param.getDataMapList();
        String fileName = param.getFileName();


        //1.存入标题
        ExcelFileEntity fileEntity = new ExcelFileEntity();
        fileEntity.setId(fileId);
        fileEntity.setDbformId(dbFormId);
        fileEntity.setFileName(fileName);
        fileEntity.setImportState("0");//未导入
        fileEntity.setTotalNum(dataMapList.size());//总条数
        this.save(fileEntity);
        List<ExcelFileDataEntity> entityList = dataMapList.stream()
                .map(dataMap -> {
                    Integer stepSort = Func.getMap2Int(dataMap, lideeYunjiCodeConstant.EXCEL_IMPORT_STEP);
                    Long id = Func.getMap2Long(dataMap, lideeYunjiCodeConstant.EXCEL_IMPORT_ID);

                    //移除
                    dataMap.remove(lideeYunjiCodeConstant.EXCEL_IMPORT_STEP);
                    dataMap.remove(lideeYunjiCodeConstant.EXCEL_IMPORT_ID);

                    ExcelFileDataEntity entity = new ExcelFileDataEntity();
                    dataMap.put("id", Func.toStr(id));//设置id

                    entity.setId(id);
                    entity.setExcelFileId(fileId);
                    entity.setSort(stepSort);
                    entity.setDataJson(Func.json2Str(dataMap));
                    entity.setHandleState(YNEnum.N.getCode()); // 未处理
                    entity.setDataId(id);//数据id
                    //赋予默认值
                    entity.setTenantId(tenantId);
                    entity.setCreateUser(onlineUserId);
                    entity.setCreateDept(onlineUserDeptId);
                    entity.setCreateTime(now);
                    return entity;
                })
                .collect(Collectors.toList());

        excelFileDataService.saveBatch(entityList);

        ExcelImportResultModel resultModel = new ExcelImportResultModel();
        resultModel.setBatchCode(Func.toStr(fileId));
        resultModel.setDbFormId(dbFormId);
        resultModel.setTotalCou(dataMapList.size());
        resultModel.setFileId(fileId);
        return resultModel;
    }


    //撤回
    @DSTransactional(rollbackFor = Exception.class)
    @Override
    public void rollback(Long fileId) {
        ExcelFileEntity excelFileEntity = this.getById(fileId);
        Long dbformId = excelFileEntity.getDbformId();
        String tableName = formService.getTableName(dbformId);

        ExcelFileEntity updateFileEntity = new ExcelFileEntity();
        updateFileEntity.setImportState("-1");//已撤销
        updateFileEntity.setId(excelFileEntity.getId());
        this.updateById(updateFileEntity);

        LambdaQueryWrapper<ExcelFileDataEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExcelFileDataEntity::getExcelFileId, fileId);
        List<ExcelFileDataEntity> fileDataList = excelFileDataService.list(wrapper);
        if (Func.isEmpty(fileDataList)) {
            return;
        }
        //删除对应的业务表
        int batchSize = 500;
        List<Long> idList = new ArrayList<>();
        for (int i = 0; i < fileDataList.size(); i += batchSize) {
            int endIndex = Math.min(i + batchSize, fileDataList.size());
            idList.addAll(fileDataList.subList(i, endIndex).stream().map(ExcelFileDataEntity::getDataId).collect(Collectors.toList()));
            sqlService.baseDelRealData(tableName, idList);
            idList.clear();
        }


    }
}
