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.HkSeizureStat;
import com.sundot.airport.item.service.IHkSeizureStatService;
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.List;

/**
 * 查获数据
 */
@RestController
@RequestMapping("/item/hkSeizureStat")
public class HkSeizureStatController extends BaseController {

    @Autowired
    private IHkSeizureStatService service;

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

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

    @Log(title = "查获数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HkSeizureStat query) {
        List<HkSeizureStat> list = service.selectHkSeizureStatList(query);
        ExcelUtil<HkSeizureStat> util = new ExcelUtil<>(HkSeizureStat.class);
        util.exportExcel(response, list, "查获数据");
    }

    @Log(title = "查获数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HkSeizureStat data) {
        return toAjax(service.insertHkSeizureStat(data));
    }

    @Log(title = "查获数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HkSeizureStat data) {
        return toAjax(service.updateHkSeizureStat(data));
    }

    @Log(title = "查获数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(service.deleteHkSeizureStatByIds(ids));
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<HkSeizureStat> util = new ExcelUtil<>(HkSeizureStat.class);
        util.importTemplateExcel(response, "查获数据导入模板");
    }

    /**
     * 导入客户原始格式的查获数据
     * Excel结构：第1行为表头，第2行起为数据
     * col0=日期  col1=班次  col2=当班大队
     * col3-14=T1各类别  col15=T1总数(公式,跳过)
     * col16-27=T2各类别  col28=T2总数(公式,跳过)  col29=合计(公式,跳过)
     */
    @Log(title = "查获数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("请选择要导入的文件");
        }
        List<HkSeizureStat> list = parseFromExcel(file.getInputStream());
        if (list.isEmpty()) {
            throw new ServiceException("未读取到有效数据，请确认文件格式是否正确");
        }
        String message = service.importData(list);
        return success(message);
    }

    private List<HkSeizureStat> parseFromExcel(InputStream is) throws Exception {
        List<HkSeizureStat> list = new ArrayList<>();
        try (Workbook workbook = WorkbookFactory.create(is)) {
            Sheet sheet = workbook.getSheetAt(0);
            // 第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.BLANK) continue;

                HkSeizureStat data = new HkSeizureStat();
                // col0: 日期
                if (dateCell.getCellType() == CellType.NUMERIC) {
                    data.setRecordDate(DateUtil.isCellDateFormatted(dateCell)
                            ? dateCell.getDateCellValue()
                            : DateUtil.getJavaDate(dateCell.getNumericCellValue()));
                }
                if (data.getRecordDate() == null) continue;

                data.setShift(strVal(row, 1));    // 班次
                data.setBrigade(strVal(row, 2));  // 当班大队
                // T1
                data.setT1FireSource(intVal(row, 3));
                data.setT1Knife(intVal(row, 4));
                data.setT1PoliceWeapon(intVal(row, 5));
                data.setT1Firework(intVal(row, 6));
                data.setT1LiveAnimal(intVal(row, 7));
                data.setT1Corrosive(intVal(row, 8));
                data.setT1FakeId(intVal(row, 9));
                data.setT1Explosive(intVal(row, 10));
                data.setT1Tool(intVal(row, 11));
                data.setT1GunAmmo(intVal(row, 12));
                data.setT1Illegal(intVal(row, 13));
                data.setT1Other(intVal(row, 14));
                // col15: T1总数（公式，跳过）
                // T2
                data.setT2FireSource(intVal(row, 16));
                data.setT2Knife(intVal(row, 17));
                data.setT2PoliceWeapon(intVal(row, 18));
                data.setT2Firework(intVal(row, 19));
                data.setT2LiveAnimal(intVal(row, 20));
                data.setT2Corrosive(intVal(row, 21));
                data.setT2FakeId(intVal(row, 22));
                data.setT2Explosive(intVal(row, 23));
                data.setT2Tool(intVal(row, 24));
                data.setT2GunAmmo(intVal(row, 25));
                data.setT2Illegal(intVal(row, 26));
                data.setT2Other(intVal(row, 27));
                // col28: T2总数（公式）  col29: 合计（公式）— 均跳过
                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;
        }
    }
}
