package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.checkerframework.checker.units.qual.C;
import org.dromara.common.core.domain.R;
import org.dromara.system.domain.SysDiseaseLabel;
import org.dromara.system.domain.SysFoodIngredient;
import org.dromara.system.mapper.SysDictDataMapper;
import org.dromara.system.mapper.SysDiseaseLabelMapper;
import org.dromara.system.mapper.SysFoodIngredientMapper;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @Author: Huanyi
 * @CreateTime: 2025-08-21
 * @Description:
 * @Version: 1.0
 */

@SaIgnore
@RestController
@RequestMapping("/excel")
@RequiredArgsConstructor
public class ExcelController {

    private final SysFoodIngredientMapper sysFoodIngredientMapper;
    private final SysDiseaseLabelMapper sysDiseaseLabelMapper;

    @PostMapping(value = "/food", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Transactional(rollbackFor = Exception.class)
    public R insertBatchFood(@RequestPart("file") MultipartFile file) {

        try {
            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            Sheet sheet = workbook.getSheetAt(0);

            List<SysFoodIngredient> list = new ArrayList<>();

            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue;
                SysFoodIngredient food = new SysFoodIngredient();

                StringBuilder categoryIds = new StringBuilder();

                for (Cell cell : row) {
                    switch (cell.getColumnIndex()) {
                        case 0 -> food.setName(cell.getStringCellValue());
                        case 1 -> food.setCode(cell.getStringCellValue());
                        case 2 -> food.setUnit(Objects.equals(cell.getStringCellValue(), "g") ? "1" : "2");
                        case 3 -> categoryIds.append((int) cell.getNumericCellValue()).append(",");
                        case 4 -> categoryIds.append((int) cell.getNumericCellValue());
                        case 5 -> food.setEdibleRatio(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 6 -> food.setCalories(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 7 -> food.setProtein(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 8 -> food.setFat(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 9 -> food.setCarbohydrate(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 10 -> food.setWater(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 11 -> food.setVitaminA(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 12 -> food.setVitaminB2(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 13 -> food.setVitaminC(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 14 -> food.setSodium(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 15 -> food.setIron(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 16 -> food.setPhosphorus(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 17 -> food.setDietaryFiber(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 18 -> food.setVitaminB1(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 19 -> food.setNiacin(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 20 -> food.setVitaminE(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 21 -> food.setCalcium(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 22 -> food.setPotassium(BigDecimal.valueOf(cell.getNumericCellValue()));
                        case 23 -> food.setCholesterol(BigDecimal.valueOf(cell.getNumericCellValue()));
                    }
                }
                food.setFoodCategoryId(categoryIds.toString());
                list.add(food);
            }

            workbook.close();

            System.err.println("成功扫描到 list : " + list.size());

            boolean flag = sysFoodIngredientMapper.insertBatch(list);
            Long count = sysFoodIngredientMapper.selectCount(Wrappers.lambdaQuery(SysFoodIngredient.class));
            System.err.println("数据库最新有 " + count + " 条数据");
            if (!flag) throw new RuntimeException("批量插入失败");

            System.err.println("成功");

            return R.ok();

        } catch (Exception e) {
            System.err.println("处理文件异常 : " + e.getMessage());
            throw new RuntimeException("文件处理异常");
        }
    }

    @PostMapping(value = "/disease", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Transactional(rollbackFor = Exception.class)
    public R insertBatchDisease(@RequestPart("file") MultipartFile file) {
        try {
            System.err.println("开始读取文件");

            XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

            Sheet sheet = workbook.getSheetAt(0);

            List<SysDiseaseLabel> list = new ArrayList<>();

            System.err.println("开始处理表格数据");
            for (Row row : sheet) {

                if (row.getRowNum() == 0) continue;

                SysDiseaseLabel disease = new SysDiseaseLabel();
                for (Cell cell : row) {

//                    System.err.println(cell.getColumnIndex() + " : " + cell.getCellType());

                    switch (cell.getColumnIndex()) {
                        case 0 -> {
                            if (cell.getCellType() == CellType.STRING) disease.setLabelId(Long.valueOf(cell.getStringCellValue()));
                            else disease.setLabelId((long) cell.getNumericCellValue());
                        }
                        case 1 -> {
                            if (cell.getCellType() == CellType.STRING) disease.setLabelName(cell.getStringCellValue());
                            else disease.setLabelName(String.valueOf((int) cell.getNumericCellValue()));
                        }
                        case 2 -> {
                            if (cell.getCellType() == CellType.STRING) disease.setLabelCode(cell.getStringCellValue());
                            else disease.setLabelCode(String.valueOf((int) cell.getNumericCellValue()));
                        }
                        case 3 -> {
                            if (cell.getCellType() == CellType.STRING) disease.setType(cell.getStringCellValue());
                            else disease.setType(String.valueOf((int) cell.getNumericCellValue()));
                        }
                    }

                }

                list.add(disease);

            }

            System.err.println("已成功提取 " + list.size() + " 条数据");

            boolean flag = sysDiseaseLabelMapper.insertBatch(list);
            if (!flag) throw new RuntimeException("批量插入失败!");

            System.err.println("输入导入成功!");

            return R.ok();

        } catch (Exception e) {
            System.err.println("处理文件异常 : " + e.getMessage());
            throw new RuntimeException("文件处理异常");
        }
    }

}
