package com.gxwebsoft.hjm.controller;

import cn.hutool.core.util.StrUtil;
import com.gxwebsoft.common.core.config.ConfigProperties;
import com.gxwebsoft.common.core.utils.FileServerUtil;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.common.system.entity.FileRecord;
import com.gxwebsoft.hjm.service.HjmBxLogService;
import com.gxwebsoft.hjm.entity.HjmBxLog;
import com.gxwebsoft.hjm.param.HjmBxLogParam;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.PageResult;
import com.gxwebsoft.common.core.web.BatchParam;
import com.gxwebsoft.common.core.annotation.OperationLog;
import com.gxwebsoft.common.system.entity.User;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * 黄家明_报险记录控制器
 *
 * @author 科技小王子
 * @since 2025-06-06 13:08:29
 */
@Tag(name = "黄家明_报险记录管理")
@RestController
@RequestMapping("/api/hjm/hjm-bx-log")
public class HjmBxLogController extends BaseController {
    @Resource
    private ConfigProperties config;
    @Resource
    private HjmBxLogService hjmBxLogService;

    @Operation(summary = "分页查询黄家明_报险记录")
    @GetMapping("/page")
    public ApiResult<PageResult<HjmBxLog>> page(HjmBxLogParam param) {
        // 使用关联查询
        return success(hjmBxLogService.pageRel(param));
    }

    @Operation(summary = "查询全部黄家明_报险记录")
    @GetMapping()
    public ApiResult<List<HjmBxLog>> list(HjmBxLogParam param) {
        // 使用关联查询
        return success(hjmBxLogService.listRel(param));
    }

    @Operation(summary = "根据id查询黄家明_报险记录")
    @GetMapping("/{id}")
    public ApiResult<HjmBxLog> get(@PathVariable("id") Integer id) {
        // 使用关联查询
        return success(hjmBxLogService.getByIdRel(id));
    }

    @Operation(summary = "添加黄家明_报险记录")
    @PostMapping()
    public ApiResult<?> save(@RequestBody HjmBxLog hjmBxLog) {
        // 记录当前登录用户id
        User loginUser = getLoginUser();
        if (loginUser != null) {
         hjmBxLog.setUserId(loginUser.getUserId());
        }
        if (hjmBxLogService.save(hjmBxLog)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('hjm:hjmBxLog:update')")
    @OperationLog
    @Operation(summary = "修改黄家明_报险记录")
    @PutMapping()
    public ApiResult<?> update(@RequestBody HjmBxLog hjmBxLog) {
        if (hjmBxLogService.updateById(hjmBxLog)) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('hjm:hjmBxLog:remove')")
    @OperationLog
    @Operation(summary = "删除黄家明_报险记录")
    @DeleteMapping("/{id}")
    public ApiResult<?> remove(@PathVariable("id") Integer id) {
        if (hjmBxLogService.removeById(id)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @PreAuthorize("hasAuthority('hjm:hjmBxLog:save')")
    @OperationLog
    @Operation(summary = "批量添加黄家明_报险记录")
    @PostMapping("/batch")
    public ApiResult<?> saveBatch(@RequestBody List<HjmBxLog> list) {
        if (hjmBxLogService.saveBatch(list)) {
            return success("添加成功");
        }
        return fail("添加失败");
    }

    @PreAuthorize("hasAuthority('hjm:hjmBxLog:update')")
    @OperationLog
    @Operation(summary = "批量修改黄家明_报险记录")
    @PutMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody BatchParam<HjmBxLog> batchParam) {
        if (batchParam.update(hjmBxLogService, "id")) {
            return success("修改成功");
        }
        return fail("修改失败");
    }

    @PreAuthorize("hasAuthority('hjm:hjmBxLog:remove')")
    @OperationLog
    @Operation(summary = "批量删除黄家明_报险记录")
    @DeleteMapping("/batch")
    public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
        if (hjmBxLogService.removeByIds(ids)) {
            return success("删除成功");
        }
        return fail("删除失败");
    }

    @Operation(summary = "上传文件")
    @PostMapping("/upload")
    public ApiResult<FileRecord> upload(@RequestParam MultipartFile file, HttpServletRequest request) {
      FileRecord result = null;
      try {
        String dir = getUploadDir();
        File upload = FileServerUtil.upload(file, dir, config.getUploadUuidName());
        String path = upload.getAbsolutePath().replace("\\", "/").substring(dir.length() - 1);
  //            String requestURL = StrUtil.removeSuffix(request.getRequestURL(), "/upload");
        String requestURL = config.getFileServer() + "/api/file";
        String originalName = file.getOriginalFilename();
        result = new FileRecord();
        result.setCreateUserId(getLoginUserId());
        result.setName(StrUtil.isBlank(originalName) ? upload.getName() : originalName);
        result.setLength(upload.length());
        result.setPath(path);
        result.setUrl(requestURL + path);
        String contentType = FileServerUtil.getContentType(upload);
        result.setContentType(contentType);
        if (FileServerUtil.isImage(contentType)) {
          result.setThumbnail(requestURL + "/thumbnail" + path);
        }
        result.setUrl(path);
        System.out.println("result = " + result);
        return success(result);
      } catch (Exception e) {
        e.printStackTrace();
        return fail("上传失败", result).setError(e.toString());
      }
    }

    /**
     * 文件上传位置(服务器)
     */
    private String getUploadDir() {
      return config.getUploadPath();
    }

}
