package cn.iocoder.yudao.module.energy.controller.admin.record;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.energy.controller.admin.record.vo.*;
import cn.iocoder.yudao.module.energy.convert.record.HydrogenRecordConvert;
import cn.iocoder.yudao.module.energy.dal.dataobject.record.EnergyHydrogenRecordDO;
import cn.iocoder.yudao.module.energy.service.record.HydrogenRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import cn.iocoder.yudao.framework.common.pojo.PageParam;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 加氢记录管理")
@RestController
@RequestMapping("/energy/hydrogen-record")
@Validated
public class HydrogenRecordController {

    @Resource
    private HydrogenRecordService hydrogenRecordService;

    @PostMapping("/create")
    @Operation(summary = "创建加氢记录")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:create')")
    public CommonResult<Long> createRecord(@Valid @RequestBody HydrogenRecordSaveReqVO createReqVO) {
        return success(hydrogenRecordService.createRecord(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新加氢记录")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:update')")
    public CommonResult<Boolean> updateRecord(@Valid @RequestBody HydrogenRecordSaveReqVO updateReqVO) {
        hydrogenRecordService.updateRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除加氢记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:delete')")
    public CommonResult<Boolean> deleteRecord(@RequestParam("id") Long id) {
        hydrogenRecordService.deleteRecord(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得加氢记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:query')")
    public CommonResult<HydrogenRecordRespVO> getRecord(@RequestParam("id") Long id) {
        EnergyHydrogenRecordDO record = hydrogenRecordService.getRecord(id);
        return success(HydrogenRecordConvert.INSTANCE.convert(record));
    }

    @GetMapping("/page")
    @Operation(summary = "获得加氢记录分页")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:query')")
    public CommonResult<PageResult<HydrogenRecordRespVO>> getRecordPage(@Valid HydrogenRecordPageReqVO pageReqVO) {
        PageResult<EnergyHydrogenRecordDO> pageResult = hydrogenRecordService.getRecordPage(pageReqVO);
        return success(HydrogenRecordConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出加氢记录 Excel")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:export')")
    public void exportExcel(@Valid HydrogenRecordPageReqVO pageReqVO, HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        PageResult<EnergyHydrogenRecordDO> pageResult = hydrogenRecordService.getRecordPage(pageReqVO);
        List<HydrogenRecordExcelVO> excelList = HydrogenRecordConvert.INSTANCE.convertExcelList(pageResult.getList());
        ExcelUtils.write(response, "加氢记录.xlsx", "数据", HydrogenRecordExcelVO.class, excelList);
    }

    @Deprecated // 被 import-preview + import-confirm + import-progress 三步流程替代
    @PostMapping("/import")
    @Operation(summary = "Excel 批量导入")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:import')")
    public CommonResult<Map<String, Integer>> importExcel(
            @RequestParam("stationId") Long stationId,
            @RequestParam("file") MultipartFile file) throws Exception {
        List<HydrogenRecordImportVO> list = ExcelUtils.read(file, HydrogenRecordImportVO.class);
        String batchNo = generateBatchNo();
        Map<String, Integer> result = hydrogenRecordService.importRecords(stationId, list, batchNo);
        return success(result);
    }

    @PostMapping("/import-preview")
    @Operation(summary = "导入预览")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:import')")
    public CommonResult<HydrogenRecordImportPreviewVO> importPreview(
            @RequestParam("stationId") Long stationId,
            @RequestParam("file") MultipartFile file) throws Exception {
        List<HydrogenRecordImportVO> list = ExcelUtils.read(file, HydrogenRecordImportVO.class);
        return success(hydrogenRecordService.importPreview(stationId, list));
    }

    @PostMapping("/import-confirm")
    @Operation(summary = "确认导入")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:import')")
    public CommonResult<Map<String, Integer>> importConfirm(
            @RequestParam("batchNo") String batchNo,
            @RequestParam(value = "duplicateStrategy", defaultValue = "skip") String duplicateStrategy) {
        return success(hydrogenRecordService.importConfirm(batchNo, duplicateStrategy));
    }

    @GetMapping("/import-progress")
    @Operation(summary = "导入进度")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:import')")
    public CommonResult<HydrogenRecordImportProgressVO> getImportProgress(
            @RequestParam("batchNo") String batchNo) {
        return success(hydrogenRecordService.getImportProgress(batchNo));
    }

    @PutMapping("/match")
    @Operation(summary = "手动匹配车辆")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:update')")
    public CommonResult<Boolean> matchRecord(@RequestParam("id") Long id,
                                              @RequestParam("vehicleId") Long vehicleId,
                                              @RequestParam("customerId") Long customerId) {
        hydrogenRecordService.matchRecord(id, vehicleId, customerId);
        return success(true);
    }

    @PostMapping("/batch-match")
    @Operation(summary = "批量重新匹配")
    @PreAuthorize("@ss.hasPermission('energy:hydrogen-record:update')")
    public CommonResult<Map<String, Integer>> batchMatch() {
        return success(hydrogenRecordService.batchMatch());
    }

    private String generateBatchNo() {
        return "IMP" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + UUID.randomUUID().toString().substring(0, 4).toUpperCase();
    }
}
