package com.sckw.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.sckw.core.utils.TruckNoUtils;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.system.model.report.WeighbridgeRecordExcel;
import com.sckw.system.model.vo.req.LicensePlateValidateRequest;
import com.sckw.system.model.vo.req.WeighbridgePushRequest;
import com.sckw.system.model.vo.req.WeighbridgeRecordPageReqVo;
import com.sckw.system.model.vo.res.LicensePlateValidateResponse;
import com.sckw.system.service.KwsWeighbridgeRecordManageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * 地磅记录控制器
 */
@RestController
@RequestMapping("/kwsWeighbridgeRecord")
@Tag(name = "地磅记录")
@RequiredArgsConstructor
public class KwsWeighbridgeRecordController {

    private final KwsWeighbridgeRecordManageService kwsWeighbridgeRecordManageService;

    @PostMapping("/page")
    @Operation(summary = "地磅记录分页查询")
    public HttpResult page(@RequestBody WeighbridgeRecordPageReqVo reqVo) {
        return HttpResult.ok(kwsWeighbridgeRecordManageService.page(reqVo));
    }

    @PostMapping("/export")
    @Operation(summary = "导出地磅记录")
    public void export(@RequestBody WeighbridgeRecordPageReqVo reqVo, HttpServletResponse response) throws IOException {
        List<WeighbridgeRecordExcel> data = kwsWeighbridgeRecordManageService.exportList(reqVo);
        if (data == null || data.isEmpty()) {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(JSONObject.toJSONString(HttpResult.error("没有可导出的地磅记录")));
            return;
        }
        ExcelUtil.download(response, WeighbridgeRecordExcel.class, data);
    }



    /**
     * 地磅过磅数据上报
     */
    @Operation(summary = "地磅过磅数据上报", description = "接收地磅设备上报的过磅数据和图片")
    @PostMapping("/weighBridgePush")
    public LicensePlateValidateResponse weighBridgePush(
            @Parameter(description = "车牌号") @RequestParam("licensePlate") String licensePlate,
            @Parameter(description = "地磅编号") @RequestParam("weighbridgeCode") String weighbridgeCode,
            @Parameter(description = "称重重量(吨)") @RequestParam("grossWeight") String grossWeight,
            @Parameter(description = "时间戳(秒或毫秒)") @RequestParam("timestamp") String timestamp,
            @Parameter(description = "处理标签") @RequestParam(value = "tag", required = false) String tag,
            @Parameter(description = "车辆照片") @RequestParam(value = "images[]", required = false) MultipartFile[] images
    ) {
        String cleanedLicensePlate = sanitizeText(licensePlate);
        if (!TruckNoUtils.isValidTruckNo(cleanedLicensePlate)) {
            return buildPushErrorResponse("车牌号格式不正确");
        }

        WeighbridgePushRequest request = new WeighbridgePushRequest();
        request.setLicensePlate(TruckNoUtils.formatTruckNo(cleanedLicensePlate));
        request.setWeighbridgeCode(sanitizeText(weighbridgeCode));
        request.setGrossWeight(parseBigDecimal(grossWeight));
        request.setTimestamp(parseLong(timestamp));
        request.setTag(sanitizeText(tag));
        request.setImages(images);

        // 调用业务层处理
        return kwsWeighbridgeRecordManageService.handleWeighbridgePush(request);
    }

    /**
     * 车牌验证
     */
    @Operation(summary = "车牌验证", description = "用于验证车牌是否合法，允许上磅")
    @PostMapping("/validateLicensePlate")
    public LicensePlateValidateResponse validateLicensePlate(
            @Parameter(description = "车牌号") @RequestParam("licensePlate") String licensePlate,
            @Parameter(description = "厂商来源标识") @RequestParam("uuid") String uuid
    ) {
        LicensePlateValidateRequest request = new LicensePlateValidateRequest();
        String replac2 = "";
        if (StringUtils.isNotBlank(licensePlate)) {
            String trim = licensePlate.trim();
            String replace = trim.replace("\\r", "");
            String replace1 = replace.replace("\\n", "");
            replac2 = replace1.replace("\\r\\n", "");
        }

        request.setLicensePlate(replac2);
        request.setUuid(uuid);
        return kwsWeighbridgeRecordManageService.handleValidateLicensePlate(request);
    }

    private String sanitizeText(String value) {
        if (StringUtils.isBlank(value)) {
            return "";
        }
        return value.trim()
                .replace("\r", "")
                .replace("\n", "");
    }

    private BigDecimal parseBigDecimal(String value) {
        String cleanedValue = sanitizeText(value);
        return StringUtils.isBlank(cleanedValue) ? null : new BigDecimal(cleanedValue);
    }

    private Long parseLong(String value) {
        String cleanedValue = sanitizeText(value);
        return StringUtils.isBlank(cleanedValue) ? null : Long.valueOf(cleanedValue);
    }

    private LicensePlateValidateResponse buildPushErrorResponse(String message) {
        LicensePlateValidateResponse response = new LicensePlateValidateResponse();
        response.setStatus(false);
        response.setCode(400);
        response.setMessage(message);
        LicensePlateValidateResponse.Data data = new LicensePlateValidateResponse.Data();
        data.setTimestamp(System.currentTimeMillis() / 1000);
        data.setScreen_message(message);
        data.setVoice_message(message);
        response.setData(data);
        return response;
    }
}
