package digital.laboratory.platform.imr.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import digital.laboratory.platform.common.core.util.R;
import digital.laboratory.platform.common.log.annotation.SysLog;
import digital.laboratory.platform.common.mybatis.security.service.DLPUser;
import digital.laboratory.platform.imr.dto.QueryApplyDTO;
import digital.laboratory.platform.imr.dto.ReviewApprovalDTO;
import digital.laboratory.platform.imr.entity.SampleApply;
import digital.laboratory.platform.imr.enums.ApplyStatus;
import digital.laboratory.platform.imr.service.ReviewApprovalService;
import digital.laboratory.platform.imr.service.SampleApplyService;
import digital.laboratory.platform.imr.vo.SampleApplyVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Set;

/**
 * 自定义审核/审批控制层
 * 这个controller应用与检材申请的审核审批
 * 外带+销毁
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/review_approval" )
@Api(value = "review_approval", tags = "样本申请审核审批")
public class ReviewApprovalController {

    private final ReviewApprovalService reviewApprovalService;
    private final SampleApplyService sampleApplyService;

    /*
    ---------------审核模块分页(加权限)------------------
     */

    /**
     *
     */
 /*   @ApiOperation(value = "一级审核员分页查询", notes = "一级审核员分页查询")
    @GetMapping("firstAudit/page" )
    @PreAuthorize("@pms.hasPermission('imr_sample_apply_get_firstAudit')" )
    public R<IPage<SampleApplyVO>> getPage( @RequestBody SampleApplyQueryDTO dto) {

       return null;
    }*/






    @ApiOperation(value = "查询申请详情", notes = "查询申请详情")
    @SysLog("查询申请详情" )
    @GetMapping("/getDetail")
    @PreAuthorize("@pms.hasPermission('imr_review_and_approval')" )
    public R<SampleApplyVO> getDetail(String id) {

        if(id==null){
            throw new RuntimeException(String.format("申请id不能为空" ));
        }

        SampleApplyVO sampleApply = sampleApplyService.getDetail(id);

        return R.ok(sampleApply);
    }

    @ApiOperation(value = "审核分页查询", notes = "审核分页查询")
    @GetMapping("/page" )
    @PreAuthorize("@pms.hasPermission('imr_review_and_approval')" )
    public R<IPage<SampleApplyVO>> getAuditPage(QueryApplyDTO dto, HttpServletRequest theHttpServletRequest) {
        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        IPage<SampleApplyVO> page = reviewApprovalService.auditPage(dto, dlpUser);
        return R.ok(page,"查询成功");
    }

    /**
     * 审核审批
     * @param dto
     * @param theHttpServletRequest
     * @return
     */
    @ApiOperation(value = "检材申请审核审批", notes = "检材申请审核审批")
    @PutMapping("/sampleApply/approval" )
    @PreAuthorize("@pms.hasPermission('imr_review_and_approval')" )
    public R applyApproval(@RequestBody ReviewApprovalDTO dto, HttpServletRequest theHttpServletRequest) {

        Principal principal = theHttpServletRequest.getUserPrincipal();
        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        //查找对应的申请
        SampleApply sampleApply = sampleApplyService.getById(dto.getApplyId());
        ApplyStatus applicationStatus = null;
        if(sampleApply == null){
            return R.failed("当前申请数据不存在！");
        }

        applicationStatus = sampleApply.getApplicationStatus();
        if(applicationStatus == ApplyStatus.TO_BE_SUBMITTED || applicationStatus == ApplyStatus.WITHDRAWN){
            return R.failed("该申请并未提交审核或已撤回申请，请提交申请后在审核！");
        }
        if (!ApplyStatus.getPendingApprovalStatuses().contains(applicationStatus)) {
            return R.failed("该申请已经审核过，请勿重复操作！");
        }


        Set<String> permissions = dlpUser.getPermissions();//判断权限

        SampleApplyVO sampleApplyVO = null;

        for (String permission : permissions) {
            if ("imr_sample_apply_first_audit".equals(permission) && applicationStatus.equals(ApplyStatus.FIRST_LEVEL)) {
                //一级审核员权限和当前申请状态为待一级审核
                sampleApplyVO = reviewApprovalService.firstAudit(dto, sampleApply, dlpUser);
                break;
            } else if ("imr_sample_apply_secondary_audit".equals(permission) && applicationStatus.equals(ApplyStatus.SECOND_LEVEL)) {
                //二级审核员权限和当前申请状态为待二级审核
                reviewApprovalService.secondaryAudit(dto, sampleApply, dlpUser);
                break;
            }else if ("imr_sample_apply_approval".equals(permission) && applicationStatus.equals(ApplyStatus.PENDING_APPROVAL)) {
                //审批人权限和当前申请状态为待审批
                reviewApprovalService.approval(dto, sampleApply, dlpUser);
                break;
            }
        }
        return R.ok(sampleApplyVO,"审核成功");
    }
}
