package com.tofly.qualitycontrol.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.qualitycontrol.dto.*;
import com.tofly.qualitycontrol.entity.CertificationOrder;
import com.tofly.qualitycontrol.entity.Massaudit;
import com.tofly.qualitycontrol.entity.RectifyOrder;
import com.tofly.qualitycontrol.service.IRectifyOrderService;
import com.tofly.qualitycontrol.util.QualityControlUtil;
import com.tofly.qualitycontrol.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.tofly.qualitycontrol.common.QualityControlConstant.FAILED;
import static com.tofly.qualitycontrol.common.QualityControlConstant.SUCCESS;

/**
 * 整改工单控制器
 *
 * @author B
 */
@RestController
@RequestMapping("/rectifyOrder")
@Api(value = "整改工单接口", tags = "整改工单接口")
@RequiredArgsConstructor
public class RectifyOrderController {

    private final IRectifyOrderService service;

    /**
     * 质检工单整改下达汇总列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "质检工单整改下达汇总列表", notes = "", httpMethod = "POST")
    @PostMapping("/issueSummary")
    public ResultRespone issueSummary(@RequestBody OrderDto dto) {
        List<ReportSummaryVo> summaryVos = service.getIssueSummary(dto);
        return ResultRespone.success(summaryVos);
    }


    /**
     * 质检工单整改处置汇总列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "质检工单整改处置汇总列表", notes = "", httpMethod = "POST")
    @PostMapping("/rectifySummary")
    public ResultRespone rectifySummary(@RequestBody OrderDto dto) {
        List<ReportSummaryVo> summaryVos = service.getRectifySummary(dto);
        return ResultRespone.success(summaryVos);
    }

    /**
     * 质检工单整改审核汇总列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "质检工单整改审核汇总列表", notes = "", httpMethod = "POST")
    @PostMapping("/auditSummary")
    public ResultRespone auditSummary(@RequestBody OrderDto dto) {
        List<ReportSummaryVo> summaryVos = service.getAuditSummary(dto);
        return ResultRespone.success(summaryVos);
    }

    /**
     * 质检工单整改验证汇总列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "质检工单整改验证汇总列表", notes = "", httpMethod = "POST")
    @PostMapping("/verifySummary")
    public ResultRespone verifySummary(@RequestBody OrderDto dto) {
        List<ReportSummaryVo> summaryVos = service.getVerifySummary(dto);
        return ResultRespone.success(summaryVos);
    }

    /**
     * 质检工单验证审核汇总列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "质检工单验证审核汇总列表", notes = "", httpMethod = "POST")
    @PostMapping("/validateSummary")
    public ResultRespone validateSummary(@RequestBody OrderDto dto) {
        List<ReportSummaryVo> summaryVos = service.getValidateSummary(dto);
        return ResultRespone.success(summaryVos);
    }

    /**
     * 第一版：下达环节只有一个审核人（废弃，不使用）
     *
     * @param rectifyOrder
     * @param fileList
     * @param executeAdvice
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(value = "处理意见(驳回时填写)", name = "executeAdvice", paramType = "query", dataType = "string", dataTypeClass = String.class)
    })
    @ApiOperation(value = "处理整改下达,推送消息,可上传文件", httpMethod = "POST")
    @PostMapping("/updateRectifyIssue")
    public ResultRespone updateRectifyIssue(@Valid @RequestPart RectifyOrder rectifyOrder, @RequestPart(value = "fileList", required = false) List<MultipartFile> fileList, @RequestParam(required = false) String executeAdvice) {
        Boolean flag = service.updateRectifyIssue(rectifyOrder, fileList, executeAdvice);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    /**
     * 第二版 当前审核人可以指定下一级审核人，无级数限制（废弃，不使用）
     *
     * @param rectifyOrder
     * @param massaudit
     * @param fileList
     * @param executeAdvice
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(value = "处理意见(驳回时填写)", name = "executeAdvice", paramType = "query", dataType = "string", dataTypeClass = String.class)
    })
    @ApiOperation(value = "处理整改下达,推送消息,可上传文件", httpMethod = "POST")
    @PostMapping("/rectifyIssue")
    public ResultRespone updateRectifyIssue(@Valid @RequestPart RectifyOrder rectifyOrder, @RequestPart Massaudit massaudit, @RequestPart(value = "fileList", required = false) List<MultipartFile> fileList, @RequestParam(required = false) String executeAdvice) {
        Boolean flag = service.updateRectifyIssue(rectifyOrder, fileList, executeAdvice, massaudit);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    @ApiOperation(value = "处理整改下达,推送消息,可上传文件", httpMethod = "POST")
    @PostMapping("/newRectifyIssue")
    public ResultRespone updateRectifyIssue(@RequestPart NewRectifyIssueDto dto, @RequestPart(value = "fileList", required = false) List<MultipartFile> fileList) {
        return ResultRespone.success(service.updateRectifyIssue(dto, fileList));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "整改下达信息", notes = "", httpMethod = "GET")
    @GetMapping("/getRectifyIssueDetail")
    public ResultRespone<RectifyIssueOrderVO_D> getRectifyIssueDetail(@RequestParam Long id) {
        return ResultRespone.success(service.getRectifyIssueDetail(id), SUCCESS);
    }


    /**
     * 整改下达列表
     *
     * @param orderDto 查询条件
     * @param page     分页
     * @return
     */
    @ApiOperation(value = "整改下达分页和模糊查询", httpMethod = "POST")
    @PostMapping("/getRectifyIssueList")
    public ResultRespone<IPage<RectifyOrderListVo>> getRectifyIssueList(ReportOrderDto orderDto, Page<RectifyOrder> page) {
        return ResultRespone.success(service.getRectifyIssueList(orderDto, page), SUCCESS);
    }


    @ApiImplicitParams({
            @ApiImplicitParam(value = "处理意见(驳回时填写)", name = "executeAdvice", required = false, paramType = "query", dataType = "string", dataTypeClass = String.class)
    })
    @ApiOperation(value = "处理整改处置,推送消息,上传文件", notes = "", httpMethod = "POST")
    @PostMapping("/updateRectifyResult")
    public ResultRespone updateRectifyResult(@RequestPart @Valid RectifyOrder rectifyOrder, @RequestPart(value = "fileList", required = false) List<MultipartFile> fileList, @RequestParam(required = false) String executeAdvice, @RequestParam(required = false) String transferIdea) {
        Boolean flag = service.updateRectifyResult(rectifyOrder, fileList, executeAdvice, transferIdea);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "整改处置信息", notes = "", httpMethod = "GET")
    @GetMapping("/getRectifyResultDetail")
    public ResultRespone<RectifyResultOrderVO_D> getRectifyResultDetail(@RequestParam Long id) {
        return ResultRespone.success(service.getRectifyResultDetail(id), SUCCESS);
    }


    /**
     * 整改处置列表
     *
     * @param orderDto 查询条件
     * @param page     分页
     * @return
     */
    @ApiOperation(value = "整改处置分页和模糊查询", notes = "", httpMethod = "POST")
    @PostMapping("/getRectifyResultList")
    public ResultRespone getRectifyResultList(ReportOrderDto orderDto, Page<RectifyOrder> page) {
        return ResultRespone.success(service.getRectifyResultList(orderDto, page), SUCCESS);
    }


    @ApiImplicitParams({
            @ApiImplicitParam(value = "处理意见(驳回时填写)", name = "executeAdvice", required = false, paramType = "query", dataType = "string", dataTypeClass = String.class)
    })
    @ApiOperation(value = "处理整改审核,推送消息,驳回流程", notes = "", httpMethod = "POST")
    @PostMapping("/updateRectifyAudit")
    public ResultRespone updateRectifyAudit(@RequestBody @Valid RectifyOrder rectifyOrder, @RequestParam(required = false) String executeAdvice) {
        Boolean flag = service.updateRectifyAudit(rectifyOrder, executeAdvice);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "整改审核信息", notes = "", httpMethod = "GET")
    @GetMapping("/getRectifyAuditDetail")
    public ResultRespone<RectifyAuditOrderVO_D> getRectifyAuditDetail(@RequestParam Long id) {
        return ResultRespone.success(service.getRectifyAuditDetail(id), SUCCESS);
    }


    /**
     * 整改审核列表
     *
     * @param orderDto
     * @param page
     * @return
     */
    @ApiOperation(value = "整改审核分页和模糊查询", notes = "", httpMethod = "POST")
    @PostMapping("/getRectifyAuditList")
    public ResultRespone getRectifyAuditList(ReportOrderDto orderDto, Page page) {
        return ResultRespone.success(service.getRectifyAuditList(orderDto, page));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "处理意见(驳回时填写)", name = "executeAdvice", required = false, paramType = "query", dataType = "string", dataTypeClass = String.class)
    })
    @ApiOperation(value = "处理整改验证,驳回流程", notes = "", httpMethod = "POST")
    @PostMapping("/updateRectifyVerify")
    public ResultRespone updateRectifyVerify(@RequestBody @Valid RectifyOrder rectifyOrder, BindingResult bindingResult, @RequestParam(required = false) String executeAdvice) {
        if (bindingResult.hasErrors()) {
            return ResultRespone.failed(QualityControlUtil.getErrorStrings(bindingResult), FAILED);
        }
        Boolean flag = service.updateRectifyVerify(rectifyOrder, executeAdvice);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "整改验证信息", notes = "", httpMethod = "GET")
    @GetMapping("/getRectifyVerifyDetail")
    public ResultRespone<RectifyVerifyOrderVO_D> getRectifyVerifyDetail(@RequestParam Long id) {
        return ResultRespone.success(service.getRectifyVerifyDetail(id), SUCCESS);
    }


    /**
     * 整改验证查询列表
     *
     * @param orderDto 查询条件
     * @param page     分页
     * @return
     */
    @ApiOperation(value = "整改验证查询列表", notes = "", httpMethod = "POST")
    @PostMapping("/getRectifyVerifyList")
    public ResultRespone getRectifyVerifyList(ReportOrderDto orderDto, Page page) {

        return ResultRespone.success(service.getRectifyVerifyList(orderDto, page), SUCCESS);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "处理意见(驳回时填写)", name = "executeAdvice", required = false, paramType = "query", dataType = "string", dataTypeClass = String.class)
    })
    @ApiOperation(value = "验证审核,推送消息", notes = "", httpMethod = "POST")
    @PostMapping("/updateRectifyValidate")
    public ResultRespone updateRectifyValidate(@Valid @RequestBody RectifyOrder rectifyOrder, @RequestParam(required = false) String executeAdvice) {
        Boolean flag = service.updateRectifyValidate(rectifyOrder, executeAdvice);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    @ApiOperation(value = "验证审核,推送消息", httpMethod = "POST")
    @PostMapping("/rectifyValidate")
    public ResultRespone updateRectifyValidate(@RequestBody RectifyValidateDto dto) {
        Boolean flag = service.updateRectifyValidate(dto);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    @PostMapping("/newRectifyValidate")
    @ApiOperation(value = "验证审核,推送消息(最新)", httpMethod = "POST")
    public ResultRespone updateRectifyValidate(@RequestPart NewRectifyIssueDto dto, @RequestPart(value = "fileList", required = false) List<MultipartFile> fileList) {
        return ResultRespone.success(service.updateRectifyValidate(dto, fileList));
    }

    @PostMapping("/newAppRectifyValidate")
    @ApiOperation(value = "验证审核,推送消息(最新)", httpMethod = "POST")
    public ResultRespone updateAppRectifyValidate(@RequestBody NewRectifyIssueDto dto) {
        return ResultRespone.success(service.updateRectifyValidate(dto, null));
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "验证审核信息", notes = "", httpMethod = "GET")
    @GetMapping("/getRectifyValidateDetail")
    public ResultRespone<RectifyValidateOrderVO_D> getRectifyValidateDetail(@RequestParam Long id) {
        return ResultRespone.success(service.getRectifyValidateDetail(id), SUCCESS);
    }


    /**
     * 验证审核列表
     *
     * @param orderDto
     * @param page
     * @return
     */
    @ApiOperation(value = "验证审核列表", notes = "", httpMethod = "POST")
    @PostMapping("/getRectifyValidateList")
    public ResultRespone getRectifyValidateList(ReportOrderDto orderDto, Page page) {
        return ResultRespone.success(service.getRectifyValidateList(orderDto, page), SUCCESS);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "开始日期,如2021-02-01", name = "startDate", paramType = "query", dataType = "string", dataTypeClass = String.class),
            @ApiImplicitParam(value = "结束日期,如2021-05-01", name = "endDate", paramType = "query", dataType = "string", dataTypeClass = String.class),
            @ApiImplicitParam(value = "工单编号或客户编号", name = "number", paramType = "query", dataType = "string", dataTypeClass = String.class),
            @ApiImplicitParam(value = "业务环节", name = "currentProcess", paramType = "query", dataType = "string", dataTypeClass = String.class),
            @ApiImplicitParam(value = "工单总异常状态（取值 0 1 2 3)", name = "orderExceptionStatus", required = false, paramType = "query", dataType = "int", dataTypeClass = Integer.class),
    })
    @ApiOperation(value = "业务监控分页和模糊查询", notes = "", httpMethod = "POST")
    @PostMapping("/getBusinessMonitorList")
    public ResultRespone<IPage<BusinessMonitorVO_L>> getBusinessMonitorList(@RequestParam(required = false) String startDate, @RequestParam(required = false) String endDate, @RequestParam(required = false) String number, @RequestParam(required = false) String currentProcess, @RequestParam(required = false) Integer orderExceptionStatus, @RequestBody Page<CertificationOrder> page) {
        Date begdate = null;
        if (StringUtils.isNotEmpty(startDate)) {
            begdate = DateUtil.beginOfDay(DateUtil.parse(startDate));
        }
        Date enddate = null;
        if (StringUtils.isNotEmpty(endDate)) {
            enddate = DateUtil.endOfDay(DateUtil.parse(endDate));
        }

        return ResultRespone.success(service.getBusinessMonitorList(begdate, enddate, number, currentProcess, orderExceptionStatus, page), SUCCESS);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "业务监控", notes = "", httpMethod = "GET")
    @GetMapping("/getAllDetail")
    public ResultRespone<BusinessMonitorVO_D> getAllDetail(@RequestParam Long id) {
        return ResultRespone.success(service.getAllDetail(id), SUCCESS);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "认证编号", name = "certificationNumber", required = true, paramType = "query", dataType = "string", dataTypeClass = String.class)
    })
    @ApiOperation(value = "通过认证编号获取认证详情", notes = "", httpMethod = "GET")
    @GetMapping("/getCertificationOrderDetail")
    public ResultRespone<CertificationOrderVO_D> getCertificationOrderDetail(@RequestParam String certificationNumber) {
        return ResultRespone.success(service.getCertificationOrderDetail(certificationNumber), SUCCESS);
    }

    /**
     * 每天10点定时发消息 提醒超时任务
     */
    @Scheduled(cron = "0 0 10 * * ?")
    @GetMapping("/task")
    public void remindOverdueTasks() {
        service.remindOverdueTasks();
    }


    /**
     * 部门工单整改率
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "部门工单整改率", httpMethod = "POST")
    @PostMapping("/orderRectifyList")
    public ResultRespone<List<RectifySummaryVo>> orderRectify(OrderReportDto dto) {
        if (dto.getEndDate() != null) {
            dto.setEndDate(DateUtil.endOfDay(dto.getEndDate()));
        }
        if (dto.getStartDate() == null || dto.getEndDate() == null || dto.getEndDate().getTime() < dto.getStartDate().getTime()) {
            return ResultRespone.failed("时间错误");
        }
        return ResultRespone.success(service.getOrderRectify(dto));
    }


    /**
     * 经济社会效益
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "经济社会效益", notes = "", httpMethod = "POST")
    @PostMapping("/economyBenefit")
    public ResultRespone<List<Map<String, Object>>> economyBenefit(@RequestBody OrderReportDto dto) {
        if (dto.getEndDate() != null) {
            dto.setEndDate(DateUtil.endOfMonth(dto.getEndDate()));
        }
        return ResultRespone.success(service.getEconomyBenefit(dto));
    }

}
