package com.openhis.web.basicmanage.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.core.common.core.domain.R;
import com.core.common.utils.SecurityUtils;
import com.openhis.administration.domain.InvoiceSegment;
import com.openhis.administration.service.IInvoiceSegmentService;
import com.openhis.web.basicmanage.domain.InvoiceSegmentDeleteRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 发票段管理控制器
 *
 * @author system
 * @date 2025-11-18
 */
@RestController
@RequestMapping("/basicmanage/invoice-segment")
public class InvoiceSegmentController {

    @Autowired
    private IInvoiceSegmentService invoiceSegmentService;

    /**
     * 分页查询发票段列表（带用户角色权限过滤）
     *
     * @param pageNo   页码
     * @param pageSize 每页条数
     * @param request  请求对象
     * @return 发票段列表
     */
    @GetMapping("/page")
    public R<?> selectInvoiceSegmentPage(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "100") Integer pageSize,
            HttpServletRequest request) {
        
        // 获取当前用户ID
        Long userId = SecurityUtils.getUserId();
        
        // 判断当前用户是否为管理员
        boolean isAdmin = SecurityUtils.isAdmin(userId);
        
        // 分页查询发票段列表
        Page<InvoiceSegment> page = new Page<>(pageNo, pageSize);
        return R.ok(invoiceSegmentService.selectInvoiceSegmentPage(page, isAdmin, userId));
    }
    
    /**
     * 新增发票段
     *
     * @param invoiceSegment 发票段信息
     * @return 操作结果
     */
    @PostMapping("/add")
    public R<?> addInvoiceSegment(@RequestBody InvoiceSegment invoiceSegment) {
        // 设置创建人信息
        invoiceSegment.setCreateBy(SecurityUtils.getUsername());
        int result = invoiceSegmentService.insertInvoiceSegment(invoiceSegment);
        return result > 0 ? R.ok() : R.fail();
    }
    
    /**
     * 修改发票段
     *
     * @param invoiceSegment 发票段信息
     * @return 操作结果
     */
    @PostMapping("/update")
    public R<?> updateInvoiceSegment(@RequestBody InvoiceSegment invoiceSegment) {
        // 设置更新人信息
        invoiceSegment.setUpdateBy(SecurityUtils.getUsername());
        int result = invoiceSegmentService.updateInvoiceSegment(invoiceSegment);
        return result > 0 ? R.ok() : R.fail();
    }
    
    /**
     * 删除发票段
     */
    @PostMapping("/delete")
    public R<?> delete(@RequestBody InvoiceSegmentDeleteRequest request) {
        int rows = invoiceSegmentService.deleteInvoiceSegmentByIds(request.getIds());
        return rows > 0 ? R.ok("删除成功") : R.fail("删除失败");
    }
}