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.HkPersuadePowerBank;
import com.sundot.airport.item.service.IHkPersuadePowerBankService;
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/hkPersuadePowerBank")
public class HkPersuadePowerBankController extends BaseController {

    @Autowired
    private IHkPersuadePowerBankService service;

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

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

    @Log(title = "劝阻充电宝数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HkPersuadePowerBank query) {
        List<HkPersuadePowerBank> list = service.selectHkPersuadePowerBankList(query);
        ExcelUtil<HkPersuadePowerBank> util = new ExcelUtil<>(HkPersuadePowerBank.class);
        util.exportExcel(response, list, "劝阻充电宝数据");
    }

    @Log(title = "劝阻充电宝数据", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HkPersuadePowerBank data) {
        return toAjax(service.insertHkPersuadePowerBank(data));
    }

    @Log(title = "劝阻充电宝数据", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HkPersuadePowerBank data) {
        return toAjax(service.updateHkPersuadePowerBank(data));
    }

    @Log(title = "劝阻充电宝数据", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(service.deleteHkPersuadePowerBankByIds(ids));
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<HkPersuadePowerBank> util = new ExcelUtil<>(HkPersuadePowerBank.class);
        util.importTemplateExcel(response, "劝阻充电宝数据导入模板");
    }

    /**
     * 导入劝阻充电宝数据（按导入模板格式）
     * Excel结构：第1行为表头，第2行起为数据，每天3个时间段，日期列跨行合并
     * col0=日期  col1=时间段
     * col2-8=T1(召回充电宝/无3C标识/标识不清/超规数量/邮寄/自弃/暂存)
     * col9-15=T2(召回充电宝/无3C标识/标识不清/超规数量/邮寄/自弃/暂存)
     */
    @Log(title = "劝阻充电宝数据", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        if (file == null || file.isEmpty()) {
            throw new ServiceException("请选择要导入的文件");
        }
        List<HkPersuadePowerBank> list = parseFromExcel(file.getInputStream());
        if (list.isEmpty()) {
            throw new ServiceException("未读取到有效数据，请确认文件格式是否正确");
        }
        String message = service.importData(list);
        return success(message);
    }

    private List<HkPersuadePowerBank> parseFromExcel(InputStream is) throws Exception {
        List<HkPersuadePowerBank> 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;

                HkPersuadePowerBank data = new HkPersuadePowerBank();
                data.setRecordDate(lastDate);
                data.setTimeSlot(timeSlot);
                // T1
                data.setT1Recall(intVal(row, 2));
                data.setT1No3c(intVal(row, 3));
                data.setT1UnclearMark(intVal(row, 4));
                data.setT1ExcessQty(intVal(row, 5));
                data.setT1Mail(intVal(row, 6));
                data.setT1Abandon(intVal(row, 7));
                data.setT1TempStore(intVal(row, 8));
                // T2（模板无公式列，col9直接接T2）
                data.setT2Recall(intVal(row, 9));
                data.setT2No3c(intVal(row, 10));
                data.setT2UnclearMark(intVal(row, 11));
                data.setT2ExcessQty(intVal(row, 12));
                data.setT2Mail(intVal(row, 13));
                data.setT2Abandon(intVal(row, 14));
                data.setT2TempStore(intVal(row, 15));
                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;
        }
    }
}
