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.HkOperationData;
import com.sundot.airport.item.service.IHkOperationDataService;
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/hkOperationData")
public class HkOperationDataController extends BaseController {

    @Autowired
    private IHkOperationDataService service;

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

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

    @Log(title = "每日运行数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HkOperationData query) {
        List<HkOperationData> list = service.selectHkOperationDataList(query);
        ExcelUtil<HkOperationData> util = new ExcelUtil<>(HkOperationData.class);
        util.exportExcel(response, list, "每日运行数据");
    }

    @Log(title = "每日运行数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HkOperationData data) {
        return toAjax(service.insertHkOperationData(data));
    }

    @Log(title = "每日运行数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HkOperationData data) {
        return toAjax(service.updateHkOperationData(data));
    }

    @Log(title = "每日运行数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(service.deleteHkOperationDataByIds(ids));
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<HkOperationData> util = new ExcelUtil<>(HkOperationData.class);
        util.importTemplateExcel(response, "每日运行数据导入模板");
    }

    /**
     * 导入每日运行数据（按导入模板格式）
     * Excel结构：第1行为表头，第2行起为数据，共24列
     * col0=日期  col1=A区  col2=B区  col3=贵宾  col4=国内旅检  col5=国际旅检
     * col6=贵宾通道  col7=T1回流通道  col8=T1行检  col9=一楼员工
     * col10=T2回流通道  col11=T2行检  col12=三楼东区员工  col13=一楼中心区员工
     * col14=负一楼西区员工  col15=三楼西区员工  col16=国内货站  col17=道口(国内货站)
     * col18=南侧车检  col19=防爆(国内货站)  col20=国际货站  col21=道口(国际货站)
     * col22=北侧车检  col23=防爆(国际货站)
     */
    @Log(title = "每日运行数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("请选择要导入的文件");
        }
        List<HkOperationData> list = parseFromExcel(file.getInputStream());
        if (list.isEmpty()) {
            throw new ServiceException("未读取到有效数据，请确认文件格式是否正确");
        }
        String message = service.importData(list);
        return success(message);
    }

    private List<HkOperationData> parseFromExcel(InputStream is) throws Exception {
        List<HkOperationData> 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;
                if (dateCell.getCellType() != CellType.NUMERIC) continue;

                HkOperationData data = new HkOperationData();
                if (DateUtil.isCellDateFormatted(dateCell)) {
                    data.setRecordDate(dateCell.getDateCellValue());
                } else {
                    data.setRecordDate(DateUtil.getJavaDate(dateCell.getNumericCellValue()));
                }
                data.setAZone(intVal(row, 1));
                data.setBZone(intVal(row, 2));
                data.setVip(intVal(row, 3));
                data.setDomesticPassenger(intVal(row, 4));
                data.setIntlPassenger(intVal(row, 5));
                data.setVipChannel(intVal(row, 6));
                data.setT1ReturnChannel(intVal(row, 7));
                data.setT1LuggageCheck(intVal(row, 8));
                data.setFloor1Staff(intVal(row, 9));
                data.setT2ReturnChannel(intVal(row, 10));
                data.setT2LuggageCheck(intVal(row, 11));
                data.setFloor3EastStaff(intVal(row, 12));
                data.setFloor1CenterStaff(intVal(row, 13));
                data.setFloorB1WestStaff(intVal(row, 14));
                data.setFloor3WestStaff(intVal(row, 15));
                data.setDomesticCargo(intVal(row, 16));
                data.setDomesticGate(intVal(row, 17));
                data.setSouthVehicleCheck(intVal(row, 18));
                data.setDomesticBomb(intVal(row, 19));
                data.setIntlCargo(intVal(row, 20));
                data.setIntlGate(intVal(row, 21));
                data.setNorthVehicleCheck(intVal(row, 22));
                data.setIntlBomb(intVal(row, 23));
                list.add(data);
            }
        }
        return list;
    }

    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;
        }
    }
}
