package digital.laboratory.platform.imr.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.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.ArrayList;
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();


        Page<SampleApply> page = new Page<>(dto.getCurrent(),dto.getSize());
        QueryWrapper<SampleApply> queryWrapper = new QueryWrapper<>();
        ArrayList<Integer> list = new ArrayList<>();

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

        //System.out.println(permissions);
        for (String permission : permissions) {
            if ("imr_sample_apply_first_audit".equals(permission)) {
                //
                queryWrapper.eq("apply_type",1);
                if(dto.getStatus()==null){//审核初页面(不应该有销毁申请)
                    queryWrapper.eq("application_status",1);
                }else {//点击通过页面时
                    if(dto.getStatus()==0){
                        //返回全部
                        queryWrapper.and(Wrapper->Wrapper.le("application_status",-2)
                                .or().ge("application_status",2)
                        );
                    }else {
                        //通过status==1/不通过status==-1
                        if(dto.getStatus()==1){
                            queryWrapper.ge("application_status",2);
                        }
                        if(dto.getStatus()==-1){
                            queryWrapper.le("application_status",-2);
                        }
                    }
                }
                break;
            } else if ("imr_sample_apply_secondary_audit".equals(permission)) {
                //二级审核员(不应该有销毁申请)
                queryWrapper.eq("apply_type",1);
                if(dto.getStatus()==null){
                    queryWrapper.eq("application_status",2);
                }else {
                    if(dto.getStatus()==0){
                        //返回全部
                        queryWrapper.and(Wrapper->Wrapper.le("application_status",-3)
                                .or().ge("application_status",3)
                        );
                        /*queryWrapper.le("application_status",-3).or()
                                .ge("application_status",3);//大于=3的后面所有*/
                    }else {
                        //通过status==1/不通过status==-1
                        if(dto.getStatus()==1){
                            queryWrapper.ge("application_status",3);
                        }
                        if(dto.getStatus()==-1){
                            queryWrapper.le("application_status",-3);
                        }
                    }
                }
                break;
            }else if ("imr_sample_apply_approval".equals(permission)) {
                //审批人
                if(dto.getStatus()==null){
                    queryWrapper.eq("application_status",3);
                }else {
                    if(dto.getStatus()==0){
                        list.add(-4);//二级不通过
                        list.add(4);//通过/不通过
                        queryWrapper.in("application_status",list);
                    }else {
                        //通过status==1/不通过status==-1
                        if(dto.getStatus()==1){
                            queryWrapper.eq("application_status",4);
                        }
                        if(dto.getStatus()==-1){
                            queryWrapper.eq("application_status",-4);
                        }
                    }
                }
                break;
            }
        }
        //判断权限查询条件设置完毕
        queryWrapper.between(dto.getBeginDate()!=null && dto.getFinishDate()!=null,"application_date",dto.getBeginDate(),dto.getFinishDate());
        queryWrapper.orderByDesc("application_date");
        IPage<SampleApplyVO> applyVOPage = sampleApplyService.getApplyPage(page, queryWrapper);
        return R.ok(applyVOPage,"查询成功");
    }

    /**
     * 审核审批
     * @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();

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

        SampleApplyVO sampleApplyVO = null;

        for (String permission : permissions) {
            if ("imr_sample_apply_first_audit".equals(permission)) {
                //一级审核员
                sampleApplyVO = reviewApprovalService.firstAudit(dto, dlpUser);
                break;
            } else if ("imr_sample_apply_secondary_audit".equals(permission)) {
                //二级审核员
                reviewApprovalService.secondaryAudit(dto, dlpUser);
                break;
            }else if ("imr_sample_apply_approval".equals(permission)) {
                //审批人
                reviewApprovalService.approval(dto,dlpUser);
                break;
                }
            }
        return R.ok(sampleApplyVO,"审核成功");
    }
}
