package digital.laboratory.platform.reagent.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
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.reagent.dto.AuditAndApproveDTO;
import digital.laboratory.platform.reagent.dto.CentralizedRequestDTO;
import digital.laboratory.platform.reagent.entity.CentralizedRequest;
import digital.laboratory.platform.reagent.entity.DetailsOfCentralized;
import digital.laboratory.platform.reagent.service.CentralizedRequestService;
import digital.laboratory.platform.reagent.service.DetailsOfCentralizedService;
import digital.laboratory.platform.reagent.vo.CentralizedRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
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.List;

/**
 * (集中采购申请)
 *
 * @author Zhang Xiaolong created at  2023-03-10
 * @describe (集中采购申请) 前端控制器
 * <p>
 * 这是与表示层的接口, 不应该接业务逻辑写在这里, 业务逻辑应该写在 service 中
 * 这里写什么:
 * 为前端提供数据, 接受前端的数据
 * 为前端提供的数据, 从 service 取得后, 可以做一些适当的加工, 这种加工不是业务层面的, 只能是数据格式上, 为方便前端处理
 * 接受前端的数据, 每一个函数的参数可以先做一些整理后, 再调用 service 中的函数。这里对参数的整理, 应该只是格式上的, 而不能是业务上的
 * 数据层在 mapper 中, 数据层不涉及业务, 只管技术上的 对象<->表 之间的转换
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/centralized_request")
@Api(value = "centralized_request", tags = "集中采购申请管理")
public class CentralizedRequestController {

    @Autowired
    private final CentralizedRequestService centralizedRequestService;

    @Autowired
    private final DetailsOfCentralizedService detailsOfCentralizedService;

    /**
     * 通过id查询(集中采购申请)
     *
     * @param centralizedRequestId id
     * @return R
     */
    @ApiOperation(value = "通过id查询集中采购申请", notes = "通过id查询集中采购申请")
    @GetMapping("/{centralizedRequestId}")
//    @PreAuthorize("@pms.hasPermission('reagent_centralized_request_get')")
    public R<CentralizedRequestVO> getById(@PathVariable("centralizedRequestId") String centralizedRequestId, HttpServletRequest theHttpServletRequest) {

        Principal principal = theHttpServletRequest.getUserPrincipal();

        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        CentralizedRequestVO vo = centralizedRequestService.getCentralizedRequestVO(centralizedRequestId);

        if (vo != null) {
            return R.ok(vo);
        } else {
            return R.failed("未查询到该数据");
        }
    }

    /**
     * 分页查询
     *
     * @param page               分页对象
     * @param centralizedRequest 集中采购申请
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
//    @PreAuthorize("@pms.hasPermission('CentralizedPurchaseRequestList')")
    public R<IPage<CentralizedRequestVO>> getCentralizedRequestPage(Page<CentralizedRequest> page,String orgName, CentralizedRequest centralizedRequest, HttpServletRequest theHttpServletRequest) {

        Principal principal = theHttpServletRequest.getUserPrincipal();

        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if (orgName!=null){

            IPage<CentralizedRequestVO> centralizedRequestVOPage = centralizedRequestService.getCentralizedRequestVOPage(page, Wrappers.<CentralizedRequest>query()
                    .eq("create_by", dlpUser.getId()).orderByDesc("create_time")
                    .eq("orgName",orgName));

            return R.ok(centralizedRequestVOPage);
        }

        IPage<CentralizedRequestVO> centralizedRequestVOPage = centralizedRequestService.getCentralizedRequestVOPage(page, Wrappers.<CentralizedRequest>query()
                .eq("create_by", dlpUser.getId()).orderByDesc("create_time"));


        return R.ok(centralizedRequestVOPage);

    }

    /**
     * 分页查询
     *
     * @param orgName               分页对象
     * @param orgName 集中采购申请
     * @return
     */
    @ApiOperation(value = "采购计划整合集中采购申请分页查询", notes = "采购计划整合集中采购申请分页查询")
    @GetMapping("/list")
//    @PreAuthorize("@pms.hasPermission('CentralizedPurchaseRequestList')")
    public R<List<CentralizedRequestVO>> getCentralizedRequestVOPage(String orgName,HttpServletRequest theHttpServletRequest) {

        Principal principal = theHttpServletRequest.getUserPrincipal();

        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if (orgName!=null){


            List<CentralizedRequestVO> centralizedRequestVOList = centralizedRequestService.getOrgVOList(Wrappers.<CentralizedRequest>query().orderByDesc("create_time"),orgName);

            return R.ok(centralizedRequestVOList);
        }

        List<CentralizedRequestVO> centralizedRequestVOList = centralizedRequestService.getCentralizedRequestVOList(Wrappers.<CentralizedRequest>query()
               .orderByDesc("create_time"));

        return R.ok(centralizedRequestVOList);

    }


    /**
     * 新增(集中采购申请)
     *
     * @param centralizedRequestDTOList 集中采购申请
     * @return R
     */
    @ApiOperation(value = "保存集中采购申请", notes = "保存集中采购申请")
    @SysLog("新增集中采购申请")
    @PostMapping
//    @PreAuthorize("@pms.hasPermission('reagent_centralized_request_add')")
    public R<CentralizedRequest> postAddObject(@RequestBody List<CentralizedRequestDTO> centralizedRequestDTOList, HttpServletRequest theHttpServletRequest) {

        Principal principal = theHttpServletRequest.getUserPrincipal();

        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        CentralizedRequest centralizedRequest = centralizedRequestService.addRequest(centralizedRequestDTOList, dlpUser);

        if (centralizedRequest != null) {
            return R.ok(centralizedRequest, "保存成功");
        } else {
            return R.failed(centralizedRequest, "保存失败");
        }
    }

    /**
     * 新增集中采购申请明细
     *
     * @param centralizedRequestDto 集中采购申请
     * @return R
     */
    @ApiOperation(value = "新增集中采购申请明细", notes = "新增集中采购申请明细")
    @SysLog("新增集中采购申请明细")
    @PostMapping("/details")
//    @PreAuthorize("@pms.hasPermission('reagent_details_of_centralized_add')")
    public R<DetailsOfCentralized> postAddDetails(@RequestBody CentralizedRequestDTO centralizedRequestDto, HttpServletRequest theHttpServletRequest) {

        DetailsOfCentralized detailsOfCentralized = centralizedRequestService.addDetailsById(centralizedRequestDto);

        if (detailsOfCentralized!=null) {
            return R.ok(detailsOfCentralized, "添加成功");
        } else {
            return R.failed(detailsOfCentralized, "添加失败");
        }
    }

    /**
     * 提交(集中采购申请)
     *
     * @param centralizedRequestDTOList 集中采购申请
     * @return R
     */
    @ApiOperation(value = "提交集中采购申请", notes = "提交集中采购申请")
    @SysLog("提交集中采购申请")
    @PostMapping("/commit")
//    @PreAuthorize("@pms.hasPermission('reagent_centralized_request_commit')")
    public R<CentralizedRequest> postCommitObject(@RequestBody List<CentralizedRequestDTO> centralizedRequestDTOList, HttpServletRequest theHttpServletRequest) {

        Principal principal = theHttpServletRequest.getUserPrincipal();

        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        CentralizedRequest centralizedRequest = centralizedRequestService.commitRequest(centralizedRequestDTOList, dlpUser);

        if (centralizedRequest != null) {
            return R.ok(centralizedRequest, "提交成功");
        } else {
            return R.failed("提交失败，请检查内容是否有误");
        }

    }

    /**
     * 修改(集中采购申请)
     *
     * @param centralizedRequestDto (集中采购申请)
     * @return R
     */
    @ApiOperation(value = "修改集中采购申请明细", notes = "修改集中采购申请明细")
    @SysLog("修改(集中采购申请)")
    @PutMapping
//    @PreAuthorize("@pms.hasPermission('reagent_centralized_request_edit')")
    public R<DetailsOfCentralized> putUpdateById(@RequestBody CentralizedRequestDTO centralizedRequestDto, HttpServletRequest theHttpServletRequest) {

        Principal principal = theHttpServletRequest.getUserPrincipal();

        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        DetailsOfCentralized detailsOfCentralized = centralizedRequestService.editDetailsById(centralizedRequestDto);

        if (detailsOfCentralized != null) {
            return R.ok(detailsOfCentralized, "修改成功");
        } else {
            return R.failed("修改失败");
        }
    }

    /**
     * 通过id删除(集中采购申请)
     *
     * @param centralizedRequestId id
     * @return R
     */
    @ApiOperation(value = "通过id删除集中采购申请", notes = "通过id删除集中采购申请")
    @SysLog("通过id删除集中采购申请")
    @DeleteMapping("/{centralizedRequestId}")
//    @PreAuthorize("@pms.hasPermission('reagent_centralized_request_del')")
    public R<String> deleteById(@PathVariable String centralizedRequestId, HttpServletRequest theHttpServletRequest) {

        Principal principal = theHttpServletRequest.getUserPrincipal();

        DLPUser dlpUser = (DLPUser) ((OAuth2Authentication) principal).getUserAuthentication().getPrincipal();

        if (centralizedRequestService.delRequestById(centralizedRequestId)) {
            return R.ok("删除成功");
        } else return R.failed("删除失败");

    }

    /**
     * 通过id删除集中采购申请明细
     *
     * @param detailsOfCentralizedId
     * @return R
     */
    @ApiOperation(value = "通过id删除集中采购申请明细", notes = "通过id删除集中采购申请明细")
    @SysLog("通过id删除(集中采购申请)")
    @DeleteMapping("/details/{detailsOfCentralizedId}")
//    @PreAuthorize("@pms.hasPermission('reagent_details_of_centralized_del')")
    public R<DetailsOfCentralized> deleteDetailsById(@PathVariable String detailsOfCentralizedId, HttpServletRequest theHttpServletRequest) {

        DetailsOfCentralized oldDetailsOfCentralized = detailsOfCentralizedService.getById(detailsOfCentralizedId);

        if (detailsOfCentralizedService.removeById(oldDetailsOfCentralized)) {
            return R.ok(oldDetailsOfCentralized, "删除成功");
        } else {
            return R.failed(oldDetailsOfCentralized, "删除失败");
        }
    }
}




