
package com.jeelowcode.core.framework.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.jeelowcode.core.framework.entity.HistoryI18nEntity;
import com.jeelowcode.core.framework.entity.ReportEntity;
import com.jeelowcode.core.framework.params.PageReportParam;
import com.jeelowcode.core.framework.params.i18n.I18nExportParam;
import com.jeelowcode.core.framework.params.vo.PageVo;
import com.jeelowcode.core.framework.service.II18nService;
import com.jeelowcode.core.framework.utils.Func;
import com.jeelowcode.core.framework.utils.FuncWeb;
import com.jeelowcode.framework.excel.JeeLowCodeExcelUtils;
import com.jeelowcode.framework.excel.model.MoreSheetConfig;
import com.jeelowcode.framework.excel.write.ExcelExportUtils;
import com.jeelowcode.framework.exception.JeeLowCodeException;
import com.jeelowcode.framework.global.JeeLowCodeBaseConstant;
import com.jeelowcode.framework.utils.adapter.IJeeLowCodeAdapter;
import com.jeelowcode.framework.utils.model.global.BaseWebResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Tag(name = "低代码框架-国际化接口")
@RestController
@AllArgsConstructor
@RequestMapping(JeeLowCodeBaseConstant.REQUEST_URL_START + "/i18n")
public class I18nController extends BaseController {


    private final II18nService ii18nService;

    private final IJeeLowCodeAdapter jeeLowCodeAdapter;

    @PreAuthorize("@ss.hasPermission('jeelowcode:i18n:export')")
    @PostMapping("/export")
    @Operation(tags = "国际化管理", summary = "导出国际化")
    public void exportData(@RequestBody I18nExportParam exportParam, HttpServletResponse rsp) throws IOException {
        List<I18nExportParam.Param> params = exportParam.getParam();
        Map<String, Object> langMap = new LinkedHashMap<>();
        for (I18nExportParam.Param param : params) {
            String code = param.getLang();
            String name = param.getName();

            langMap.put(code, name);
        }
        List<MoreSheetConfig> export = ii18nService.export(langMap);
        ExcelExportUtils.exportExcel(rsp, "国际化", export);
    }

    @PreAuthorize("@ss.hasPermission('jeelowcode:i18n:import')")
    @PostMapping("/import")
    @Operation(tags = "国际化管理", summary = "导入国际化")
    public BaseWebResult importData(I18nExportParam exportParam) throws IOException {
        try {
            String fileUrl = exportParam.getFileUrl();
            String exportLangParam = exportParam.getExportLangParam();
            MultipartFile file = exportParam.getFile();

            List<String> strList = Func.toStrList(exportLangParam);

            List<I18nExportParam.Param> params =new ArrayList<>();
            for(String str:strList){
                List<String> tmpList = Func.toStrList("=", str);
                I18nExportParam.Param param=new I18nExportParam.Param();
                param.setLang(tmpList.get(0));
                param.setName(tmpList.get(1));
                params.add(param);
            }

            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();

            // 将原始 InputStream 复制到 ByteArrayOutputStream
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            inputStream.close(); // 关闭原始 InputStream

            Map<Integer, List<Map<String, Object>>> sheetDataMap = new LinkedHashMap<>();
            Integer totalCou = 0;
            for (int sheet = 0; sheet < 6; sheet++) {
                Map<String, String> fieldNameAndCodeMap = new LinkedHashMap<>();
                fieldNameAndCodeMap.put("Id(不允许改动)", "id");
                for (I18nExportParam.Param param : params) {
                    String code = param.getLang();
                    String name = param.getName();
                    fieldNameAndCodeMap.put(name, code);
                }
                InputStream newInputStream = new ByteArrayInputStream(outputStream.toByteArray());
                //国际化数据
                List<Map<String, Object>> dataMapList = JeeLowCodeExcelUtils.importExcel(newInputStream, 1, sheet, fieldNameAndCodeMap);
                sheetDataMap.put(sheet, dataMapList);
                totalCou += dataMapList.size();
            }

            String batchCode = IdWorker.getIdStr();
            //保存
            HistoryI18nEntity entity = new HistoryI18nEntity();

            entity.setBatchCode(batchCode);
            entity.setFileName(fileName);
            entity.setFileUrl(fileUrl);
            entity.setTotalCou(totalCou);
            entity.setUserName(jeeLowCodeAdapter.getOnlineUserName());
            ii18nService.saveHistory(entity);

            //进行导入
            ii18nService.importData(batchCode, sheetDataMap);
            return BaseWebResult.success(batchCode);
        } catch (Exception e) {
            throw new JeeLowCodeException("导入失败");
        }
    }

    @ApiOperationSupport(order = 4)
    @Operation(tags = "国际化管理", summary = "查询导入进度")
    @GetMapping({"/import/progress"})
    public BaseWebResult importProgress(String batchCode) {
        Map<String, Integer> resultMap = ii18nService.getImportProgress(batchCode);
        return BaseWebResult.success(resultMap);
    }

    @PreAuthorize("@ss.hasPermission('jeelowcode:i18n:query')")
    @PostMapping("/page")
    @ApiOperationSupport(order = 5)
    @Operation(tags = "国际化管理",summary = "数据 - 获取分页数据")
    public BaseWebResult getPage(PageVo pageVo) {
        Page page = FuncWeb.getPage(pageVo.getPageNo(), pageVo.getPageSize());
        IPage<HistoryI18nEntity> pages = ii18nService.getPages(page);
        return BaseWebResult.success(pages);
    }
}
