package com.cf.imes.module.system.controller.admin.funds.advertisement;

import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.common.pojo.PageResult;
import com.cf.imes.module.system.controller.admin.funds.advertisement.vo.AdvertisementPageReqVO;
import com.cf.imes.module.system.controller.admin.funds.advertisement.vo.AdvertisementPublishReqVO;
import com.cf.imes.module.system.controller.admin.funds.advertisement.vo.AdvertisementRespVO;
import com.cf.imes.module.system.controller.admin.funds.advertisement.vo.AdvertisementSaveReqVO;
import com.cf.imes.module.system.service.funds.advertisement.AdvertisementService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
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 jakarta.annotation.Resource;
import jakarta.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.List;

import static com.cf.imes.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.cf.imes.framework.common.pojo.CommonResult.success;
import static com.cf.imes.module.system.enums.ErrorCodeConstants.ADVERTISEMENT_STATUS_ERROR;

@Tag(name = "管理后台 - 广告管理")
@RestController
@RequestMapping("/system/ad")
@Validated
@Slf4j
public class AdvertisementController {

    @Resource
    private AdvertisementService advertisementService;


    @PostMapping("")
    @Operation(summary = "新建广告")
    @PreAuthorize("@ss.hasPermission('base:advertisement:create')")
    public CommonResult<Long> createAdvertisement(@Valid @RequestBody AdvertisementSaveReqVO createReqVO) {
        return success(advertisementService.create(createReqVO));
    }


    @PutMapping("")
    @Operation(summary = "更新广告")
    @PreAuthorize("@ss.hasPermission('base:advertisement:update')")
    public CommonResult<Boolean> updateAdvertisement(@Valid @RequestBody AdvertisementSaveReqVO reqVO) {
        advertisementService.update(reqVO);
        return success(true);
    }


    @DeleteMapping("")
    @Operation(summary = "删除广告")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('base:advertisement:delete')")
    public CommonResult<Boolean> deleteAdvertisement(@RequestParam("id") Long id) {
        advertisementService.delete(id);
        return success(true);
    }


    @GetMapping("/{id}")
    @Operation(summary = "获得广告")
    @Parameter(name = "id", description = "广告ID", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('base:advertisement:query')")
    public CommonResult<AdvertisementRespVO> getAdvertisement(@PathVariable("id") Long id) {

        return success(advertisementService.get(id));
    }


    @GetMapping("/page")
    @Operation(summary = "获得广告分页")
    @PreAuthorize("@ss.hasPermission('base:advertisement:query')")
    public CommonResult<PageResult<AdvertisementRespVO>> getAdvertisementPage(@Valid AdvertisementPageReqVO pageReqVO) {

        return success(advertisementService.getPage(pageReqVO));
    }



    @PutMapping("/publish")
    @Operation(summary = "发布/结束/重新发布广告")
    @Parameter(name = "id", description = "广告id", required = true)
    @Parameter(name = "status", description = "广告状态", required = true)
    @PreAuthorize("@ss.hasPermission('base:advertisement:update')")
    public CommonResult<Boolean> updatePublishStatus(@RequestBody AdvertisementPublishReqVO reqVO) {
        advertisementService.updatePublishStatus(reqVO);
        return success(true);
    }




    @GetMapping("/getAd")
    @Operation(summary = "根据广告位置获得广告信息")
    @PreAuthorize("@ss.hasPermission('base:advertisement:query')")
    public CommonResult<List<AdvertisementRespVO>> getAdvertisementByPosition(@RequestParam("id") Integer adPosition) {

        return success(advertisementService.getAdvertisementByPosition(adPosition));
    }







    // 上传图片，支持附带 orderId 参数
    @PostMapping("/upload")
    public CommonResult<String> uploadImage(@RequestParam("file") MultipartFile file,
                                              @RequestParam("orderId") Long orderId) {

        try {


            // 获取原始文件名并提取扩展名
            String originalFilename = file.getOriginalFilename();
            String extension = "";

            int dotIndex = originalFilename.lastIndexOf('.');
            if (dotIndex != -1) {
                extension = originalFilename.substring(dotIndex); // 包含“.”
            } else {
                throw exception(1,"缺少扩展名");
            }

            // 构建新文件名: orderId + .扩展名
            String filename = orderId + extension;

            // 确保目录存在
            File dir = new File("E:\\ceshi123\\");
            if (!dir.exists()) {
                dir.mkdirs();
            }


            File dest = new File(dir, filename);
            file.transferTo(dest);


            // 你可以把图片信息和 orderId 一起存入数据库，这里省略
            return success("上传成功: " + filename);
        } catch (IOException e) {
            log.error(e.getMessage());
            throw exception(ADVERTISEMENT_STATUS_ERROR);
        }

    }









}
