package com.sckw.transport.controller;

import com.alibaba.fastjson.JSONObject;
import com.sckw.core.annotation.Log;
import com.sckw.core.annotation.RepeatSubmit;
import com.sckw.core.exception.CustomPromptException;
import com.sckw.core.model.enums.OrderRuleEnum;
import com.sckw.core.model.enums.RedisOrderGenerateEnum;
import com.sckw.core.model.page.PageRes;
import com.sckw.core.model.vo.BaseList;
import com.sckw.core.utils.OrderGenerateSeqNoUtils;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.constant.HttpStatus;
import com.sckw.core.web.response.HttpResult;
import com.sckw.excel.config.easyexcel.RequestHolder;
import com.sckw.excel.utils.ExcelUtil;
import com.sckw.transport.model.dto.*;
import com.sckw.transport.model.param.*;
import com.sckw.transport.model.vo.execlVo.AcceptCarriageOrderExcelVo;
import com.sckw.transport.service.Import.KwtAcceptCarriageOrderImportService;
import com.sckw.transport.service.KwtAcceptCarriageOrderService;
import com.sckw.transport.service.KwtLogisticsOrderImportService;
import com.sckw.transport.service.KwtTransportCommonService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;

/**
 * @author lfdc
 * @desc 承运订单controller
 * @date 2023-06-26 16:06:07
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/kwtAcceptCarriageOrder")
public class KwtAcceptCarriageOrderController {

    @Autowired
    KwtAcceptCarriageOrderService acceptCarriageOrderService;

    @Autowired
    KwtAcceptCarriageOrderImportService acceptCarriageOrderImportService;

    @Autowired
    KwtTransportCommonService transportCommonService;

    @Autowired
    KwtLogisticsOrderImportService logisticsOrderImportService;

    /**
     * 承运订单首页条件查询
     *
     * @param query 查询参数
     * @return  响应结果
     */
    @RequestMapping(value = "/selectAcceptCarriageOrderList", method = RequestMethod.POST)
    public HttpResult acceptCarriageOrderList(@Valid @RequestBody AcceptCarriageOrderQuery query) {
        try {
            PageRes result = acceptCarriageOrderService.selectLogisticsOrderList(query, "2");
            return HttpResult.ok(result);
        } catch (Exception e) {
            log.error("承运订单首页条件查询 查询失败:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单top统计
     *
     * @param query 查询参数
     * @return  响应结果
     */
    @RequestMapping(value = "/statisticsAcceptCarriage", method = RequestMethod.POST)
    public HttpResult statisticsAcceptCarriage(@Valid @RequestBody AcceptCarriageOrderQuery query) {
        try {
            return acceptCarriageOrderService.statisticsAcceptCarriage(query, "2");
        } catch (Exception e) {
            log.error("承运订单top统计 查询失败:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单导出
     * @param query 查询参数
     */
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    @RequestMapping(value = "/acceptCarriageOrderExport", method = RequestMethod.POST)
    public void exportAcceptCarriage(@Validated @RequestBody AcceptCarriageOrderQuery query) {
        HttpServletResponse response = RequestHolder.getResponse();
        List<AcceptCarriageOrderExcelVo> list = acceptCarriageOrderService.exportAcceptCarriage(query, "2");
        if (org.springframework.util.CollectionUtils.isEmpty(list)){
            throw new CustomPromptException(HttpStatus.SUCCESS_CODE,"暂无数据，请确认");
        }
        ExcelUtil.downData(response, AcceptCarriageOrderExcelVo.class, list);
    }

    /**
     * @param file 导入文件
     * @desc 导入
     * @author zk
     * @date 2023/12/10
     **/
    @PostMapping("/import")
    public HttpResult importExcel(@RequestParam("file") MultipartFile file) {
        return logisticsOrderImportService.importExcel(file);
    }

    /**
     * 获取订单详情-托运订单-承运订单-销售订单-采购订单
     *
     * @param dto   获取订单数据请求参数
     * @return  响应结果
     */
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    @RequestMapping(value = "/getOrderDetail", method = RequestMethod.POST)
    public HttpResult getOrderDetail(@Validated @RequestBody DocumentParamDTO dto) {
        log.info("获取订单详情参数:{}", JSONObject.toJSONString(dto));
        try {
            return transportCommonService.getOrderDetail(dto);
        } catch (Exception e) {
            log.error("获取订单详情失败:error {} ", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运合同/托运合同-根据合同id获取托运订单列表
     *
     * @param contractParam 请求参数
     * @return  响应结果
     */
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    @RequestMapping(value = "/getLogisticsOrderContract", method = RequestMethod.POST)
    public HttpResult getLogisticsOrderContract(@Valid @RequestBody ContractParam contractParam) {
        try {
            return transportCommonService.getLogisticsOrderByContractId(contractParam);
        } catch (Exception e) {
            log.error("承运合同/托运合同-根据合同id获取托运订单列表 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 托运订单/承运订单-撤销托运
     *
     * @param orderDto  订单请求数据
     * @return  响应结果
     */
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    @RequestMapping(value = "/cancelConsign", method = RequestMethod.POST)
    public HttpResult cancelConsign(@Validated @RequestBody CancelOrderDTO orderDto) {
        try {
            return transportCommonService.cancelConsign(orderDto);
        } catch (Exception e) {
            log.error("托运订单-撤销托运运单失败:订单id {},error {} ", orderDto.getId(), e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 对账管理-运费收款对账界面查询接口
     *
     * @param logisticsOrderParam   物流请求数据
     * @return  物流订单响应结果
     */
    @RequestMapping(value = "/getAcceptCarriageOrder", method = RequestMethod.POST)
    public HttpResult getAcceptCarriageOrder(@RequestBody @Valid LogisticsOrderParam logisticsOrderParam) {
        log.info("对账管理查询物流订单信息:{}", JSONObject.toJSONString(logisticsOrderParam));
        try {
            return transportCommonService.getAcceptCarriageOrder(logisticsOrderParam);
        } catch (Exception e) {
            log.error("对账管理-运费收款对账界面查询接口 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }

    }

    /**
     * 承运订单-接单
     *
     * @param orderDTO  物流订单接单请求数据
     * @return  接单响应结果
     */
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    @RequestMapping(value = "/orderTaking", method = RequestMethod.POST)
    public HttpResult orderTaking(@Validated @RequestBody OrderTakingDTO orderDTO) {
        return acceptCarriageOrderService.orderTaking(orderDTO);
    }

    /**
     * 承运订单-分包托运
     *
     * @param query 请求参数
     * @return 操作响应数据
     */
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    @RequestMapping(value = "/subcontractConsignment", method = RequestMethod.POST)
    public HttpResult subcontractConsignment(@RequestBody SubcontractConsignmentDTO query) {
        try {
            return acceptCarriageOrderService.subcontractConsignment(query);
        } catch (Exception e) {
//            OrderGenerateSeqNoUtils.getSeqNoMinusOne(RedisOrderGenerateEnum.LOGISTICS_ORDER, OrderRuleEnum.LOGISTICS_ORDER);
            log.error("分包托运 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-分包托运-订单详情
     *
     * @param id 物流订单id
     * @return  物流订单数据
     */
    @RequestMapping(value = "/subcontractConsignmentOrderDetail", method = RequestMethod.GET)
    public HttpResult subcontractConsignmentOrderDetail(@NotNull(message = "物流订单不能为空") @RequestParam("id") String id) {
        try {
            return acceptCarriageOrderService.subcontractConsignmentOrderDetail(id);
        } catch (Exception e) {
            log.error("分包托运 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-获取运单详情
     *
     * @param wOrderId 运单id
     * @return  运单数据
     */
    @RequestMapping(value = "/getWaybillData", method = RequestMethod.GET)
    public HttpResult getWaybillData(@NotNull(message = "物流订单id不能为空") @RequestParam("wOrderId") String wOrderId) {
        try {
            return acceptCarriageOrderService.getWaybillData(wOrderId);
        } catch (Exception e) {
            log.error("承运订单-获取运单详情 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-获取分包托运列表
     *
     * @param lOrderIds 单据id
     * @param page  请求当前页数
     * @param pageSize  请求每页条数
     * @return  响应结果
     */
    @RequestMapping(value = "/getSubcontractConsignment", method = RequestMethod.GET)
    public HttpResult getSubcontractConsignment(@RequestParam("lOrderIds") @NotBlank(message = "单据id不能为空") String lOrderIds,
                                                                       @RequestParam("page") @NotNull(message = "分页不能为空") int page,
                                                                       @RequestParam("pageSize") @NotNull(message = "分页条数不能为空") int pageSize) {
        try {
            return HttpResult.ok(acceptCarriageOrderService.getSubcontractConsignment(lOrderIds, page, pageSize));
        } catch (Exception e) {
            log.error("承运订单-获取分包托运列表 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-获取分包托运列表-数据统计
     *
     * @param lOrderId 单据id
     * @return  统计响应结果
     */
    @RequestMapping(value = "/getSubcontractConsignmentCount", method = RequestMethod.GET)
    public HttpResult getSubcontractConsignmentCount(@RequestParam("lOrderId") @NotBlank(message = "单据id不能为空") String lOrderId) {
        try {
            return acceptCarriageOrderService.getSubcontractConsignmentCount(lOrderId);
        } catch (Exception e) {
            log.error("承运订单-获取分包托运列表 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-停止接单-查询
     * @param driverParam   查询订单数据
     * @return  查询结果数据
     */
    @RequestMapping(value = "/acceptStopDocumentDetail", method = RequestMethod.POST)
    public HttpResult stopDocumentDetail(@Validated @RequestBody DriverParam driverParam) {
        log.info("承运订单-设置停止接单-查询 请求参数:{}", JSONObject.toJSONString(driverParam));
        try {
            return acceptCarriageOrderService.stopDocumentDetail(driverParam);
        } catch (Exception e) {
            log.error("承运订单-设置停止接单-查询 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-设置停止接单-循环单提交
     *
     * @param stopOrderTakingDTO    停止接单请求数据
     * @return  响应结果
     */
    @RequestMapping(value = "/acceptStopDocumentCommit", method = RequestMethod.POST)
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    public HttpResult stopDocumentCommit(@Validated @RequestBody StopOrderTakingDTO stopOrderTakingDTO) {
        log.info("承运订单/托运订单-设置停止接单-提交 请求参数:{}", JSONObject.toJSONString(stopOrderTakingDTO));
        try {
            return acceptCarriageOrderService.stopDocumentCommit(stopOrderTakingDTO);
        } catch (Exception e) {
            log.error("承运订单/托运订单-设置停止接单-提交 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-取消派车(撤回派车)/单趟撤回
     *
     * @param baseList 车辆运单id
     * @return  响应结果
     */
    @RequestMapping(value = "/cancelDelivery", method = RequestMethod.POST)
    public HttpResult cancelDelivery(@Valid @RequestBody BaseList baseList) {
        log.info("承运订单-取消派车(撤回派车)/单趟撤回请求参数:{}", JSONObject.toJSONString(baseList));
        List<String> lists = StringUtils.splitStrToList(baseList.getIds(), ",", String.class);
        try {
            return acceptCarriageOrderService.cancelDelivery(lists, baseList.getIds());
        } catch (Exception e) {
            log.error("承运订单-单趟撤回 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-完结订单-页面数据查询
     *
     * @param orderId 物流订单id
     * @return  查询响应结果
     */
    @RequestMapping(value = "/acceptCarriageOrderFinishDetail", method = RequestMethod.GET)
    public HttpResult acceptCarriageOrderFinishDetail(@RequestParam("orderId") @NotBlank(message = "数据id不能为空") String orderId) {
        log.info("承运订单-完结订单-页面数据查询 传递参数信息:{}", orderId);
        try {
            //return acceptCarriageOrderService.acceptCarriageOrderFinishDetail(orderId);
            return transportCommonService.orderFinishDetail(orderId);
        } catch (Exception e) {
            log.error("承运订单-完结订单-页面数据查询 error :{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-完结订单
     *
     * @param orderFinishDTO    物流订单请求参数
     * @return  响应结果
     */
    @RequestMapping(value = "/commitAcceptCarriageOrderFinish", method = RequestMethod.POST)
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    public HttpResult commitAcceptCarriageOrderFinish(@Valid @RequestBody OrderManualCompletionDto orderFinishDTO) {
        try {
            //return acceptCarriageOrderService.commitAcceptCarriageOrderFinish(orderFinishDTO);
            return transportCommonService.orderFinish(orderFinishDTO);
        } catch (Exception e) {
            log.error("托运订单-完结订单失败:订单id {},error {} ", orderFinishDTO.getId(), e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-查看撤销原因+驳回原因
     *
     * @param id 物流订单
     * @return 响应结果
     */
    @RequestMapping(value = "/getCancelReason", method = RequestMethod.GET)
    public HttpResult getCancelReason(@NotBlank(message = "物流订单id不能为空") @RequestParam("id") String id,
                                      @NotNull(message = "单据状态不能为空") @RequestParam("status") Integer status) {
        try {
            return acceptCarriageOrderService.getCancelReason(id, status);
        } catch (Exception e) {
            log.error("承运订单-查看撤销原因 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单-新建订单
     *
     * @param addOrderDTO 页面传递参数
     * @return  响应结果
     */
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    public HttpResult addOrder(@Valid @RequestBody AddOrderDTO addOrderDTO) {
        log.info("承运订单-页面新建订单 add {}", JSONObject.toJSONString(addOrderDTO));
        try {
            return acceptCarriageOrderService.addOrder(addOrderDTO);
        } catch (Exception e) {
            OrderGenerateSeqNoUtils.getSeqNoMinusOne(RedisOrderGenerateEnum.LOGISTICS_ORDER, OrderRuleEnum.LOGISTICS_ORDER);
            log.error("承运订单-新建订单 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 承运订单数据导入(外部数据)-批量导入
     *
     * @param file 文件
     * @return  响应结果
     */
    @Log(description = "承运订单数据导入(外部数据)")
    @RepeatSubmit(interval = 1000,message ="前方拥堵，请稍后尝试")
    @RequestMapping(value = "/externalImportExcel", method = RequestMethod.POST)
    public HttpResult externalImportExcel(@RequestParam("file") MultipartFile file) {
        try {
            return acceptCarriageOrderImportService.externalImportExcel(file);
        } catch (Exception e) {
            log.error("异常错误信息:{}",e.getMessage(),e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }


    /**
     * 工作台-承运业务统计
     * @param dateType 1代表周 2代表月
     * @return 统计结果
     */
    @RequestMapping(value = "/workbenchStatisticsByAcceptCarriage", method = RequestMethod.GET)
    public HttpResult workbenchStatistics(@RequestParam("dateType") @NotBlank(message = "类型不能为空") String dateType) {
        log.info("工作台-承运业务统计 {}", dateType);
        try {
            return acceptCarriageOrderService.workbenchStatistics(dateType);
        } catch (Exception e) {
            log.error("工作台-承运业务统计 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }

    /**
     * 工作台-物流运输数据统计-承运
     * @param logisticsOrderStatistics  物流统计请求参数
     * @return  响应结果
     */
    @RequestMapping(value = "/workbenchLogisticsOrderStatistics", method = RequestMethod.POST)
    public HttpResult workbenchLogisticsOrderStatistics(@RequestBody LogisticsOrderStatisticsParam logisticsOrderStatistics) {
        log.info("工作台-物流运输数据统计-承运 {}", JSONObject.toJSONString(logisticsOrderStatistics));
        try {
            return acceptCarriageOrderService.workbenchLogisticsOrderStatistics(logisticsOrderStatistics);
        } catch (Exception e) {
            log.error("工工作台-承运业务统计-承运 error:{}", e.getMessage(), e);
            return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, e.getMessage());
        }
    }
}
