package com.tofly.qualitycontrol.controller;

import cn.hutool.core.collection.CollUtil;
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.service.ICertificationOrderService;
import com.tofly.qualitycontrol.service.ICollectionNumberSummaryService;
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.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
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("/certificationOrder")
@Api(value = "认证工单接口", tags = "认证工单接口")
@RequiredArgsConstructor
public class CertificationOrderController {

    private final ICertificationOrderService certificationOrderService;

    private final ICollectionNumberSummaryService collectionNumberSummaryService;


    /**
     * 质检工单汇总列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "质检工单汇总列表", notes = "", httpMethod = "POST")
    @PostMapping("/summary")
    public ResultRespone getOrderSummaryList(@RequestBody OrderDto dto) {
        List<OrderSummaryVo> listVos = certificationOrderService.orderSummaryList(dto);
        return ResultRespone.success(listVos);
    }


    /**
     * 质检工单上报汇总列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "质检工单上报汇总列表", notes = "", httpMethod = "POST")
    @PostMapping("/reportSummary")
    public ResultRespone getOrderReportSummary(@RequestBody OrderDto dto) {
        List<ReportSummaryVo> summaryVos = certificationOrderService.orderReportSummary(dto);
        return ResultRespone.success(summaryVos);
    }

    /**
     * 质检工单检查汇总列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "质检工单检查汇总列表", notes = "", httpMethod = "POST")
    @PostMapping("/inspectSummary")
    public ResultRespone getInspectSummary(@RequestBody OrderDto dto) {
        List<ReportSummaryVo> summaryVos = certificationOrderService.orderInspectSummary(dto);
        return ResultRespone.success(summaryVos);
    }

    @ApiOperation(value = "服务调用工单上报", notes = "", httpMethod = "POST")
    @PostMapping("/orderSave")
    public ResultRespone saveCertificationExternalOrder(@Valid @RequestBody CertificationOrderDto dto) {
        if (dto.getDispatchPersonId() == null) {
            return ResultRespone.failed("DispatchPerson is null");
        }
        if (CollUtil.isEmpty(dto.getClients())) {
            return ResultRespone.failed("Clients is null");
        }
        if (StringUtils.isEmpty(dto.getYearMonth())) {
            return ResultRespone.failed("YearMonth is null");
        }
        Boolean flag = certificationOrderService.saveCertificationOrder(dto);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    @ApiOperation(value = "工单上报", notes = "", httpMethod = "POST")
    @PostMapping("/save")
    public ResultRespone saveCertificationOrder(@Valid @RequestBody CertificationOrderDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultRespone.failed(QualityControlUtil.getErrorStrings(bindingResult), FAILED);
        }
        Boolean flag = certificationOrderService.saveCertificationOrder(dto);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    /**
     * 工单上报列表
     *
     * @param orderDto 工单上报列表
     * @param page
     * @return
     */
    @ApiOperation(value = "工单上报列表", notes = "", httpMethod = "POST")
    @PostMapping("/getOrderList")
    public ResultRespone<IPage<BusinessMonitorVO_L>> getOrderList(ReportOrderDto orderDto, Page page) {
        return ResultRespone.success(certificationOrderService.getOrderList(orderDto, page), SUCCESS);
    }


    @ApiOperation(value = "检验记录,可新增整改工单,上传文件,推送消息", notes = "附带上传文件,推送消息,若质检不合格新增整改工单", httpMethod = "POST")
    @PostMapping("/certify")
    public ResultRespone certifyOrder(@Valid @RequestPart CertificationOrder certificationOrder, @RequestPart(value = "fileList", required = false) List<MultipartFile> fileList) {
        Boolean flag = certificationOrderService.certifyOrder(certificationOrder, fileList);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    /**
     * 批量添加检验记录
     *
     * @param dto
     * @param fileList
     * @return
     */
    @ApiOperation(value = "检验记录批量提交问题", notes = "附带上传文件,推送消息,若质检不合格新增整改工单", httpMethod = "POST")
    @PostMapping("/certifyBatch")
    public ResultRespone certifyOrderBatch(@Valid @RequestPart CertifyOrderDto dto, @RequestPart(value = "fileList", required = false) List<MultipartFile> fileList) {
        Object flag = certificationOrderService.certifyOrderBatch(dto, fileList);
        return flag instanceof String ? ResultRespone.failed(flag, FAILED) : ResultRespone.success(flag, SUCCESS);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "工单信息", notes = "", httpMethod = "GET")
    @GetMapping("/detail")
    public ResultRespone<CertificationOrderVO_D> getDetail(@RequestParam Long id) {
        return ResultRespone.success(certificationOrderService.getDetail(id), SUCCESS);
    }

    /**
     * 工单详细信息
     *
     * @param id   工单id
     * @param type 工单类型，
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(value = "主键id", name = "id", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class),
            @ApiImplicitParam(value = "工单类型，0:工单上报，1:其它", name = "type", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "工单详细信息", httpMethod = "GET")
    @GetMapping("/order")
    public ResultRespone<List<ReportOrderInfoVo>> getOrder(@RequestParam Long id, @RequestParam Long type) {
        return ResultRespone.success(certificationOrderService.getOrder(id, type));
    }


    /**
     * 检验记录列表
     *
     * @param orderDto
     * @param page
     * @return
     */
    @ApiOperation(value = "检验记录，质检认证的分页和模糊查询", notes = "", httpMethod = "POST")
    @PostMapping("/getCertificationList")
    public ResultRespone<IPage<BusinessMonitorVO_L>> getCertificationList(ReportOrderDto orderDto, Page page) {
        return ResultRespone.success(certificationOrderService.getCertificationList(orderDto, page), SUCCESS);
    }


    @ApiOperation(value = "修改认证工单", notes = "", httpMethod = "POST")
    @PostMapping("/update")
    public ResultRespone updateCertificationOrder(@RequestBody @Valid CertificationOrder certificationOrder) {
        Boolean flag = certificationOrderService.updateById(certificationOrder);
        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 = "删除认证工单", httpMethod = "GET")
    @GetMapping("/delete")
    public ResultRespone deleteCertificationOrder(@RequestParam Long id) {
        Boolean flag = certificationOrderService.deleteOrder(id);
        return flag ? ResultRespone.success(flag, SUCCESS) : ResultRespone.failed(flag, FAILED);
    }

    @ApiImplicitParams({
            @ApiImplicitParam(value = "文件id的list", name = "fileIdList", required = true, paramType = "query", dataType = "long", dataTypeClass = Long.class)
    })
    @ApiOperation(value = "获取文件下载路径和文件名", httpMethod = "GET")
    @GetMapping("/getFilePath")
    public ResultRespone<List<Map<String, String>>> getFilePathList(@RequestParam List<Long> fileIdList) {
        return ResultRespone.success(certificationOrderService.getFilePath(fileIdList), SUCCESS);
    }

    @ApiOperation(value = "获取当前用户每个环节的计数", httpMethod = "GET")
    @GetMapping("/getProcessCount")
    public ResultRespone<Map<String, Object>> getProcessCount() {
        return ResultRespone.success(certificationOrderService.getProcessCount(), SUCCESS);
    }

    /**
     * 质量工单列表
     *
     * @param dto
     * @param page
     * @return
     */
    @ApiOperation(value = "质量工单列表", httpMethod = "POST")
    @PostMapping("/workOrderList")
    public ResultRespone<Page<OrderListInfoVo>> getWorkOrderList(HttpServletResponse response, OrderListDto dto, Page page) {
        if (StringUtils.isNotEmpty(dto.getYearMonth())) {
            Date dt = DateUtil.parse(dto.getYearMonth(), "yyyy-MM");
            dto.setStartDate(DateUtil.beginOfMonth(dt));
            dto.setEndDate(DateUtil.endOfMonth(dt));
        }
        if (dto.getEndDate() != null) {
            dto.setEndDate(DateUtil.endOfDay(dto.getEndDate()));
        }
        if (dto.getExport() != null && dto.getExport()) {
            List<OrderListInfoVo> list = certificationOrderService.getWorkOrderList(dto);
            collectionNumberSummaryService.exportData(response, "质量监督检查（整改）业务工单明细", "质量业务工单", list, OrderListInfoVo.class);
        } else {
            return ResultRespone.success(certificationOrderService.getWorkOrderList(dto, page));
        }

        return ResultRespone.success();
    }

    /**
     * 工单完成率
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "工单完成率", notes = "", httpMethod = "POST")
    @PostMapping("/orderFinish")
    public ResultRespone<List<OrderFinishVo>> orderFinish(OrderReportDto dto) {
        if (dto.getEndDate() != null) {
            dto.setEndDate(DateUtil.endOfDay(dto.getEndDate()));
        }
        return ResultRespone.success(certificationOrderService.getOrderFinish(dto));
    }

    /**
     * 缺陷类型统计
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "缺陷类型统计", notes = "", httpMethod = "POST")
    @PostMapping("/defectType")
    public ResultRespone<List<OrderFinishInfoVo>> defectType(OrderReportDto dto) {
        if (dto.getEndDate() != null) {
            dto.setEndDate(DateUtil.endOfDay(dto.getEndDate()));
        }
        return ResultRespone.success(certificationOrderService.getDefectType(dto));
    }

    /**
     * 缺陷趋势
     *
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "缺陷趋势", notes = "", httpMethod = "POST")
    @PostMapping("/defectTrend")
    public ResultRespone<List<Map<String, Object>>> defectTrend(OrderReportDto dto) {
        if (dto.getEndDate() != null) {
            dto.setEndDate(DateUtil.endOfMonth(dto.getEndDate()));
        }
        if (dto.getStartDate() == null || dto.getEndDate() == null || dto.getEndDate().getTime() < dto.getStartDate().getTime()) {
            return ResultRespone.failed("时间错误");
        }
        return ResultRespone.success(certificationOrderService.getDefectTrend(dto));
    }

    /**
     * 认证频次明细表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "认证频次明细表", notes = "", httpMethod = "POST")
    @PostMapping("/clientAttestation")
    public ResultRespone<List<ClientAttestationVo>> clientAttestation(HttpServletResponse response, ClientAttestationDto dto) {
        if (dto.getEndDate() != null) {
            dto.setEndDate(DateUtil.endOfDay(dto.getEndDate()));
        }

        if (dto.getKeyword() != null) {
            dto.setContent(dto.getKeyword());
        }

        List<ClientAttestationVo> datas = certificationOrderService.getClientAttestation(dto);
        if (dto.getExport() != null && dto.getExport()) {
            collectionNumberSummaryService.exportData(response, "认证频次明细表", "认证频次明细", datas, ClientAttestationVo.class);
            return ResultRespone.success();
        }
        return ResultRespone.success(datas);
    }

    /**
     * 管理效益
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "管理效益", notes = "", httpMethod = "POST")
    @PostMapping("/manageBenefit")
    public ResultRespone manageBenefit(OrderReportDto dto) {
        if (dto.getEndDate() != null) {
            dto.setEndDate(DateUtil.endOfMonth(dto.getEndDate()));
        }
        if (dto.getStartDate() == null || dto.getEndDate() == null || dto.getEndDate().getTime() < dto.getStartDate().getTime()) {
            return ResultRespone.failed("时间错误");
        }
        return ResultRespone.success(certificationOrderService.getManageBenefit(dto));
    }


}
