package com.casic.missiles.controller.business;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.casic.missiles.core.base.controller.ExportController;
import com.casic.missiles.core.page.PageFactory;
import com.casic.missiles.core.page.PageInfoBT;
import com.casic.missiles.dto.*;
import com.casic.missiles.dto.business.certificate.CertificateMonitorResponse;
import com.casic.missiles.dto.business.certificate.CertificateReportApprovalRequest;
import com.casic.missiles.dto.business.certificate.CertificateReportResponse;
import com.casic.missiles.dto.customer.CertificationResponse;
import com.casic.missiles.dto.customer.sample.CustomerSampleIdRequest;
import com.casic.missiles.dto.flowable.ApprovalDeleteRequest;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.exception.BusinessException;
import com.casic.missiles.model.business.BusinessCertificateReport;
import com.casic.missiles.model.exception.enums.CoreExceptionEnum;
import com.casic.missiles.service.business.IBusinessCertificateReportService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 业务管理-证书报告 前端控制器
 * </p>
 *
 * @author zt
 * @since 2023-02-02
 */
@RestController
@Api(tags = "证书报告模块")
@RequestMapping("/business/certificateReport")
public class BusinessCertificateReportController extends ExportController {
    @Resource
    private IBusinessCertificateReportService certificateReportService;

    @ApiOperation("证书报告记录导出")
    @PostMapping("/listExport")
    @ResponseBody
    public void export(@RequestBody @Valid CertificateReportApprovalRequest request , HttpServletResponse response) throws IOException {

        certificateReportService.originExport(request, response);
    }

    @ApiOperation("证书报告保存（保存至草稿箱）")
    @PostMapping("/save")
    @ResponseBody
    public ReturnDTO  save(@RequestBody @Valid BusinessCertificateReport certificateReport, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return  ReturnUtil.success(certificateReportService.saveCertificateReport(certificateReport));
    }

    /**
     * 草稿箱文件编辑
     */
    @ApiOperation("草稿箱文件更新")
    @PostMapping("/draftUpdate")
    @ResponseBody
    public ReturnDTO draftUpdate(@RequestBody @Valid BusinessCertificateReport certificateReport, BindingResult bindingResult) {
        Assert.isFalse(Objects.isNull(certificateReport.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return certificateReportService.draftUpdate(certificateReport);

    }

    @ApiOperation("证书报告提交")
    @PostMapping("/submit")
    @ResponseBody
    public ReturnDTO certificateReportSubmit(@RequestBody @Valid BaseApprovalSubmitRequest request, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return certificateReportService.submitCertificateReport(request);
    }


    @ApiOperation("证书报告批量删除")
    @PostMapping("/batchDelete")
    @ResponseBody
    public ReturnDTO supplierBatchDelete(@RequestBody @Valid IdsDTO idsDTO) {
        Assert.isFalse(CollectionUtils.isEmpty(idsDTO.getIds()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        return certificateReportService.deleteBatchTraceSupplier(idsDTO.getIds());
    }

    @ApiOperation("证书报告详情")
    @PostMapping("/detail")
    @ResponseBody
    public ReturnDTO<BusinessCertificateReport> supplierDetail(@RequestBody @Valid IdDTO idDTO) {
        Assert.isFalse(Objects.isNull(idDTO.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        return ReturnUtil.success(certificateReportService.certificateReportDetail(idDTO.getId()));
    }

    @ApiOperation("证书报告审批列表及详情中基础信息（分页）")
    @PostMapping("/approval/listPage")
    @ResponseBody
    public ReturnDTO<PageInfoBT<CertificateReportResponse>> approvalListPage(@RequestBody @Valid CertificateReportApprovalRequest request, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        Page<CertificateReportResponse> page = PageFactory.defaultPage();
        List<CertificateReportResponse> responseList = certificateReportService.approvalListPage(page, request);
        page.setRecords(responseList);
        return ReturnUtil.success(super.packForBT(page));
    }

    /**
     * 删除（发起者或具有删除权限的用户可以删除，已通过/未通过状态不可删除）
     * 前端控制按钮权限
     */
    @ApiOperation("审批操作-删除")
    @PostMapping("/approval/operate/delete")
    @ResponseBody
    public ReturnDTO delete(@RequestBody @Valid ApprovalDeleteRequest request, BindingResult bindingResult) {
        if(bindingResult.hasErrors()){
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return certificateReportService.approvalDelete(request);
    }

    /**
     * 审批操作-编辑
     *      驳回的流程放置在未通过列表中，实现进行编辑后自动审核通过发起人节点
     */
    @ApiOperation("未通过证书报告编辑（驳回后的证书报告重新编辑，仅未通过列表中的编辑按钮可调用）")
    @PostMapping("/failUpdate")
    @ResponseBody
    public ReturnDTO failUpdate(@RequestBody @Valid BusinessCertificateReport certificateReport, BindingResult bindingResult) {
        Assert.isFalse(Objects.isNull(certificateReport.getId()), () -> {
            throw new BusinessException(BusinessExceptionEnum.ID_NULL);
        });
        if (bindingResult.hasErrors()) {
            throw new BusinessException(CoreExceptionEnum.REQUEST_NULL.getCode(), bindingResult.getFieldError().getDefaultMessage());
        }
        return certificateReportService.failUpdate(certificateReport);
    }



    @ApiOperation("根据样品id/客户id查询检定证书")
    @PostMapping("/certificateRecordsById")
    public ReturnDTO<PageInfoBT<CertificationResponse>> certificationBySampleId(@RequestBody CustomerSampleIdRequest customerSampleIdRequest) throws Exception{
        return ReturnUtil.success(super.packForBT(certificateReportService.certificateRecordsById(customerSampleIdRequest)));
    }



    @ApiOperation("根据样品id查询证书监控列表")
    @PostMapping("/certificateMonitorsById")
    public ReturnDTO<PageInfoBT<CertificateMonitorResponse>> certificateMonitorsById(@RequestBody CustomerSampleIdRequest customerSampleIdRequest) throws Exception{
        return ReturnUtil.success(super.packForBT(certificateReportService.certificateMonitorsById(customerSampleIdRequest)));
    }

}
