package shop.alien.store.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import shop.alien.entity.result.R;
import shop.alien.entity.store.ProtocolManagement;
import shop.alien.store.service.ProtocolManagementService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 协议管理表 前端控制器
 *
 * @author alien
 * @since 2025-12-09
 */
@Slf4j
@Api(tags = {"协议管理"})
@ApiSort(100)
@CrossOrigin
@RestController
@RequestMapping("/protocolManagement")
@RequiredArgsConstructor
public class ProtocolManagementController {

    private final ProtocolManagementService protocolManagementService;

    @ApiOperation("协议列表-分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "页容", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "protocolFileName", value = "协议名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "displayPosition", value = "展示位置", dataType = "String", paramType = "query")
    })
    @GetMapping("/getPage")
    public R<IPage<ProtocolManagement>> getPage(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            @RequestParam(value = "protocolFileName", required = false) String protocolFileName,
            @RequestParam(value = "displayPosition", required = false) String displayPosition) {
        log.info("ProtocolManagementController.getPage?pageNum={}&pageSize={}&protocolFileName={}&displayPosition={}", 
                pageNum, pageSize, protocolFileName, displayPosition);
        
        try {
            IPage<ProtocolManagement> page = protocolManagementService.getProtocolPage(pageNum, pageSize, protocolFileName, displayPosition);
            return R.data(page);
        } catch (Exception e) {
            log.error("查询协议列表失败", e);
            return R.fail("查询失败: " + e.getMessage());
        }
    }

    @ApiOperation("协议详情-根据ID查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "协议ID", dataType = "Integer", paramType = "query", required = true)
    })
    @GetMapping("/getById")
    public void getById(@RequestParam("id") Integer id, HttpServletResponse response) throws IOException {
        log.info("ProtocolManagementController.getById?id={}", id);

        try {
            protocolManagementService.getProtocolById(id, response);
        } catch (IllegalArgumentException e) {
            log.error("查询协议详情失败", e);
            if (!response.isCommitted()) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
            }
        } catch (Exception e) {
            log.error("查询协议详情失败", e);
            if (!response.isCommitted()) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "查询失败: " + e.getMessage());
            }
        }
    }

    @ApiOperation("新增协议")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "protocolFileName", value = "协议名称", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "displayPosition", value = "展示位置", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "protocolFilePath", value = "协议文件存储路径", dataType = "String", paramType = "query", required = true),
            @ApiImplicitParam(name = "createdUserId", value = "创建人ID", dataType = "Integer", paramType = "query")

    })
    @PostMapping("/add")
    public R<Boolean> add(
            @RequestParam("protocolFileName") String protocolFileName,
            @RequestParam(value = "displayPosition") String displayPosition,
            @RequestParam(value = "createdUserId", required = false) Integer createdUserId,
            MultipartFile multipartFile) {
        log.info("ProtocolManagementController.add?protocolFileName={}&displayPosition={}&createdUserId={}",
                protocolFileName, displayPosition, createdUserId);
        
        try {
            ProtocolManagement protocolManagement = new ProtocolManagement();
            protocolManagement.setProtocolFileName(protocolFileName);
            protocolManagement.setDisplayPosition(displayPosition);
            
            // 当createdUserId不为空时才设置值
            if (createdUserId != null) {
                protocolManagement.setCreatedUserId(createdUserId);
            }
            
            boolean result = protocolManagementService.addProtocol(multipartFile, protocolManagement);
            
            if (result) {
                return R.success("新增成功");
            } else {
                return R.fail("新增失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("新增协议失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("新增协议失败", e);
            return R.fail("新增失败: " + e.getMessage());
        }
    }

    @ApiOperation("修改协议")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "协议ID", dataType = "Integer", paramType = "query", required = true),
            @ApiImplicitParam(name = "protocolFileName", value = "协议名称", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "displayPosition", value = "展示位置", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "protocolFilePath", value = "协议文件存储路径", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "updatedUserId", value = "修改人ID", dataType = "Integer", paramType = "query")
    })
    @PostMapping("/update")
    public R<Boolean> update(
            @RequestParam("id") Integer id,
            @RequestParam(value = "protocolFileName", required = false) String protocolFileName,
            @RequestParam(value = "displayPosition", required = false) String displayPosition,
            @RequestParam(value = "protocolFilePath", required = false) String protocolFilePath,
            @RequestParam(value = "updatedUserId", required = false) Integer updatedUserId,
            MultipartRequest multipartRequest) {
        log.info("ProtocolManagementController.update?id={}&protocolFileName={}&displayPosition={}&protocolFilePath={}&updatedUserId={}", 
                id, protocolFileName, displayPosition, protocolFilePath, updatedUserId);
        
        try {
            ProtocolManagement protocolManagement = new ProtocolManagement();
            protocolManagement.setId(id);
            protocolManagement.setProtocolFileName(protocolFileName);
            protocolManagement.setDisplayPosition(displayPosition);
            protocolManagement.setProtocolFilePath(protocolFilePath);
            protocolManagement.setUpdatedUserId(updatedUserId);
            
            boolean result = protocolManagementService.updateProtocol(multipartRequest, protocolManagement);
            
            if (result) {
                return R.success("修改成功");
            } else {
                return R.fail("修改失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("修改协议失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("修改协议失败", e);
            return R.fail("修改失败: " + e.getMessage());
        }
    }

    @ApiOperation("删除协议")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "协议ID", dataType = "Integer", paramType = "query", required = true)
    })
    @PostMapping("/delete")
    public R<Boolean> delete(@RequestParam("id") Integer id) {
        log.info("ProtocolManagementController.delete?id={}", id);
        
        try {
            boolean result = protocolManagementService.deleteProtocol(id);
            
            if (result) {
                return R.success("删除成功");
            } else {
                return R.fail("删除失败");
            }
        } catch (IllegalArgumentException e) {
            log.error("删除协议失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("删除协议失败", e);
            return R.fail("删除失败: " + e.getMessage());
        }
    }

//    @ApiOperation("批量删除协议")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "ids", value = "协议ID列表(逗号分隔)", dataType = "String", paramType = "query", required = true, example = "1,2,3")
//    })
//    @PostMapping("/batchDelete")
//    public R<Boolean> batchDelete(@RequestParam("ids") String ids) {
//        log.info("ProtocolManagementController.batchDelete?ids={}", ids);
//
//        try {
//            boolean result = protocolManagementService.batchDeleteProtocol(ids);
//
//            if (result) {
//                return R.success("批量删除成功");
//            } else {
//                return R.fail("批量删除失败");
//            }
//        } catch (IllegalArgumentException e) {
//            log.error("批量删除协议失败", e);
//            return R.fail(e.getMessage());
//        } catch (Exception e) {
//            log.error("批量删除协议失败", e);
//            return R.fail("批量删除失败: " + e.getMessage());
//        }
//    }

    @ApiOperation("校验文件名是否重复")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "protocolFileName", value = "协议文件名", dataType = "String", paramType = "query", required = true)
    })
    @GetMapping("/checkFileNameDuplicate")
    public R<Boolean> checkFileNameDuplicate(@RequestParam("protocolFileName") String protocolFileName) {
        log.info("ProtocolManagementController.checkFileNameDuplicate?protocolFileName={}", protocolFileName);

        try {
            Boolean result = protocolManagementService.checkFileNameDuplicate(protocolFileName);
            return R.data(result);
        } catch (IllegalArgumentException e) {
            log.error("校验文件名失败", e);
            return R.fail(e.getMessage());
        } catch (Exception e) {
            log.error("校验文件名失败", e);
            return R.fail("校验失败: " + e.getMessage());
        }
    }
}

