package com.sundot.airport.web.controller.item;

import com.sundot.airport.common.annotation.Log;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.page.TableDataInfo;
import com.sundot.airport.common.enums.BusinessType;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.poi.ExcelUtil;
import com.sundot.airport.item.domain.HkPendingConfiscate;
import com.sundot.airport.item.service.IHkPendingConfiscateService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 待检区收缴数据
 */
@RestController
@RequestMapping("/item/hkPendingConfiscate")
public class HkPendingConfiscateController extends BaseController {

    @Autowired
    private IHkPendingConfiscateService service;

    @GetMapping("/list")
    public TableDataInfo list(HkPendingConfiscate query) {
        startPage();
        List<HkPendingConfiscate> list = service.selectHkPendingConfiscateList(query);
        return getDataTable(list);
    }

    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable Long id) {
        return success(service.selectHkPendingConfiscateById(id));
    }

    @Log(title = "待检区收缴数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HkPendingConfiscate query) {
        List<HkPendingConfiscate> list = service.selectHkPendingConfiscateList(query);
        ExcelUtil<HkPendingConfiscate> util = new ExcelUtil<>(HkPendingConfiscate.class);
        util.exportExcel(response, list, "待检区收缴数据");
    }

    @Log(title = "待检区收缴数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HkPendingConfiscate data) {
        return toAjax(service.insertHkPendingConfiscate(data));
    }

    @Log(title = "待检区收缴数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HkPendingConfiscate data) {
        return toAjax(service.updateHkPendingConfiscate(data));
    }

    @Log(title = "待检区收缴数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(service.deleteHkPendingConfiscateByIds(ids));
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<HkPendingConfiscate> util = new ExcelUtil<>(HkPendingConfiscate.class);
        util.importTemplateExcel(response, "待检区收缴数据导入模板");
    }

    /**
     * 导入待检区收缴数据（按导入模板格式）
     * Excel结构：第1行为表头，第2行起为数据，每天3个时间段，日期列跨行合并
     * col0=日期  col1=时间段
     * col2-4=T1 A区(火种/液态物品/其他)  col5-7=T1 B区(火种/液态物品/其他)
     * col8-10=T2国内(火种/液态物品/其他)  col11-13=T2国际(火种/液态物品/其他)
     * col14-16=T2中转(火种/液态物品/其他)
     */
    @Log(title = "待检区收缴数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("请选择要导入的文件");
        }
        List<HkPendingConfiscate> list = parseFromExcel(file.getInputStream());
        if (list.isEmpty()) {
            throw new ServiceException("未读取到有效数据，请确认文件格式是否正确");
        }
        String message = service.importData(list);
        return success(message);
    }

    private List<HkPendingConfiscate> parseFromExcel(InputStream is) throws Exception {
        List<HkPendingConfiscate> list = new ArrayList<>();
        try (Workbook workbook = WorkbookFactory.create(is)) {
            Sheet sheet = workbook.getSheetAt(0);
            Date lastDate = null;
            // 第1行（index=0）为表头，数据从第2行（index=1）开始
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                // 日期列跨行合并，非空时更新，空时沿用上一个日期
                Cell dateCell = row.getCell(0);
                if (dateCell != null && dateCell.getCellType() == CellType.NUMERIC) {
                    lastDate = DateUtil.isCellDateFormatted(dateCell)
                            ? dateCell.getDateCellValue()
                            : DateUtil.getJavaDate(dateCell.getNumericCellValue());
                }
                if (lastDate == null) continue;

                String timeSlot = strVal(row, 1);
                if (timeSlot == null || timeSlot.isEmpty()) continue;

                HkPendingConfiscate data = new HkPendingConfiscate();
                data.setRecordDate(lastDate);
                data.setTimeSlot(timeSlot);
                // T1 A区
                data.setT1AFireSource(intVal(row, 2));
                data.setT1ALiquid(intVal(row, 3));
                data.setT1AOther(intVal(row, 4));
                // T1 B区
                data.setT1BFireSource(intVal(row, 5));
                data.setT1BLiquid(intVal(row, 6));
                data.setT1BOther(intVal(row, 7));
                // T2 国内
                data.setT2DomesticFireSource(intVal(row, 8));
                data.setT2DomesticLiquid(intVal(row, 9));
                data.setT2DomesticOther(intVal(row, 10));
                // T2 国际
                data.setT2IntlFireSource(intVal(row, 11));
                data.setT2IntlLiquid(intVal(row, 12));
                data.setT2IntlOther(intVal(row, 13));
                // T2 中转
                data.setT2TransitFireSource(intVal(row, 14));
                data.setT2TransitLiquid(intVal(row, 15));
                data.setT2TransitOther(intVal(row, 16));
                list.add(data);
            }
        }
        return list;
    }

    private String strVal(Row row, int colIdx) {
        Cell cell = row.getCell(colIdx);
        if (cell == null || cell.getCellType() == CellType.BLANK) return null;
        return cell.toString().trim();
    }

    private Integer intVal(Row row, int colIdx) {
        Cell cell = row.getCell(colIdx);
        if (cell == null || cell.getCellType() == CellType.BLANK) return null;
        try {
            if (cell.getCellType() == CellType.NUMERIC || cell.getCellType() == CellType.FORMULA) {
                return (int) cell.getNumericCellValue();
            }
            String s = cell.toString().trim();
            return s.isEmpty() ? null : (int) Double.parseDouble(s);
        } catch (Exception e) {
            return null;
        }
    }
}
