package com.ycwl.basic.controller.mobile;

import com.ycwl.basic.annotation.IgnoreToken;
import com.ycwl.basic.mapper.PrinterGuideMapper;
import com.ycwl.basic.model.jwt.JwtInfo;
import com.ycwl.basic.model.mobile.face.FaceRecognizeResp;
import com.ycwl.basic.model.pc.printer.entity.PrinterGuideEntity;
import com.ycwl.basic.model.pc.printer.resp.MemberPrintResp;
import com.ycwl.basic.model.pc.printer.resp.PrinterResp;
import com.ycwl.basic.model.printer.req.FromSourceReq;
import com.ycwl.basic.service.printer.PrinterService;
import com.ycwl.basic.storage.StorageFactory;
import com.ycwl.basic.utils.ApiResponse;
import com.ycwl.basic.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/mobile/printer/v1")
public class AppPrinterController {
    @Autowired
    private PrinterService printerService;
    @Autowired
    private PrinterGuideMapper printerGuideMapper;
    @GetMapping("/listFor/{scenicId}")
    @IgnoreToken
    public ApiResponse<List<PrinterResp>> listFor(@PathVariable("scenicId") Long scenicId) {
        return ApiResponse.success(printerService.listByScenicId(scenicId));
    }

    // 查询打印机已启用的指引图片（按排序）
    @GetMapping("/guide/{printerId}")
    @IgnoreToken
    public ApiResponse<List<PrinterGuideEntity>> guideList(@PathVariable("printerId") Integer printerId) {
        return ApiResponse.success(printerGuideMapper.listEnabledByPrinterId(printerId));
    }

    @GetMapping("/useSample/{sampleId}")
    public ApiResponse<FaceRecognizeResp> useSample(@PathVariable("sampleId") Long sampleId) throws IOException {
        JwtInfo worker = JwtTokenUtil.getWorker();
        return ApiResponse.success(printerService.useSample(worker.getUserId(), sampleId));
    }

    @GetMapping("/getListFor/{scenicId}")
    public ApiResponse<List<MemberPrintResp>> getListFor(@PathVariable("scenicId") Long scenicId, @RequestParam(required = false) String faceId) {
        JwtInfo worker = JwtTokenUtil.getWorker();
        return ApiResponse.success(printerService.getUserPhotoList(worker.getUserId(), scenicId, parseFaceId(faceId)));
    }

    @GetMapping("/getItem/{scenicId}/{id}")
    public ApiResponse<MemberPrintResp> getItem(@PathVariable("scenicId") Long scenicId, @PathVariable("id") Long id) {
        JwtInfo worker = JwtTokenUtil.getWorker();
        MemberPrintResp userPhoto = printerService.getUserPhoto(worker.getUserId(), scenicId, id);
        if (userPhoto == null) {
            return ApiResponse.fail("未找到该图片");
        }
        return ApiResponse.success(userPhoto);
    }

    @PostMapping("/deleteFrom/{scenicId}/{id}")
    public ApiResponse<?> deleteFrom(@PathVariable("scenicId") Long scenicId, @PathVariable("id") Long id) {
        JwtInfo worker = JwtTokenUtil.getWorker();
        printerService.deleteUserPhoto(worker.getUserId(), scenicId, id);
        return ApiResponse.success(null);
    }
    @PostMapping("/uploadTo/{scenicId}")
    public ApiResponse<?> upload(@PathVariable("scenicId") Long scenicId,
                                 @RequestParam(value = "file") MultipartFile file,
                                 @RequestParam(value = "faceId", required = false) String faceId) {
        String[] split = file.getOriginalFilename().split("\\.");
        String ext = split[split.length - 1];
        String url = StorageFactory.use().uploadFile(file, "printer", UUID.randomUUID() + "." + ext);
        Integer id = printerService.addUserPhoto(JwtTokenUtil.getWorker().getUserId(), scenicId, url, parseFaceId(faceId), null);
        return ApiResponse.success(id);
    }
    @PostMapping(value = "/uploadTo/{scenicId}/cropped/{id}", consumes = "multipart/form-data")
    public ApiResponse<?> uploadReplace(@PathVariable("scenicId") Long scenicId,
                                        @PathVariable("id") Long id,
                                        @RequestPart(value = "crop", required = false) String crop,
                                        @RequestPart(value = "file") MultipartFile file) {
        String[] split = file.getOriginalFilename().split("\\.");
        String ext = split[split.length - 1];
        String url = StorageFactory.use().uploadFile(file, "printer", UUID.randomUUID() + "." + ext);
        printerService.setPhotoCropped(JwtTokenUtil.getWorker().getUserId(), scenicId, id, url, crop);
        return ApiResponse.success(url);
    }
    @PostMapping("/uploadTo/{scenicId}/formSource")
    public ApiResponse<?> uploadFromSource(@PathVariable("scenicId") Long scenicId,
                                           @RequestBody FromSourceReq req,
                                           @RequestParam(value = "faceId", required = false) String faceId) {
        List<Integer> list = printerService.addUserPhotoFromSource(JwtTokenUtil.getWorker().getUserId(), scenicId, req, parseFaceId(faceId));
        return ApiResponse.success(list);
    }

    @PostMapping("/setQuantity/{scenicId}/{id}")
    public ApiResponse<?> setQuantity(@PathVariable("scenicId") Long scenicId, @PathVariable("id") Long id, @RequestParam("quantity") Integer quantity) {
        if (quantity == null) {
            return ApiResponse.fail("请输入数量");
        }
        if (quantity < 0) {
            return ApiResponse.fail("数量不能小于0");
        }
        printerService.setPhotoQuantity(JwtTokenUtil.getWorker().getUserId(), scenicId, id, quantity);
        return ApiResponse.success(null);
    }
    @GetMapping("/price/{scenicId}")
    public ApiResponse<?> queryPrice(@PathVariable("scenicId") Long scenicId,
                                     @RequestParam(value = "faceId", required = false) String faceId) {
        return ApiResponse.success(printerService.queryPrice(JwtTokenUtil.getWorker().getUserId(), scenicId, parseFaceId(faceId)));
    }

    @PostMapping("/order/{scenicId}")
    public ApiResponse<Map<String, Object>> createOrder(@PathVariable("scenicId") Long scenicId,
                                                        @RequestParam(value = "faceId", required = false) String faceId) {
        return ApiResponse.success(printerService.createOrder(JwtTokenUtil.getWorker().getUserId(), scenicId, null, parseFaceId(faceId)));
    }
    @PostMapping("/order/{scenicId}/toPrinter/{printerId}")
    public ApiResponse<Map<String, Object>> createOrderToPrinter(@PathVariable("scenicId") Long scenicId,
                                                                 @PathVariable("printerId") Integer printerId,
                                                                 @RequestParam(value = "faceId", required = false) String faceId) {
        return ApiResponse.success(printerService.createOrder(JwtTokenUtil.getWorker().getUserId(), scenicId, printerId, parseFaceId(faceId)));
    }

    /**
     * 解析 faceId 字符串为 Long 类型
     * 如果字符串不是有效数字，则返回 null
     */
    private Long parseFaceId(String faceId) {
        if (faceId == null || faceId.trim().isEmpty()) {
            return null;
        }
        try {
            return Long.parseLong(faceId.trim());
        } catch (NumberFormatException e) {
            return null;
        }
    }
}
