package com.ruoyi.orderPlan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.basicData.domain.TCorps;
import com.ruoyi.basicData.domain.TGoods;
import com.ruoyi.basicData.mapper.TCorpsMapper;
import com.ruoyi.basicData.mapper.TGoodsMapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.finance.mapper.TFeeDoMapper;
import com.ruoyi.framework.web.service.WechatService;
import com.ruoyi.orderPlan.domain.*;
import com.ruoyi.orderPlan.mapper.*;
import com.ruoyi.orderPlan.service.IftmsorderbillscarsService;
import com.ruoyi.system.mapper.SysRoleMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.warehouseBusiness.domain.BillnoDel;
import com.ruoyi.warehouseBusiness.mapper.BillnoDelMapper;
import com.ruoyi.warehouseBusiness.service.impl.BillnoSerialServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 车队派车Service业务层处理
 *
 * @author ruoyi
 * @date 2021-02-22
 */
@Slf4j
@Service
public class FtmsorderbillscarsServiceImpl implements IftmsorderbillscarsService {

    final Logger logger = LoggerFactory.getLogger(FtmsorderbillscarsServiceImpl.class);

    @Autowired
    private TGoodsMapper tGoodsMapper;

    @Autowired
    private TFeeDoMapper tFeeDoMapper;

    @Autowired
    private TCorpsMapper tCorpsMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private BillnoDelMapper billnoDelMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private FtmsorderbillsMapper ftmsorderbillsMapper;

    @Autowired
    private BillnoSerialServiceImpl billnoSerialServiceImpl;

    @Autowired
    private FtmsorderbillsServiceImpl ftmsorderbillsService;

    @Autowired
    private FtmsorderbillscarsMapper ftmsorderbillscarsMapper;

    @Autowired
    private FtmsorderbillsfeesMapper ftmsorderbillsfeesMapper;

    @Autowired
    private FtmsorderbillsplansMapper ftmsorderbillsplansMapper;

    @Autowired
    private FtmsorderbillscntrsMapper ftmsorderbillscntrsMapper;

    @Autowired
    private FtmsorderbillsattachsMapper ftmsorderbillsattachsMapper;

    /**
     * 查询车队派车
     *
     * @param id 车队派车ID
     * @return 车队派车
     */
    @Override
    public Map<String, Object> selectftmsorderbillscarsById(Long id) {
        Map<String, Object> map = new HashMap<>();
        Ftmsorderbillsplans ftmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(id);
        if (StringUtils.isNull(ftmsorderbillsplans)) {
            return AjaxResult.error("未找到调度数据，请确认");
        }
        map.put("plans", ftmsorderbillsplans);
        // 查询订单主表
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(ftmsorderbillsplans.getOrgId());
        map.put("tmsorder", ftmsorderbills);
        // 查询派车信息
        Ftmsorderbillscars ftmsorderbillscars = new Ftmsorderbillscars();
        ftmsorderbillscars.setpId(id);
        List<Ftmsorderbillscars> tmsorderbillscarsList = ftmsorderbillscarsMapper.selectftmsorderbillscarsList(ftmsorderbillscars);
        map.put("cars", tmsorderbillscarsList);
        // 查询附件信息
        Ftmsorderbillsattachs ftmsorderbillsattachs = new Ftmsorderbillsattachs();
        ftmsorderbillsattachs.setPId(id);
        ftmsorderbillsattachs.setActId(1020L);
        map.put("attachs", ftmsorderbillsattachsMapper.selectftmsorderbillsattachsList(ftmsorderbillsattachs));
        // 查询费用信息
        Ftmsorderbillsfees ftmsorderbillsfees = new Ftmsorderbillsfees();
        ftmsorderbillsfees.setfPid(id);
        ftmsorderbillsfees.setActId(1020L);
        map.put("fees", ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesList(ftmsorderbillsfees));
        return map;
    }

    /**
     * 查询车队派车列表
     *
     * @param ftmsorderbillscars 车队派车
     * @return 车队派车
     */
    @Override
    public List<Ftmsorderbillscars> selectftmsorderbillscarsList(Ftmsorderbillscars ftmsorderbillscars) {
        return ftmsorderbillscarsMapper.selectftmsorderbillscarsList(ftmsorderbillscars);
    }

    /**
     *  判断当前用户是否为车队、是否是司机
     * @param ftmsorderbills    条件
     * @return  结果
     */
    @Override
    public Ftmsorderbills judgmentFleet(Ftmsorderbills ftmsorderbills) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String phonenumber = user.getPhonenumber();
        if ("11".equals(user.getUserType())) {
            if (StringUtils.isNotEmpty(phonenumber)) {
                ftmsorderbills.setDriverTel(phonenumber);
            } else {
                return null;
            }
        }
        if ("22".equals(user.getUserType())) {
            ftmsorderbills.setIsFleet("1");
            TCorps corps = tCorpsMapper.selectTCorpsByFTel(phonenumber);
            ftmsorderbills.setFleetId(corps.getfId());
        }
        return ftmsorderbills;
    }

    /**
     * 查询司机状态跟踪列表
     *
     * @param ftmsorderbills 条件
     * @return 结果
     */
    @Override
    public List<FtmsorderbillscarsExcel> selectftmsorderbillscarsMapList(Ftmsorderbills ftmsorderbills) {
        return ftmsorderbillscarsMapper.selectftmsorderbillscarsMapList(ftmsorderbills);
    }

    /**
     * 费用修改的查询司机状态跟踪列表
     *
     * @param ftmsorderbills
     * @return
     */
    @Override
    public List<FtmsorderbillscarsExcel> selectftmsorderbillscarsMapListModify(Ftmsorderbills ftmsorderbills) {
        return ftmsorderbillscarsMapper.selectftmsorderbillscarsMapListModify(ftmsorderbills);
    }

    /**
     *  根据查询条件查询 状态跟踪列表页 按钮数据
     * @return  结果
     */
    @Override
    public Map<String, Object> getButtonValue() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String phonenumber = user.getPhonenumber();
        Ftmsorderbills ftmsorderbills = new Ftmsorderbills();
        if ("11".equals(user.getUserType())) {
            if (StringUtils.isNotEmpty(phonenumber)) {
                ftmsorderbills.setDriverTel(phonenumber);
            } else {
                return null;
            }
        }
        // 判断是不是车队
        if ("22".equals(user.getUserType())) {
            ftmsorderbills.setIsFleet("1");
            TCorps corps = tCorpsMapper.selectTCorpsByFTel(user.getPhonenumber());
            ftmsorderbills.setFleetId(corps.getfId());
        }
        return ftmsorderbillscarsMapper.getButtonValue(ftmsorderbills);
    }

    /**
     * 根据手机号查询司机的
     * 新订单、本月订单、本月历程、本月运费
     * @param phoneNumber   手机号
     * @return  结果
     */
    @Override
    public AjaxResult selectDriverPerformance(String phoneNumber) {
        SysUser sysUser = sysUserMapper.selectUserByTel(phoneNumber);
        if (StringUtils.isNull(sysUser)) {
            return AjaxResult.error("未找到司机信息，请确认手机号");
        }
        // 查询未接单数量
        int count = ftmsorderbillscarsMapper.selectMissedOrdersCount(phoneNumber);
        // 月份
        Ftmsorderbillscars ftmsorderbillscars = new Ftmsorderbillscars();
        ftmsorderbillscars.setDriverTel(phoneNumber);
        ftmsorderbillscars.setMonthList(DateUtils.getMonthList());
        Map<String, Object> map = ftmsorderbillscarsMapper.selectMonthlyOrder(ftmsorderbillscars);
        map.put("count", count);
        return AjaxResult.success(map);
    }

    /**
     * 根据司机id查询详细信息
     *
     * @param ftmsorderbillscars 用户id
     * @return 结果
     */
    @Override
    public Map<String, Object> selectDriver(Ftmsorderbillscars ftmsorderbillscars) {
        Map<String, Object> map = new HashMap<>();
        Long id = ftmsorderbillscars.getId();
        Map<String, Object> carsMap = ftmsorderbillscarsMapper.selectTmsorderbillsCarsByDriver(id);
        if (StringUtils.isNotNull(carsMap)) {
            String billKind = carsMap.get("billKind").toString();
            if (StringUtils.isNotEmpty(billKind) && "MM".equalsIgnoreCase(billKind)) {
                String mBillNo = carsMap.get("mBillNo").toString();
                map.put("carsTable", ftmsorderbillscarsMapper.selectTmsorderbillsCarsByBillKind(mBillNo));
            }
        }
        map.put("cars", carsMap);
        Ftmsorderbillsattachs ftmsorderbillsattachs = new Ftmsorderbillsattachs();
        map.put("feesList", ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesByPId(id));
        ftmsorderbillsattachs.setPId(id);
        ftmsorderbillsattachs.setActId(1030L);
        map.put("attachs", ftmsorderbillsattachsMapper.selectftmsorderbillsattachsList(ftmsorderbillsattachs));
        return map;
    }

    /**
     *
     * 获取暂存表数据
     * @param ftmsorderbillscars
     * @return
     */
    @Override
    public Map<String, Object> selectDriverModify(Ftmsorderbillscars ftmsorderbillscars) {
        Map<String, Object> map = new HashMap<>();
        Long id = ftmsorderbillscars.getId();
        Map<String, Object> carsMap = ftmsorderbillscarsMapper.selectTmsorderbillsCarsByDriver(id);
        if (StringUtils.isNotNull(carsMap)) {
            String billKind = carsMap.get("billKind").toString();
            if (StringUtils.isNotEmpty(billKind) && "MM".equalsIgnoreCase(billKind)) {
                String mBillNo = carsMap.get("mBillNo").toString();
                map.put("carsTable", ftmsorderbillscarsMapper.selectTmsorderbillsCarsByBillKind(mBillNo));
            }
        }
        map.put("cars", carsMap);
        map.put("feesListModify", ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesBySrcMId(id));
        map.put("feesListAudited", ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesByPId(id));
        return map;
    }

    /**
     * 司机操作接单/提箱/装卸货/还卸柜/回单操作  变更
     *
     * @param cars          司机信息
     * @param operationType 操作类型
     * @param loginUser     用户
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult operationalChanges(String cars, String operationType, LoginUser loginUser) {
        Ftmsorderbillscars tmsorderbillscars = JSONArray.parseObject(cars, Ftmsorderbillscars.class);
        if (StringUtils.isNull(tmsorderbillscars.getId())) {
            return AjaxResult.error("未找到司机信息id");
        }
        Ftmsorderbillsfees ftmsorderbillsfees = new Ftmsorderbillsfees();
        ftmsorderbillsfees.setActId(1090L);
        if (ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesCount(ftmsorderbillsfees) > 0) {
            return AjaxResult.error("运单已完成，无法变更");
        }
        return AjaxResult.success();
    }

    /**
     * 司机操作接单/提箱/装卸货/还卸柜/回单操作  保存
     *
     * @param cars          派车
     * @param attachs       附件
     * @param operationType 状态
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult driverSave(String cars, String fees, String attachs, String operationType) {
        Ftmsorderbillscars tmsorderbillscars = JSONArray.parseObject(cars, Ftmsorderbillscars.class);
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(tmsorderbillscars.getOrgId());
        tmsorderbillscars.setUpdateTime(new Date());
        tmsorderbillscars.setUpdateBy(SecurityUtils.getUsername());
        tmsorderbillscars.setMblno(ftmsorderbills.getMblno());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(tmsorderbillscars);
        long pId = tmsorderbillscars.getId();
        long orgId = tmsorderbillscars.getOrgId();
        long orderStatus = 1030L;
        Ftmsorderbillsattachs ftmsorderbillsattachs = new Ftmsorderbillsattachs();
        ftmsorderbillsattachs.setPId(pId);
        ftmsorderbillsattachs.setActId(orderStatus);
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachs(ftmsorderbillsattachs);
        ftmsorderbillsfeesMapper.deleteFTmsorderbillsfeesByPId(pId);
        if (StringUtils.isNotEmpty(fees) && !"[]".equals(fees)) {
            JSONArray attachJson = JSONArray.parseArray(fees);
            List<Ftmsorderbillsfees> ftmsorderbillsfees = JSONObject.parseArray(attachJson.toJSONString(), Ftmsorderbillsfees.class);
            for (Ftmsorderbillsfees f : ftmsorderbillsfees) {
                f.setfPid(pId);
                if (StringUtils.isNull(f.getfId())) {
                    f.setfStatus(2L);
                }
                f.setOrgId(orgId);
                f.setCreateTime(new Date());
                f.setCreateBy(SecurityUtils.getUsername());
                if (ftmsorderbillsfeesMapper.insertFTmsorderbillsfees(f) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            JSONArray attachJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(attachJson.toJSONString(), Ftmsorderbillsattachs.class);
            for (Ftmsorderbillsattachs a : tmsorderbillsattachsList) {
                a.setPId(pId);
                a.setOrgId(orgId);
                a.setBillStatus(2L);
                a.setActId(orderStatus);
                a.setCreateTime(new Date());
                a.setCreateBy(SecurityUtils.getUsername());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(a) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 司机操作接单/提箱/装卸货/还卸柜/回单操作  提交
     *
     * @param cars          派车
     * @param attachs       附件
     * @param operationType 状态
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertDriver(String cars, String attachs, String operationType) {
        Ftmsorderbillscars tmsorderbillscars = JSONArray.parseObject(cars, Ftmsorderbillscars.class);
        long pId = tmsorderbillscars.getId();
        long orgId = tmsorderbillscars.getOrgId();
        String otherStatus = ftmsorderbillsService.dataValidation(null, attachs, null, null, null);
        if (StringUtils.isNotEmpty(otherStatus)) {
            return AjaxResult.error(otherStatus);
        }
        String status = ftmsorderbillsService.objValidation(null, null, null, null, cars);
        if (StringUtils.isNotEmpty(status)) {
            return AjaxResult.error(status);
        }
        long actId = 1030L;
        boolean orderStatus = false;
        if (tmsorderbillscars.getOrderStatus() == 80L) {
            orderStatus = true;
        }
        if ("waybillDate".equals(operationType)) {
            // 回单提交
            if (StringUtils.isNull(tmsorderbillscars.getWaybillDate())) {
                return AjaxResult.error("未找到还卸柜时间");
            }
            tmsorderbillscars.setOrderStatus(80L);
        } else if ("unLoadDate".equals(operationType)) {
            // 还卸柜提交
            if (StringUtils.isNull(tmsorderbillscars.getUnLoadDate())) {
                return AjaxResult.error("未找到还卸柜时间");
            }
            if (orderStatus) {
                return AjaxResult.error("该运单已回单，若多次失败请联系管理员");
            } else if (tmsorderbillscars.getOrderStatus() < 80L) {
                tmsorderbillscars.setOrderStatus(60L);
            }
        } else if ("mdLoadDate".equals(operationType)) {
            // 装卸货提交
            if (StringUtils.isNull(tmsorderbillscars.getMdLoadDate())) {
                return AjaxResult.error("未找到装卸货时间");
            }
            if (orderStatus) {
                return AjaxResult.error("该运单已回单，若多次失败请联系管理员");
            } else if (tmsorderbillscars.getOrderStatus() < 60L) {
                tmsorderbillscars.setOrderStatus(50L);
            }
        } else if ("loadDate".equals(operationType)) {
            // 提箱提交
            if (StringUtils.isNull(tmsorderbillscars.getLoadDate())) {
                return AjaxResult.error("未找到提箱时间");
            }
            if (orderStatus) {
                return AjaxResult.error("该运单已回单，若多次失败请联系管理员");
            } else if (tmsorderbillscars.getOrderStatus() < 50L) {
                tmsorderbillscars.setOrderStatus(40L);
            }
        } else if ("acceptDate".equals(operationType)) {
            // 接单提交
            if (StringUtils.isNull(tmsorderbillscars.getAcceptDate())) {
                return AjaxResult.error("未找到接单时间");
            }
            if (orderStatus) {
                return AjaxResult.error("该运单已回单，若多次失败请联系管理员");
            } else if (tmsorderbillscars.getOrderStatus() < 40L) {
                tmsorderbillscars.setOrderStatus(20L);
            }
        }
        tmsorderbillscars.setUpdateTime(new Date());
        tmsorderbillscars.setUpdateBy(SecurityUtils.getUsername());
        if (ftmsorderbillscarsMapper.updateftmsorderbillscars(tmsorderbillscars) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新司机状态失败，若多次失败请联系管理员");
        }
        Ftmsorderbillsattachs ftmsorderbillsattachs = new Ftmsorderbillsattachs();
        ftmsorderbillsattachs.setPId(pId);
        ftmsorderbillsattachs.setActId(actId);
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachs(ftmsorderbillsattachs);
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            JSONArray attachJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(attachJson.toJSONString(), Ftmsorderbillsattachs.class);
            for (Ftmsorderbillsattachs a : tmsorderbillsattachsList) {
                a.setPId(pId);
                a.setOrgId(orgId);
                a.setBillStatus(6L);
                a.setActId(actId);
                a.setCreateTime(new Date());
                a.setCreateBy(SecurityUtils.getUsername());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(a) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }

        //新增逻辑20210707 dongyongwei,
        //更改订单状态为
        //7回单中 派车量和回单量比较 派车量大于0 回单量<>0   派车量>回单量 
        //8回单完成 派车量和回单量比较 派车量大于0 派车量=回单量
        ftmsorderbillsService.setFtmsorderbillsBillStatus(orgId,7L);

        return AjaxResult.success(tmsorderbillscars);
    }

    /**
     *  状态跟踪提交
     * @param cars      车辆信息
     * @param fees      费用信息
     * @param attachs   附件信息
     * @return  结果
     */
    @Transactional
    @Override
    public AjaxResult driverSubmit(String cars, String fees, String attachs) {
        Ftmsorderbillscars tmsorderbillscars = JSONArray.parseObject(cars, Ftmsorderbillscars.class);
        long pId = tmsorderbillscars.getId();
        long orgId = tmsorderbillscars.getOrgId();
        Ftmsorderbillscars ftmsorderbillscars = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(pId);
        if (StringUtils.isNull(tmsorderbillscars.getAcceptDate())) {
            return AjaxResult.error("该运单未填写接单日期");
        }
        if (ftmsorderbillscars.getOrderStatus() < 60L) {
            return AjaxResult.error("运单状态异常该运单未回单：" + ftmsorderbillscars.getBillStatus());
        }
        if (ftmsorderbillscars.getBillStatus() < 6L) {
            return AjaxResult.error("运单状态异常：" + ftmsorderbillscars.getBillStatus());
        }
        if (ftmsorderbillscars.getBillStatus() == 7L) {
            return AjaxResult.error("该运单不允许重复提交");
        }
        tmsorderbillscars.setBillStatus(7L);
        tmsorderbillscars.setUpdateTime(new Date());
        tmsorderbillscars.setUpdateBy(SecurityUtils.getUsername());
        tmsorderbillscars.setOrderStatus(ftmsorderbillscars.getOrderStatus());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(tmsorderbillscars);
        if (StringUtils.isNotEmpty(fees) && !"[]".equals(fees)) {
            JSONArray attachJson = JSONArray.parseArray(fees);
            List<Ftmsorderbillsfees> ftmsorderbillsfeesList = JSONObject.parseArray(attachJson.toJSONString(), Ftmsorderbillsfees.class);
            int line = 0;
            for (Ftmsorderbillsfees f : ftmsorderbillsfeesList) {
                line++;
                if (StringUtils.isNull(f.getfBillstatus()) || f.getfBillstatus() != 6) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("费用信息第"+line+"行，状态异常，请确认是否提交");
                }
            }
        }
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachsByPId(pId);
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            JSONArray attachJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(attachJson.toJSONString(), Ftmsorderbillsattachs.class);
            for (Ftmsorderbillsattachs a : tmsorderbillsattachsList) {
                a.setPId(pId);
                a.setOrgId(orgId);
                a.setCreateTime(new Date());
                a.setCreateBy(SecurityUtils.getUsername());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(a) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询车辆可配载运单
     * @param ftmsorderbillscars    车队派车
     * @return
     */
    @Override
    public List<Map<String, Object>> selectStowageList(Ftmsorderbillscars ftmsorderbillscars) {
        return ftmsorderbillscarsMapper.selectStowageList(ftmsorderbillscars);
    }

    /**
     *  撤销车辆配载
     * @param id    车辆id
     * @return  结果
     */
    @Override
    @Transactional
    public AjaxResult revokeStowage(Long id) {
        Ftmsorderbillscars tmsorderbillscars = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(id);
        if (StringUtils.isNull(tmsorderbillscars)) {
            return AjaxResult.error("未找到运单信息，请确认是否存在该运单");
        }
        if (!"MH".equals(tmsorderbillscars.getBillKind())) {
            return AjaxResult.error("该运单不是分单无法撤销");
        }
        if (tmsorderbillscars.getOrderStatus() > 80L || tmsorderbillscars.getBillStatus() > 6) {
            return AjaxResult.error("该运单已回单或已完成无法撤销配载");
        }
        // 清除从表
        Ftmsorderbillscars ftmsorderbillscars = ftmsorderbillscarsMapper.selectftmsorderbillscarsByOrderNo(tmsorderbillscars.getmBillNo());
        if (StringUtils.isNull(ftmsorderbillscars)) {
            return AjaxResult.error("未找到运单信息，请确认是否存在该运单");
        }
        if (ftmsorderbillscars.getOrderStatus() > 80L || ftmsorderbillscars.getBillStatus() > 6) {
            return AjaxResult.error("该运单已回单或已完成无法撤销配载");
        }
        ftmsorderbillscars.setmBillNo(ftmsorderbillscars.getOrderNo());
        ftmsorderbillscars.setBillKind("NN");
        ftmsorderbillscars.setUpdateTime(new Date());
        ftmsorderbillscars.setUpdateBy(SecurityUtils.getUsername());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscars);
        tmsorderbillscars.setmBillNo(tmsorderbillscars.getOrderNo());
        tmsorderbillscars.setBillKind("NN");
        tmsorderbillscars.setUpdateTime(new Date());
        tmsorderbillscars.setUpdateBy(SecurityUtils.getUsername());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(tmsorderbillscars);
        return AjaxResult.success(ftmsorderbillscarsMapper.selectftmsorderbillscarsByPid(tmsorderbillscars.getpId()));
    }

    /**
     *  提交车辆配载
     * @param ftmsorderbillscars    车辆信息
     * @return  结果
     */
    @Override
    @Transactional
    public AjaxResult addStowage(Ftmsorderbillscars ftmsorderbillscars) {
        Ftmsorderbillscars tmsorderbillscars = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(ftmsorderbillscars.getId());
        if (StringUtils.isNull(tmsorderbillscars)) {
            return AjaxResult.error("未找到运单信息，请确认是否存在该运单");
        }
        if (tmsorderbillscars.getOrderStatus() > 80L) {
            return AjaxResult.error("该运单已回单无法配载");
        }
        if (!"NN".equals(tmsorderbillscars.getBillKind())) {
            return AjaxResult.error("配载失败，该运单已参与配载");
        }
        Ftmsorderbillscars orderNoCars = ftmsorderbillscarsMapper.selectftmsorderbillscarsByOrderNo(ftmsorderbillscars.getmBillNo());
        if (StringUtils.isNull(orderNoCars)) {
            return AjaxResult.error("未找到配载的运单信息，请确认是否存在该运单");
        }
        if (orderNoCars.getOrderStatus() > 80L) {
            return AjaxResult.error("该配载的运单已回单无法配载");
        }
        if (!"NN".equals(orderNoCars.getBillKind())) {
            return AjaxResult.error("配载失败，所选配载的运单已被配载");
        }
        tmsorderbillscars.setBillKind("MH");
        tmsorderbillscars.setmBillNo(ftmsorderbillscars.getmBillNo());
        tmsorderbillscars.setUpdateTime(new Date());
        tmsorderbillscars.setUpdateBy(SecurityUtils.getUsername());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(tmsorderbillscars);
        orderNoCars.setBillKind("MM");
        orderNoCars.setmBillNo(orderNoCars.getOrderNo());
        orderNoCars.setUpdateTime(new Date());
        orderNoCars.setUpdateBy(SecurityUtils.getUsername());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(orderNoCars);
        return AjaxResult.success(ftmsorderbillscarsMapper.selectftmsorderbillscarsByPid(tmsorderbillscars.getpId()));
    }

    /**
     * 自动配载
     * @param sourceId 来源ID,待插入数据ID,执行逻辑:插入数据,单据类型为分单,主单号为原来车辆的运单号
     * @param targetId 目标ID,待处理数据ID,执行逻辑:单据类型 变为主单
     * @return dongyongwei 20210713
     */
    @Override
    @Transactional
    public AjaxResult autoStowage(Long sourceId, Long targetId) {
        //获取来源单据
        Ftmsorderbillscars source = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(sourceId);
        //获取目标单据
        Ftmsorderbillscars target = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(targetId);

        //处理目标单据单据类型变更为主单
        target.setBillKind("MM");
        ftmsorderbillscarsMapper.updateftmsorderbillscars(target);
        //执行逻辑:插入数据,单据类型为分单,主单号为原来车辆的运单号
        Ftmsorderbillscars newTarget = new Ftmsorderbillscars();
        //原数据先复制给待插入数据
        BeanUtil.copyProperties(source,newTarget);
        //分单逻辑
        newTarget.setBillKind("MH");
        //主单号为原来车辆的运单号
        newTarget.setOrderNo(source.getmBillNo());
        //关联目标主表ID
        newTarget.setpId(target.getpId());
        //orgID
        newTarget.setOrgId(target.getOrgId());
        //执行完以上自动逻辑进行插入
        ftmsorderbillscarsMapper.insertftmsorderbillscars(newTarget);

        return AjaxResult.success("配载成功");
    }

    /**
     *  查询陆运台账列表信息
     * @param vehicleLedgerExcel    查询条件
     * @return  结果
     */
    @Override
    public List<VehicleLedgerExcel> queryLedgerList(VehicleLedgerExcel vehicleLedgerExcel) {
        List<VehicleLedgerExcel> vehicleLedgerExcels = ftmsorderbillscarsMapper.queryLedgerList(vehicleLedgerExcel);
        if (StringUtils.isNotEmpty(vehicleLedgerExcels)) {
            for (VehicleLedgerExcel ex : vehicleLedgerExcels) {
                VehicleLedgerExcel vehicleLedger = ftmsorderbillscarsMapper.selectCarsFeeByMBillNo(ex.getmBillNo());
                ex.setOtherCr(vehicleLedger.getOtherCr());
                ex.setOtherDr(vehicleLedger.getOtherDr());
                ex.setShippingCr(vehicleLedger.getShippingCr());
                ex.setShippingDr(vehicleLedger.getShippingDr());
            }
        }
        return vehicleLedgerExcels;
    }

    /**
     * 修改车队派车
     *
     * @param ftmsorderbillscars 车队派车
     * @return 结果
     */
    @Override
    @Transactional
    public int updateftmsorderbillscars(Ftmsorderbillscars ftmsorderbillscars) {
        ftmsorderbillscars.setUpdateTime(DateUtils.getNowDate());
        return ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscars);
    }

    /**
     * 车队派车的提交/保存
     *
     * @param plans     调度数据
     * @param attachs   附件表
     * @param fees      费用表
     * @param cars      车俩安排表
     * @param billType  状态
     * @param loginUser 操作人
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertftmsorderbillscars(String plans, String attachs, String fees, String cars, String billType, LoginUser loginUser) {
        String objStatus = ftmsorderbillsService.objValidation(null, null, null, plans, null);
        if (StringUtils.isNotEmpty(objStatus)) {
            return AjaxResult.error(objStatus);
        }
        Long billsStatus = 60L;
        Ftmsorderbillsplans tmsorderbillsplans = JSONArray.parseObject(plans, Ftmsorderbillsplans.class);
        Ftmsorderbills tmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(tmsorderbillsplans.getOrgId());
        long pId = tmsorderbills.getId();
        ftmsorderbillscarsMapper.deleteftmsorderbillscarsByPId(tmsorderbillsplans.getId());
        Ftmsorderbillsfees ftmsorderbillsfees = new Ftmsorderbillsfees();
        ftmsorderbillsfees.setfPid(tmsorderbillsplans.getId());
        ftmsorderbillsfees.setActId(1020L);
        ftmsorderbillsfeesMapper.deleteFTmsorderbillsfees(ftmsorderbillsfees);
        Ftmsorderbillsattachs ftmsorderbillsattachs = new Ftmsorderbillsattachs();
        ftmsorderbillsattachs.setPId(tmsorderbillsplans.getId());
        ftmsorderbillsattachs.setActId(1020L);
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachs(ftmsorderbillsattachs);
        if ("save".equals(billType)) {
            // 保存
            if (StringUtils.isNotEmpty(cars) && !"[]".equals(cars)) {
                JSONArray planJson = JSONArray.parseArray(cars);
                List<Ftmsorderbillscars> tmsorderbillscarsList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillscars.class);
                for (Ftmsorderbillscars s : tmsorderbillscarsList) {
                    if (StringUtils.isNull(s.getId())) {
                        s.setBillStatus(2L);
                    }
                    s.setOrgId(pId);
                    s.setCreateTime(new Date());
                    s.setCorpId(tmsorderbills.getCorpId());
                    s.setCreateBy(loginUser.getUsername());
                    if (ftmsorderbillscarsMapper.insertftmsorderbillscars(s) <= 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("更新车辆安排失败，若多次失败请联系管理员");
                    }
                }
            }
            Ftmsorderbillscars ftmsorderbillscars = new Ftmsorderbillscars();
            ftmsorderbillscars.setBillStatus(6L);
            if (ftmsorderbillscarsMapper.selectftmsorderbillscarsCount(ftmsorderbillscars) > 0) {
                tmsorderbillsplans.setBillStatus(20L);
            } else {
                tmsorderbillsplans.setBillStatus(6L);
            }
            tmsorderbillsplans.setUpdateTime(new Date());
            tmsorderbillsplans.setUpdateBy(loginUser.getUsername());
            ftmsorderbillsplansMapper.updateftmsorderbillsplans(tmsorderbillsplans);
        } else {
            String status = ftmsorderbillsService.dataValidation(null, attachs, fees, null, cars);
            if (StringUtils.isNotEmpty(status)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error(status);
            }
            // 提交
            tmsorderbillsplans.setBillStatus(60L);
            tmsorderbillsplans.setUpdateTime(new Date());
            tmsorderbillsplans.setUpdateBy(loginUser.getUsername());
            ftmsorderbillsplansMapper.updateftmsorderbillsplans(tmsorderbillsplans);
            billsStatus = 80L;
            JSONArray planJson = JSONArray.parseArray(cars);
            List<Ftmsorderbillscars> tmsorderbillscarsList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillscars.class);
            for (Ftmsorderbillscars s : tmsorderbillscarsList) {
                if (StringUtils.isNull(s.getBillStatus()) || (s.getBillStatus() != 3L && s.getBillStatus() < 6L)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("派车数据中存在未提交的数据，无法提交");
                }
                s.setOrgId(pId);
                if (StringUtils.isNull(s.getId())) {
                    s.setBillStatus(6L);
                }
                s.setCreateTime(new Date());
                s.setMblno(tmsorderbills.getMblno());
                s.setCorpId(tmsorderbills.getCorpId());
                s.setCreateBy(loginUser.getUsername());
                if (ftmsorderbillscarsMapper.insertftmsorderbillscars(s) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新车辆安排失败，若多次失败请联系管理员");
                }
                /*Ftmsorderbillsplans ftmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(s.getPId());
                Long qty = ftmsorderbillsplans.getCarQty() + s.getCntrQty();
                if (qty > ftmsorderbillsplans.getCntrQty()) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("车辆安排第" + line + "行，货量超出调度货量");
                }
                ftmsorderbillsplans.setCarQty(qty);
                ftmsorderbillsplansMapper.updateftmsorderbillsplans(ftmsorderbillsplans);*/
            }
        }
        if (StringUtils.isNotNull(fees) && !"[]".equals(fees)) {
            JSONArray feesJson = JSONArray.parseArray(fees);
            List<Ftmsorderbillsfees> tmsorderbillsfeesList = JSONObject.parseArray(feesJson.toJSONString(), Ftmsorderbillsfees.class);
            for (Ftmsorderbillsfees a : tmsorderbillsfeesList) {
                a.setfPid(tmsorderbillsplans.getId());
                a.setOrgId(pId);
                a.setActId(1020L);
                a.setfBillstatus(billsStatus);
                a.setCreateTime(new Date());
                a.setCreateBy(loginUser.getUsername());
                if (ftmsorderbillsfeesMapper.insertFTmsorderbillsfees(a) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新费用数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotNull(attachs) && !"[]".equals(attachs)) {
            JSONArray attachJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(attachJson.toJSONString(), Ftmsorderbillsattachs.class);
            for (Ftmsorderbillsattachs a : tmsorderbillsattachsList) {
                a.setPId(tmsorderbillsplans.getId());
                a.setOrgId(pId);
                a.setActId(1020L);
                a.setBillStatus(billsStatus);
                a.setCreateBy(loginUser.getUsername());
                a.setCreateTime(new Date());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(a) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        return AjaxResult.success(ftmsorderbillscarsMapper.selectftmsorderbillscarsByPid(tmsorderbillsplans.getId()));
    }

    /**
     * 批量删除车队派车
     *
     * @param ids 需要删除的车队派车ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteftmsorderbillscarsByIds(Long[] ids) {
        return ftmsorderbillscarsMapper.deleteftmsorderbillscarsByIds(ids);
    }

    /**
     * 删除车队派车信息
     *
     * @param id 车队派车ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteftmsorderbillscarsById(Long id) {
        return ftmsorderbillscarsMapper.deleteftmsorderbillscarsById(id);
    }

    /**
     * 单条车辆安排提交接口
     *
     * @param status             状态
     * @param ftmsorderbillscars 车辆安排数据
     * @param loginUser          当前操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult vehicleArrangement(String status, Ftmsorderbillscars ftmsorderbillscars, LoginUser loginUser) {
        //新增逻辑  20210714 dongyongwei
        // 配载常规提交
        if ("addStowage".equals(status)) {
            AjaxResult result = vehicleChangeAdd(ftmsorderbillscars, loginUser);
            String ajaxCode = result.get("code").toString();
            if ("500".equals(ajaxCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            //新增更改配载过来的单据的状态为:主单,字典:直单NN主单MM从单MH 20210714
            //配载过来的单据的主单号,实际为来之前的单据的运单号
            String orderNo = ftmsorderbillscars.getmBillNo();
            Ftmsorderbillscars ftmsorderbillscarsBefore = ftmsorderbillscarsMapper.selectftmsorderbillscarsByOrderNo(orderNo);
            ftmsorderbillscarsBefore.setBillKind("MM");
            ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscarsBefore);

            //新增逻辑20210707 dongyongwei,
            //更改订单状态为
            //5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
            //6待回单 调度量和派车量比较 调度量大于0 调度量=派车
            ftmsorderbillsService.setFtmsorderbillsBillStatus(ftmsorderbillscars.getOrgId(),5L);

            return result;
        }

        // 常规提交
        if ("add".equals(status)) {
            AjaxResult result = vehicleChangeAdd(ftmsorderbillscars, loginUser);
            String ajaxCode = result.get("code").toString();
            if ("500".equals(ajaxCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

            //新增逻辑20210707 dongyongwei,
            //更改订单状态为
            //5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
            //6待回单 调度量和派车量比较 调度量大于0 调度量=派车
            ftmsorderbillsService.setFtmsorderbillsBillStatus(ftmsorderbillscars.getOrgId(),5L);

            return result;
        }
        // 变更提交
        if ("change".equals(status)) {
            AjaxResult result = vehicleChangeSubmission(ftmsorderbillscars, loginUser);
            String ajaxCode = result.get("code").toString();
            if ("500".equals(ajaxCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            //新增逻辑20210707 dongyongwei,
            //更改订单状态为
            //5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
            //6待回单 调度量和派车量比较 调度量大于0 调度量=派车
            ftmsorderbillsService.setFtmsorderbillsBillStatus(ftmsorderbillscars.getOrgId(),5L);
            return result;
        }

        // 配载撤销 20210714 dongyongwei
        if ("revokeStowage".equals(status)) {
            AjaxResult result = vehicleChangeRevokeStowage(ftmsorderbillscars, loginUser);
            String ajaxCode = result.get("code").toString();
            if ("500".equals(ajaxCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            //新增逻辑20210707 dongyongwei,
            //更改订单状态为
            //5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
            //6待回单 调度量和派车量比较 调度量大于0 调度量=派车
            ftmsorderbillsService.setFtmsorderbillsBillStatus(ftmsorderbillscars.getOrgId(),5L);
            return result;
        }

        // 撤销
        if ("revoke".equals(status)) {
            AjaxResult result = vehicleChangeRevoke(ftmsorderbillscars, loginUser);
            String ajaxCode = result.get("code").toString();
            if ("500".equals(ajaxCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            //新增逻辑20210707 dongyongwei,
            //更改订单状态为
            //5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
            //6待回单 调度量和派车量比较 调度量大于0 调度量=派车
            ftmsorderbillsService.setFtmsorderbillsBillStatus(ftmsorderbillscars.getOrgId(),5L);
            return result;
        }
        // 删除
        if ("remove".equals(status)) {
            AjaxResult result = vehicleChangeRemove(ftmsorderbillscars, loginUser);
            String ajaxCode = result.get("code").toString();
            if ("500".equals(ajaxCode)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            //新增逻辑20210707 dongyongwei,
            //更改订单状态为
            //5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
            //6待回单 调度量和派车量比较 调度量大于0 调度量=派车
            ftmsorderbillsService.setFtmsorderbillsBillStatus(ftmsorderbillscars.getOrgId(),5L);
            return result;
        }

        //新增逻辑20210707 dongyongwei,
        //更改订单状态为
        //5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
        //6待回单 调度量和派车量比较 调度量大于0 调度量=派车
        ftmsorderbillsService.setFtmsorderbillsBillStatus(ftmsorderbillscars.getOrgId(),5L);
        return AjaxResult.success();
    }


    /**
     * 单条车辆安排 是否允许变更
     *
     * @param id        安排id
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult vehicleOperationChanges(Long id) {
        Ftmsorderbillscars ftmsorderbillscars = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(id);
        if (StringUtils.isNull(ftmsorderbillscars)) {
            return AjaxResult.error("未找到车辆信息，请确认");
        }
        Long billStatus = ftmsorderbillscars.getBillStatus();
        if (billStatus == 3L) {
            return AjaxResult.error("车辆安排信息已撤销无法变更");
        } else if (billStatus < 6) {
            return AjaxResult.error("车辆安排信息未提交无法变更");
        }
        return AjaxResult.success();
    }

    /**
     * 车辆派车主表变更
     *
     * @param id        调度id
     * @param loginUser 用户
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult dispatchChange(Long id, LoginUser loginUser) {
        Ftmsorderbillsplans ftmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(id);
        if (ftmsorderbillsplans.getBillStatus() <= 20L) {
            return AjaxResult.error("该数据未提交，无法变更");
        }
        if (ftmsorderbillsplans.getBillStatus() == 50L) {
            return AjaxResult.error("该数据已在变更中");
        }
        ftmsorderbillsplans.setBillStatus(60L);
        ftmsorderbillsplans.setUpdateTime(new Date());
        ftmsorderbillsplans.setUpdateBy(loginUser.getUsername());
        if (ftmsorderbillsplansMapper.updateftmsorderbillsplans(ftmsorderbillsplans) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新派车变更状态失败，若多次失败请联系管理员");
        }
        return AjaxResult.success();
    }

    /**
     * 单条车辆安排提交
     *
     * @return 结果
     */
    @Transactional
    public AjaxResult vehicleChangeAdd(Ftmsorderbillscars ftmsorderbillscars, LoginUser loginUser) {
        Map<String, Object> map = new HashMap<>();
        Ftmsorderbillsplans ftmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(ftmsorderbillscars.getpId());
        if (StringUtils.isNull(ftmsorderbillscars.getCntrQty())) {
            return AjaxResult.error("未找到派车数量，请确认");
        }
        long carQty = ftmsorderbillsplans.getCarQty() + ftmsorderbillscars.getCntrQty();
        if (ftmsorderbillsplans.getCntrQty() < carQty) {
            return AjaxResult.error("派车货量超出调度安排数量，请确认");
        }
        Ftmsorderbills tmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(ftmsorderbillsplans.getOrgId());
        // 生成流水号
        Date time = new Date();
        String billNo = billnoSerialServiceImpl.getSerialNumber("SJLSH", time);
        ftmsorderbillscars.setOrderNo(billNo);
        //新增配载逻辑 20210714 dongyongwei
        //如果配载过来的主单号存在,则直接赋值,反之,走之前的逻辑
        if(StrUtil.isBlank(ftmsorderbillscars.getmBillNo())){
            ftmsorderbillscars.setmBillNo(billNo);
        }
        ftmsorderbillscars.setMblno(tmsorderbills.getMblno());
        ftmsorderbillscars.setOrgId(ftmsorderbillsplans.getOrgId());
        if (ftmsorderbillsplansMapper.updateftmsorderbillsplans(ftmsorderbillsplans) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新调度数据失败，若多次失败请联系管理员");
        }
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(ftmsorderbillsplans.getOrgId());
        ftmsorderbillscars.setCorpId(tmsorderbills.getCorpId());
        ftmsorderbillscars.setQtyDr(new BigDecimal(ftmsorderbillscars.getCntrQty()));
        ftmsorderbillscars.setQtyCr(new BigDecimal(ftmsorderbillscars.getCntrQty()));
        BigDecimal amtDr = ftmsorderbillscars.getFreightPriceDr().multiply(ftmsorderbillscars.getQtyDr());
        ftmsorderbillscars.setFreightAmtDr(amtDr);
        BigDecimal amtCr = ftmsorderbillscars.getFreightPriceCr().multiply(ftmsorderbillscars.getQtyCr());
        ftmsorderbillscars.setFreightAmtCr(amtCr);
        ftmsorderbillscars.setBillStatus(6L);
        ftmsorderbillscars.setOrderStatus(10L);
        ftmsorderbillscars.setPlanDate(new Date());
        ftmsorderbillscars.setCreateTime(new Date());
        ftmsorderbillscars.setMblno(ftmsorderbills.getMblno());
        ftmsorderbillscars.setCreateBy(loginUser.getUsername());
        if (StringUtils.isNull(ftmsorderbillscars.getId())) {
            ftmsorderbillscarsMapper.insertftmsorderbillscars(ftmsorderbillscars);
        } else {
            ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscars);
        }
        map.put("cars", ftmsorderbillscarsMapper.selectftmsorderbillscarsById(ftmsorderbillscars.getId()));
        map.put("plan", ftmsorderbillsplansMapper.selectftmsorderbillsplansById(ftmsorderbillsplans.getId()));
        SysUser sysUser = sysUserMapper.selectUserByTel(ftmsorderbillscars.getDriverTel());
        if (StringUtils.isNotNull(sysUser)) {
            String loadAddr = "";
            String mdLoadAddr = "";
            String goodsName = "";
            if (StringUtils.isNotEmpty(tmsorderbills.getLoadAddr())) {
                loadAddr = tmsorderbills.getLoadAddr();
            }
            if (StringUtils.isNotEmpty(tmsorderbills.getMdLoadAddr())) {
                loadAddr = tmsorderbills.getMdLoadAddr();
            }
            String route = loadAddr + " - " + mdLoadAddr;
            if (StringUtils.isNotNull(tmsorderbills.getGoodsId())) {
                TGoods goods = tGoodsMapper.selectTGoodsById(tmsorderbills.getGoodsId());
                if (StringUtils.isNotNull(goods)) {
                    goodsName = goods.getfName();
                }
            }
            String openId = sysUser.getOpenId();
            String mblno = ftmsorderbillscars.getMblno();
            String loadDate = null;
            if (StringUtils.isNotNull(tmsorderbills.getLoadDate())) {
                loadDate = DateUtils.dateTime(tmsorderbills.getLoadDate());
            }
            wechatService.newsPush(openId, mblno, route, goodsName, loadDate);
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("未找到司机信息，请确认");
        }
        return AjaxResult.success(map);
    }

    /**
     * 单条车辆安排撤销(配载)
     *20210714 dongyongwei
     * @return 结果
     */
    @Transactional
    public AjaxResult vehicleChangeRevokeStowage(Ftmsorderbillscars ftmsorderbillscars, LoginUser loginUser) {
        //先取出真正需要撤销的单据
        //运单号,也就是配载单的主单号
        String orderNo = ftmsorderbillscars.getOrderNo();
        Ftmsorderbillscars ftmsorderbillscarsQuery = new Ftmsorderbillscars();
        ftmsorderbillscarsQuery.setmBillNo(orderNo);
        List<Ftmsorderbillscars> ftmsorderbillscarsList = ftmsorderbillscarsMapper.selectftmsorderbillscarsList(ftmsorderbillscarsQuery);
        //取最后一条配载的记录进行逻辑操作
        Ftmsorderbillscars ftmsorderbillscarsStowage = ftmsorderbillscarsList.get(ftmsorderbillscarsList.size()-1);

        Map<String, Object> map = new HashMap<>();
        // 验证司机是否产生费用，若产生的费用已经结算则拦截
        List<Ftmsorderbillsfees> ftmsorderbillsfeesList = ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesByPId(ftmsorderbillscarsStowage.getId());
/*        if (!"NN".equals(ftmsorderbillscarsStowage.getBillKind())) {
            return AjaxResult.error("该运单已参与配载，无法撤销");
        }*/
        if (ftmsorderbillsfeesList.size() != 0) {
            for (Ftmsorderbillsfees f : ftmsorderbillsfeesList) {
                if (StringUtils.isNotEmpty(f.getfStlamountNo())) {
                    return AjaxResult.error("该安排车辆费用已经结算，无法撤销");
                }
            }
        }
        if (ftmsorderbillscarsStowage.getOrderStatus() > 30) {
            return AjaxResult.error("该安排车辆已经装卸货，无法撤回");
        }
        ftmsorderbillscarsStowage.setBillStatus(3L);
        ftmsorderbillscarsStowage.setUpdateTime(new Date());
        ftmsorderbillscarsStowage.setUpdateBy(loginUser.getUsername());

        //执行配载逻辑:原单又变回直单,新增的这条变直单,运单号赋值给主单号
        //新增的这条变直单,运单号赋值给主单号
        ftmsorderbillscarsStowage.setmBillNo(ftmsorderbillscarsStowage.getOrderNo());
        ftmsorderbillscarsStowage.setBillKind("NN");//直单NN主单MM从单MH
        logger.debug("变更ftmsorderbillscarsStowage:"+ftmsorderbillscarsStowage.toString());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscarsStowage);
        //原单又变回直单,保证数据完整性,通过原单的id重新获取一下整条记录
        Ftmsorderbillscars ftmsorderbillscarsBefore = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(ftmsorderbillscars.getId());
        ftmsorderbillscarsBefore.setBillKind("NN");
        logger.debug("变更ftmsorderbillscarsBefore:"+ftmsorderbillscarsBefore.toString());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscarsBefore);

        map.put("plan", ftmsorderbillsplansMapper.selectftmsorderbillsplansById(ftmsorderbillscarsStowage.getpId()));
        map.put("cars", ftmsorderbillscarsStowage);
        return AjaxResult.success(map);
    }

    /**
     * 单条车辆安排撤销
     *
     * @return 结果
     */
    @Transactional
    public AjaxResult vehicleChangeRevoke(Ftmsorderbillscars ftmsorderbillscars, LoginUser loginUser) {
        Map<String, Object> map = new HashMap<>();
        // 验证司机是否产生费用，若产生的费用已经结算则拦截
        List<Ftmsorderbillsfees> ftmsorderbillsfeesList = ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesByPId(ftmsorderbillscars.getId());
        if (!"NN".equals(ftmsorderbillscars.getBillKind())) {
            return AjaxResult.error("该运单已参与配载，无法撤销");
        }
        if (ftmsorderbillsfeesList.size() != 0) {
            for (Ftmsorderbillsfees f : ftmsorderbillsfeesList) {
                if (StringUtils.isNotEmpty(f.getfStlamountNo())) {
                    return AjaxResult.error("该安排车辆费用已经结算，无法撤销");
                }
            }
        }
        if (ftmsorderbillscars.getOrderStatus() > 30) {
            return AjaxResult.error("该安排车辆已经装卸货，无法撤回");
        }
        ftmsorderbillscars.setBillStatus(3L);
        ftmsorderbillscars.setUpdateTime(new Date());
        ftmsorderbillscars.setUpdateBy(loginUser.getUsername());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscars);
        map.put("plan", ftmsorderbillsplansMapper.selectftmsorderbillsplansById(ftmsorderbillscars.getpId()));
        map.put("cars", ftmsorderbillscars);
        return AjaxResult.success(map);
    }

    /**
     * 单条车辆安排删除
     *
     * @return 结果
     */
    @Transactional
    public AjaxResult vehicleChangeRemove(Ftmsorderbillscars ftmsorderbillscars, LoginUser loginUser) {
        Map<String, Object> map = new HashMap<>();
        // 判断是否卸车
        Ftmsorderbillscars tmsorderbillscars = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(ftmsorderbillscars.getId());
        if (tmsorderbillscars.getBillStatus() == 6) {
            return AjaxResult.error("该安排车辆状态已提交，无法删除");
        }
        if (tmsorderbillscars.getBillStatus() == 7) {
            return AjaxResult.error("该安排车辆状态费用已确认，无法删除");
        }
        if (tmsorderbillscars.getOrderStatus() >= 40) {
            return AjaxResult.error("该安排车辆已经执行卸车操作，无法删除");
        }
        // 若允许删除则删掉后续模块
        BillnoDel billnoDel = new BillnoDel();
        billnoDel.setBillType("SJLSH");
        billnoDel.setBillNo(tmsorderbillscars.getOrderNo());
        billnoDelMapper.insertBillnoDel(billnoDel);
        ftmsorderbillscarsMapper.deleteFollowUpBusinessByCarId(tmsorderbillscars.getId());
        map.put("plan", ftmsorderbillsplansMapper.selectftmsorderbillsplansById(ftmsorderbillscars.getpId()));
        map.put("cars", ftmsorderbillscars);
        return AjaxResult.success(map);
    }

    /**
     * 单条车辆安排变更提交
     *
     * @return 结果
     */
    @Transactional
    public AjaxResult vehicleChangeSubmission(Ftmsorderbillscars ftmsorderbillscars, LoginUser loginUser) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNull(ftmsorderbillscars.getCarcorPid())) {
            return AjaxResult.error("未找到车号信息，请确认");
        }
        // 原车辆安排
        Ftmsorderbillscars tmsorderbillscars = ftmsorderbillscarsMapper.selectftmsorderbillscarsById(ftmsorderbillscars.getId());
        // 调度数据
        Ftmsorderbillsplans ftmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(ftmsorderbillscars.getpId());
        long carQty = ftmsorderbillsplans.getCarQty() - tmsorderbillscars.getCntrQty() + ftmsorderbillscars.getCntrQty();
        if (ftmsorderbillsplans.getCntrQty() < carQty) {
            return AjaxResult.error("派车货量超出调度安排数量，请确认");
        }
        ftmsorderbillsplans.setCarQty(carQty);
        if (ftmsorderbillsplansMapper.updateftmsorderbillsplans(ftmsorderbillsplans) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新调度数据失败，若多次失败请联系管理员");
        }
        Ftmsorderbillscntrs ftmsorderbillscntrs = ftmsorderbillscntrsMapper.selectftmsorderbillscntrsById(ftmsorderbillsplans.getpId());
        ftmsorderbillscntrs.setPlanQty(ftmsorderbillscntrs.getPlanQty() - tmsorderbillscars.getCntrQty() + ftmsorderbillscars.getCntrQty());
        ftmsorderbillscntrsMapper.updateftmsorderbillscntrs(ftmsorderbillscntrs);
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(ftmsorderbillsplans.getOrgId());
        if (StringUtils.isNull(ftmsorderbillscars.getOrderNo())) {
            // 生成流水号
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getSerialNumber("SJLSH", time);
            ftmsorderbillscars.setOrderNo(billNo);
        }
        ftmsorderbillscars.setBillStatus(6L);
        ftmsorderbillscars.setPlanDate(new Date());
        ftmsorderbillscars.setUpdateTime(new Date());
        ftmsorderbillscars.setOrgId(ftmsorderbills.getId());
        ftmsorderbillscars.setMblno(ftmsorderbills.getMblno());
        ftmsorderbillscars.setUpdateBy(loginUser.getUsername());
        ftmsorderbillscars.setCorpId(ftmsorderbills.getCorpId());
        ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscars);
        map.put("plan", ftmsorderbillsplans);
        map.put("cars", ftmsorderbillscarsMapper.selectftmsorderbillscarsById(ftmsorderbillscars.getId()));
        return AjaxResult.success(map);
    }

}
