package com.bs.tm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.bs.common.utils.DateUtils;
import com.bs.tm.domain.TmOrder;
import com.bs.tm.domain.TmOrderTransCargo;
import com.bs.tm.service.ITmOrderService;
import com.bs.tm.service.ITmOrderTransCargoService;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.bs.common.annotation.Log;
import com.bs.common.core.controller.BaseController;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.core.page.TableDataInfo;
import com.bs.common.enums.BusinessType;
import com.bs.common.utils.poi.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import cn.hutool.core.lang.Validator;
import com.bs.tm.domain.TmOrderTrans;
import com.bs.tm.service.ITmOrderTransService;
import javax.annotation.Resource;

/**
 * 车辆货物运输Controller
 *
 * @author bs
 * @date 2024-02-07
 */
@Api(tags = "车辆货物运输")
@RestController
@RequestMapping("/order/trans")
public class TmOrderTransController extends BaseController {
    @Resource
    private ITmOrderTransService tmOrderTransService;
    @Resource
    private ITmOrderService tmOrderService;
    @Resource
    private ITmOrderTransCargoService tmOrderTransCargoService;
    /**
     * 分页查询车辆货物运输列表
     */
    @ApiOperation("分页查询车辆货物运输列表")
    @GetMapping("/pageList")
    public TableDataInfo pageList(TmOrderTrans tmOrderTrans) {
        startPage();
        MPJLambdaWrapper<TmOrderTrans> queryWrapper = new MPJLambdaWrapper();
        queryWrapper.selectAll(TmOrderTrans.class)
                .selectAs(TmOrder::getStatus, TmOrderTrans::getStatusByOrder)
                .disableSubLogicDel()
                .leftJoin(TmOrder.class, TmOrder::getId, TmOrderTrans::getOrderId);
        conditionByMPJ(queryWrapper,tmOrderTrans);
        List<TmOrderTrans> list = tmOrderTransService.list(queryWrapper);
        if (null != list && list.size() > 0) {
            List<Long> ids = new ArrayList<>();
            for (TmOrderTrans trans : list) {
                ids.add(trans.getOrderId());
            }
            List<TmOrder> lsOrder = tmOrderService.listByIds(ids);
            Map<Long, TmOrder> orderMap = new HashMap<>();
            lsOrder.forEach(ele -> {
                orderMap.put(ele.getId(), ele);
            });
            list.forEach(ele -> {
                ele.setOrder(orderMap.get(ele.getOrderId()));
            });
        }
        return getDataTable(list);
    }

    /**
     * 查询车辆货物运输列表
     */
    @ApiOperation("查询车辆货物运输列表")
    @GetMapping("/list")
    public AjaxResult list(TmOrderTrans tmOrderTrans) {
        LambdaQueryWrapper<TmOrderTrans> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,tmOrderTrans);
        List<TmOrderTrans> list = tmOrderTransService.list(queryWrapper);
        return success(list);
    }

    /**
     * 导出车辆货物运输列表
     */
    @ApiOperation("导出车辆货物运输列表")
    @Log(title = "车辆货物运输导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TmOrderTrans tmOrderTrans) {
        LambdaQueryWrapper<TmOrderTrans> queryWrapper = new LambdaQueryWrapper();
        condition(queryWrapper,tmOrderTrans);
        List<TmOrderTrans> list = tmOrderTransService.list(queryWrapper);
        ExcelUtil<TmOrderTrans> util = new ExcelUtil<TmOrderTrans>(TmOrderTrans. class);
        util.exportExcel(response, list, "车辆货物运输数据");
    }

    /**
     * 获取车辆货物运输详细信息
     */
    @ApiOperation("获取车辆货物运输详细信息")
    @GetMapping(value = "/{ID}")
    public AjaxResult getInfo(@PathVariable("ID") Long ID) {
        return success(tmOrderTransService.getById(ID));
    }

    /**
     * 新增车辆货物运输
     */
    @ApiOperation("新增车辆货物运输")
    @Log(title = "车辆货物运输新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TmOrderTrans tmOrderTrans) {
        return toAjax(tmOrderTransService.save(tmOrderTrans));
    }

    /**
     * 修改车辆货物运输
     */
    @ApiOperation("修改车辆货物运输")
    @Log(title = "车辆货物运输修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TmOrderTrans tmOrderTrans) {
        return toAjax(tmOrderTransService.updateById(tmOrderTrans));
    }

    @ApiOperation("保存车辆货物运输")
    @Log(title = "保存车辆货物运输", businessType = BusinessType.INSERT)
    @PostMapping("/saveTrans")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveTrans(@RequestBody TmOrder tmOrder) {
        if (null != tmOrder && null != tmOrder.getOrderId()) {
            TmOrder order = tmOrderService.getById(tmOrder.getOrderId());
            //List<TmOrderTrans> lsInsert = new ArrayList<>();
            List<TmOrderTrans> lsUpdate = new ArrayList<>();
            if (null != order) {
                if (null != tmOrder.getLsTrans() && tmOrder.getLsTrans().size() > 0) {
                    for (TmOrderTrans trans : tmOrder.getLsTrans()) {
                        trans.setOrderId(tmOrder.getOrderId());
                        List<TmOrderTransCargo> lsCargo = trans.getLsCargos();
                        if (null == trans.getId()) {
                            tmOrderTransService.save(trans);
                        } else {
                            lsUpdate.add(trans);
                        }
                        if (null != lsCargo && lsCargo.size() > 0) {
                            for (TmOrderTransCargo cargo : lsCargo) {
                                cargo.setTransId(trans.getId());
                                cargo.setOrderId(trans.getOrderId());
                            }
                            tmOrderTransCargoService.saveBatch(lsCargo);
                            //trans.setLsCargos(lsCargo);
                        }
                    }
                }
                if (lsUpdate.size() > 0) {
                    tmOrderTransService.updateBatchById(lsUpdate);
                }
                return success(order);
            } else {
                return warn("未找到对应的订单!");
            }
        } else {
            return warn("请选择正确的订单!");
        }
    }

    /**
     * 删除车辆货物运输
     */
    @ApiOperation("删除车辆货物运输")
    @Log(title = "车辆货物运输删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public AjaxResult remove(@PathVariable List<Long> IDs) {
        List<TmOrderTransCargo> lsCargo = tmOrderTransCargoService.list(new LambdaQueryWrapper<TmOrderTransCargo>().in(TmOrderTransCargo::getTransId, IDs));
        if (null != lsCargo && lsCargo.size() > 0) {
            return warn("该运输计划有运输明细，不能直接删除！");
        }
        return toAjax(tmOrderTransService.removeBatchByIds(IDs));
    }

    /**
     * 条件设置
     */
    private void conditionByMPJ (MPJLambdaWrapper<TmOrderTrans> queryWrapper,TmOrderTrans tmOrderTrans){


        //id
        if(Validator.isNotEmpty(tmOrderTrans.getId())){
            queryWrapper.eq(TmOrderTrans::getId,tmOrderTrans.getId());
        }

        //订单ID
        if(Validator.isNotEmpty(tmOrderTrans.getOrderId())){
            queryWrapper.eq(TmOrderTrans::getOrderId,tmOrderTrans.getOrderId());
        }

        if(Validator.isNotEmpty(tmOrderTrans.getCargoName())){
            queryWrapper.inSql(TmOrderTrans::getId, "select trans_id from tm_order_trans_cargo where cargo_name like '%" + tmOrderTrans.getCargoName() + "%'");
        }

        if(Validator.isNotEmpty(tmOrderTrans.getBeginDate())){
            queryWrapper.inSql(TmOrderTrans::getId, "select trans_id from tm_order_trans_cargo where input_date >= '" + DateUtils.dateTime(tmOrderTrans.getBeginDate()) + "'");
        }

        if(Validator.isNotEmpty(tmOrderTrans.getEndDate())){
            queryWrapper.inSql(TmOrderTrans::getId, "select trans_id from tm_order_trans_cargo where input_date <= '" + DateUtils.dateTime(tmOrderTrans.getEndDate()) + "'");
        }

        //车辆ID
        if(Validator.isNotEmpty(tmOrderTrans.getVehicleId())){
            queryWrapper.eq(TmOrderTrans::getVehicleId,tmOrderTrans.getVehicleId());
        }

        //车牌号码
        if(Validator.isNotEmpty(tmOrderTrans.getVehicleNumber())){
            queryWrapper.eq(TmOrderTrans::getVehicleNumber,tmOrderTrans.getVehicleNumber());
        }

        //挂车ID
        if(Validator.isNotEmpty(tmOrderTrans.getTrailerId())){
            queryWrapper.eq(TmOrderTrans::getTrailerId,tmOrderTrans.getTrailerId());
        }

        //挂车号码
        if(Validator.isNotEmpty(tmOrderTrans.getTrailerNumber())){
            queryWrapper.eq(TmOrderTrans::getTrailerNumber,tmOrderTrans.getTrailerNumber());
        }

        //GPS代码
        if(Validator.isNotEmpty(tmOrderTrans.getGpsCode())){
            queryWrapper.eq(TmOrderTrans::getGpsCode,tmOrderTrans.getGpsCode());
        }

        //司机ID
        if(Validator.isNotEmpty(tmOrderTrans.getDriverId())){
            queryWrapper.eq(TmOrderTrans::getDriverId,tmOrderTrans.getDriverId());
        }

        //司机姓名
        if(Validator.isNotEmpty(tmOrderTrans.getDriverName())){
            queryWrapper.eq(TmOrderTrans::getDriverName,tmOrderTrans.getDriverName());
        }

        //司机电话
        if(Validator.isNotEmpty(tmOrderTrans.getDriverMobile())){
            queryWrapper.eq(TmOrderTrans::getDriverMobile,tmOrderTrans.getDriverMobile());
        }

        //发车时间
        if(Validator.isNotEmpty(tmOrderTrans.getDepartTime())){
            queryWrapper.eq(TmOrderTrans::getDepartTime,tmOrderTrans.getDepartTime());
        }

        //实际发车时间
        if(Validator.isNotEmpty(tmOrderTrans.getRealDepartTime())){
            queryWrapper.eq(TmOrderTrans::getRealDepartTime,tmOrderTrans.getRealDepartTime());
        }

        //到达时间
        if(Validator.isNotEmpty(tmOrderTrans.getArrivalTime())){
            queryWrapper.eq(TmOrderTrans::getArrivalTime,tmOrderTrans.getArrivalTime());
        }

        //实际到达时间
        if(Validator.isNotEmpty(tmOrderTrans.getRealArrivalTime())){
            queryWrapper.eq(TmOrderTrans::getRealArrivalTime,tmOrderTrans.getRealArrivalTime());
        }

        //收货时间
        if(Validator.isNotEmpty(tmOrderTrans.getReceiveTime())){
            queryWrapper.eq(TmOrderTrans::getReceiveTime,tmOrderTrans.getReceiveTime());
        }

        //实际收货时间
        if(Validator.isNotEmpty(tmOrderTrans.getRealReceiveTime())){
            queryWrapper.eq(TmOrderTrans::getRealReceiveTime,tmOrderTrans.getRealReceiveTime());
        }

        //签收人
        if(Validator.isNotEmpty(tmOrderTrans.getReceiver())){
            queryWrapper.eq(TmOrderTrans::getReceiver,tmOrderTrans.getReceiver());
        }

        //状态
        if(Validator.isNotEmpty(tmOrderTrans.getStatus())){
            queryWrapper.eq(TmOrderTrans::getStatus,tmOrderTrans.getStatus());
        }

        //订单状态
        if(Validator.isNotEmpty(tmOrderTrans.getStatusByOrder())){
            queryWrapper.eq(TmOrder::getStatus,tmOrderTrans.getStatusByOrder());
        }

        //备注
        if(Validator.isNotEmpty(tmOrderTrans.getRemark())){
            queryWrapper.eq(TmOrderTrans::getRemark,tmOrderTrans.getRemark());
        }

        //创建人
        if(Validator.isNotEmpty(tmOrderTrans.getCreateBy())){
            queryWrapper.eq(TmOrderTrans::getCreateBy,tmOrderTrans.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(tmOrderTrans.getCreateTime())){
            queryWrapper.eq(TmOrderTrans::getCreateTime,tmOrderTrans.getCreateTime());
        }

        //修改人
        if(Validator.isNotEmpty(tmOrderTrans.getUpdateBy())){
            queryWrapper.eq(TmOrderTrans::getUpdateBy,tmOrderTrans.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(tmOrderTrans.getUpdateTime())){
            queryWrapper.eq(TmOrderTrans::getUpdateTime,tmOrderTrans.getUpdateTime());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(tmOrderTrans.getDelFlag())){
            queryWrapper.eq(TmOrderTrans::getDelFlag,tmOrderTrans.getDelFlag());
        }

    }


    /**
      * 条件设置
      */
    private void condition (LambdaQueryWrapper<TmOrderTrans> queryWrapper,TmOrderTrans tmOrderTrans){


        //id
        if(Validator.isNotEmpty(tmOrderTrans.getId())){
            queryWrapper.eq(TmOrderTrans::getId,tmOrderTrans.getId());
        }

        //订单ID
        if(Validator.isNotEmpty(tmOrderTrans.getOrderId())){
            queryWrapper.eq(TmOrderTrans::getOrderId,tmOrderTrans.getOrderId());
        }

        if(Validator.isNotEmpty(tmOrderTrans.getCargoName())){
            queryWrapper.inSql(TmOrderTrans::getId, "select trans_id from tm_order_trans_cargo where cargo_name like '%" + tmOrderTrans.getCargoName() + "%'");
        }

        if(Validator.isNotEmpty(tmOrderTrans.getBeginDate())){
            queryWrapper.inSql(TmOrderTrans::getId, "select trans_id from tm_order_trans_cargo where input_date >= '" + DateUtils.dateTime(tmOrderTrans.getBeginDate()) + "'");
        }

        if(Validator.isNotEmpty(tmOrderTrans.getEndDate())){
            queryWrapper.inSql(TmOrderTrans::getId, "select trans_id from tm_order_trans_cargo where input_date <= '" + DateUtils.dateTime(tmOrderTrans.getEndDate()) + "'");
        }

        //车辆ID
        if(Validator.isNotEmpty(tmOrderTrans.getVehicleId())){
            queryWrapper.eq(TmOrderTrans::getVehicleId,tmOrderTrans.getVehicleId());
        }

        //车牌号码
        if(Validator.isNotEmpty(tmOrderTrans.getVehicleNumber())){
            queryWrapper.eq(TmOrderTrans::getVehicleNumber,tmOrderTrans.getVehicleNumber());
        }

        //挂车ID
        if(Validator.isNotEmpty(tmOrderTrans.getTrailerId())){
            queryWrapper.eq(TmOrderTrans::getTrailerId,tmOrderTrans.getTrailerId());
        }

        //挂车号码
        if(Validator.isNotEmpty(tmOrderTrans.getTrailerNumber())){
            queryWrapper.eq(TmOrderTrans::getTrailerNumber,tmOrderTrans.getTrailerNumber());
        }

        //GPS代码
        if(Validator.isNotEmpty(tmOrderTrans.getGpsCode())){
            queryWrapper.eq(TmOrderTrans::getGpsCode,tmOrderTrans.getGpsCode());
        }

        //司机ID
        if(Validator.isNotEmpty(tmOrderTrans.getDriverId())){
            queryWrapper.eq(TmOrderTrans::getDriverId,tmOrderTrans.getDriverId());
        }

        //司机姓名
        if(Validator.isNotEmpty(tmOrderTrans.getDriverName())){
            queryWrapper.eq(TmOrderTrans::getDriverName,tmOrderTrans.getDriverName());
        }

        //司机电话
        if(Validator.isNotEmpty(tmOrderTrans.getDriverMobile())){
            queryWrapper.eq(TmOrderTrans::getDriverMobile,tmOrderTrans.getDriverMobile());
        }

        //发车时间
        if(Validator.isNotEmpty(tmOrderTrans.getDepartTime())){
            queryWrapper.eq(TmOrderTrans::getDepartTime,tmOrderTrans.getDepartTime());
        }

        //实际发车时间
        if(Validator.isNotEmpty(tmOrderTrans.getRealDepartTime())){
            queryWrapper.eq(TmOrderTrans::getRealDepartTime,tmOrderTrans.getRealDepartTime());
        }

        //到达时间
        if(Validator.isNotEmpty(tmOrderTrans.getArrivalTime())){
            queryWrapper.eq(TmOrderTrans::getArrivalTime,tmOrderTrans.getArrivalTime());
        }

        //实际到达时间
        if(Validator.isNotEmpty(tmOrderTrans.getRealArrivalTime())){
            queryWrapper.eq(TmOrderTrans::getRealArrivalTime,tmOrderTrans.getRealArrivalTime());
        }

        //收货时间
        if(Validator.isNotEmpty(tmOrderTrans.getReceiveTime())){
            queryWrapper.eq(TmOrderTrans::getReceiveTime,tmOrderTrans.getReceiveTime());
        }

        //实际收货时间
        if(Validator.isNotEmpty(tmOrderTrans.getRealReceiveTime())){
            queryWrapper.eq(TmOrderTrans::getRealReceiveTime,tmOrderTrans.getRealReceiveTime());
        }

        //签收人
        if(Validator.isNotEmpty(tmOrderTrans.getReceiver())){
            queryWrapper.eq(TmOrderTrans::getReceiver,tmOrderTrans.getReceiver());
        }

        //状态
        if(Validator.isNotEmpty(tmOrderTrans.getStatus())){
            queryWrapper.eq(TmOrderTrans::getStatus,tmOrderTrans.getStatus());
        }

        //备注
        if(Validator.isNotEmpty(tmOrderTrans.getRemark())){
            queryWrapper.eq(TmOrderTrans::getRemark,tmOrderTrans.getRemark());
        }

        //创建人
        if(Validator.isNotEmpty(tmOrderTrans.getCreateBy())){
            queryWrapper.eq(TmOrderTrans::getCreateBy,tmOrderTrans.getCreateBy());
        }

        //创建时间
        if(Validator.isNotEmpty(tmOrderTrans.getCreateTime())){
            queryWrapper.eq(TmOrderTrans::getCreateTime,tmOrderTrans.getCreateTime());
        }

        //修改人
        if(Validator.isNotEmpty(tmOrderTrans.getUpdateBy())){
            queryWrapper.eq(TmOrderTrans::getUpdateBy,tmOrderTrans.getUpdateBy());
        }

        //修改时间
        if(Validator.isNotEmpty(tmOrderTrans.getUpdateTime())){
            queryWrapper.eq(TmOrderTrans::getUpdateTime,tmOrderTrans.getUpdateTime());
        }

        //删除标志（0代表存在 2代表删除）
        if(Validator.isNotEmpty(tmOrderTrans.getDelFlag())){
            queryWrapper.eq(TmOrderTrans::getDelFlag,tmOrderTrans.getDelFlag());
        }

        }

}
