package com.ruoyi.orderPlan.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.basicData.domain.FleetCarManage;
import com.ruoyi.basicData.domain.TCorps;
import com.ruoyi.basicData.mapper.FleetCarManageMapper;
import com.ruoyi.basicData.mapper.TCorpsMapper;
import com.ruoyi.common.core.controller.BaseController;
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.LogUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.orderPlan.domain.*;
import com.ruoyi.orderPlan.mapper.*;
import com.ruoyi.orderPlan.service.IftmsorderbillsService;
import com.ruoyi.warehouseBusiness.service.impl.BillnoSerialServiceImpl;
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.util.*;

/**
 * 订单主Service业务层处理
 *
 * @author ruoyi
 * @date 2021-02-22
 */
@Service
public class FtmsorderbillsServiceImpl implements IftmsorderbillsService {

    protected final Logger logger = LoggerFactory.getLogger(FtmsorderbillsServiceImpl.class);

    @Autowired
    private TCorpsMapper tCorpsMapper;

    @Autowired
    private FtmsorderbillsMapper ftmsorderbillsMapper;

    @Autowired
    private FleetCarManageMapper fleetCarManageMapper;

    @Autowired
    private ProjectBillsHistoryMapper billsHistoryMapper;

    @Autowired
    private BillnoSerialServiceImpl billnoSerialServiceImpl;

    @Autowired
    private FtmsorderbillsfeesMapper ftmsorderbillsfeesMapper;

    @Autowired
    private FtmsorderbillscarsMapper ftmsorderbillscarsMapper;

    @Autowired
    private FtmsorderbillsplansMapper ftmsorderbillsplansMapper;

    @Autowired
    private FtmsorderbillscntrsMapper ftmsorderbillscntrsMapper;

    @Autowired
    private FtmsorderbillsattachsMapper ftmsorderbillsattachsMapper;

    /**
     *  查询首页数据
     * @return  结果
     */
    @Override
    public AjaxResult queryHomeInfo() {
        Map<String, Object> map = new HashMap<>();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Ftmsorderbills ftmsorderbills = new Ftmsorderbills();
        if ("22".equals(user.getUserType())) {
            ftmsorderbills.setIsFleet("1");
            TCorps corps = tCorpsMapper.selectTCorpsByFTel(user.getPhonenumber());
            ftmsorderbills.setFleetId(corps.getfId());
        }
        //  查询右上 所有已结单、未结单数据
        map.put("upperRight", ftmsorderbillscarsMapper.selectHomeUpperRightMapList(ftmsorderbills));
        // 查询右下 提醒数据
        map.put("lowerRight", null);
        // 查询左上
        List<String> currentDay = DateUtils.getCurrentDay();
        ftmsorderbills.setcurrentDay(currentDay);
        map.put("upperLeftCntrs", ftmsorderbillscarsMapper.selectHomeUpperLeftCntrs(ftmsorderbills));
        // 今日派车数量
        int carQuantity = ftmsorderbillscarsMapper.selectHomeUpperLeftCars(ftmsorderbills);
        map.put("upperLeftCarQuantity", carQuantity);
        FleetCarManage fleetCarManage = new FleetCarManage();
        fleetCarManage.setDelFlag("0");
        fleetCarManage.setBillStatus(6L);
        //可用派车数量（总车辆-已派出的车辆）
        int carManageQuantity = fleetCarManageMapper.selectManageCount(ftmsorderbills);
        int carNumber = carManageQuantity - carQuantity;
        if (carNumber < 0) {
            carNumber = 0;
        }
        map.put("upperLeftOldCarQuantity", carNumber);
        // 查询左下
        map.put("lowerLeft", ftmsorderbillscarsMapper.selectHomeUpperRightMapList(ftmsorderbills));
        //新增柜数 就是 计划货量总和 F_TMSORDERBILLSCNTRS
        //未安排柜数 = 计划货量总和 - 已调度货量F_TMSORDERBILLSPLANS
        Integer scntrsManageQuantity = ftmsorderbillscntrsMapper.selectftmsorderbillscntrs();
        if (scntrsManageQuantity == null || scntrsManageQuantity <= 0){
            return AjaxResult.error("今日没有新增柜数");
        }
//        //已调度货量
        Integer scnNumber = ftmsorderbillsplansMapper.selectManagCout();
//        //未安排柜数 --自动拆箱
        int sanNoNumber = scntrsManageQuantity - scnNumber;
        if (sanNoNumber < 0){
            sanNoNumber = 0;
        }
        map.put("manageQuantity",scntrsManageQuantity);
        map.put("scnNumber",scnNumber);
        map.put("sanNuNomber",sanNoNumber);
        return AjaxResult.success(map);
    }

    /**
     * 查询订单主
     *
     * @param id       订单主ID
     * @param billType 状态
     * @return 订单主
     */
    @Override
    public Map<String, Object> selectftmsorderbillsById(Long id, Long billType) {
        Map<String, Object> map = new HashMap<>();
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(id);
        map.put("tmsorder", ftmsorderbills);
        // 查询计划货量
        Ftmsorderbillscntrs ftmsorderbillscntrs = new Ftmsorderbillscntrs();
        ftmsorderbillscntrs.setPId(id);
        map.put("scntrs", ftmsorderbillscntrsMapper.selectftmsorderbillscntrsList(ftmsorderbillscntrs));
        // 查询调度安排明细
        Ftmsorderbillsplans ftmsorderbillsplans = new Ftmsorderbillsplans();
        ftmsorderbillsplans.setOrgId(id);
        map.put("plans", ftmsorderbillsplansMapper.selectftmsorderbillsplansList(ftmsorderbillsplans));
        // 查询调度安排附件
        Ftmsorderbillsattachs ftmsorderbillsattachs = new Ftmsorderbillsattachs();
        ftmsorderbillsattachs.setPId(id);
        ftmsorderbillsattachs.setActId(billType);
        map.put("attach", ftmsorderbillsattachsMapper.selectftmsorderbillsattachsList(ftmsorderbillsattachs));
        // 查询费用明细
        Ftmsorderbillsfees ftmsorderbillsfees = new Ftmsorderbillsfees();
        ftmsorderbillsfees.setfPid(id);
        ftmsorderbillsfees.setActId(billType);
        map.put("fees", ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesList(ftmsorderbillsfees));
        return map;
    }

    /**
     * 查询订单主列表
     *
     * @param ftmsorderbills 订单主
     * @return 订单主
     */
    @Override
    public List<Ftmsorderbills> selectftmsorderbillsList(Ftmsorderbills ftmsorderbills) {
        return ftmsorderbillsMapper.selectftmsorderbillsList(ftmsorderbills);
    }

    @Transactional
    public AjaxResult updateItem(long pId, long itemstatus, String scntrs, String attachs, String fees, String plans, LoginUser loginUser) {
        if (Objects.equals(itemstatus, 6)) {
            String status = dataValidation(scntrs, attachs, fees, plans, null);
            if (StringUtils.isNotEmpty(status)) {
                return AjaxResult.error(status);
            }
        }
        if (StringUtils.isNotEmpty(scntrs) && !"[]".equals(scntrs)) {
            JSONArray scntrsJson = JSONArray.parseArray(scntrs);
            List<Ftmsorderbillscntrs> tmsorderbillscntrsList = JSONObject.parseArray(scntrsJson.toJSONString(), Ftmsorderbillscntrs.class);
            for (Ftmsorderbillscntrs s : tmsorderbillscntrsList) {
                s.setPId(pId);
                s.setOrgId(pId);
                s.setBillStatus(itemstatus);
                s.setCreateBy(loginUser.getUsername());
                s.setCreateTime(new Date());
                if (ftmsorderbillscntrsMapper.insertftmsorderbillscntrs(s) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新货量数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            JSONArray feesJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(feesJson.toJSONString(), Ftmsorderbillsattachs.class);
            for (Ftmsorderbillsattachs t : tmsorderbillsattachsList) {
                t.setPId(pId);
                t.setOrgId(pId);
                t.setActId(1000L);
                t.setBillStatus(itemstatus);
                t.setCreateBy(loginUser.getUsername());
                t.setCreateTime(new Date());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(t) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotEmpty(fees) && !"[]".equals(fees)) {
            JSONArray feesJson = JSONArray.parseArray(fees);
            List<Ftmsorderbillsfees> tmsorderbillsfeesList = JSONObject.parseArray(feesJson.toJSONString(), Ftmsorderbillsfees.class);
            for (Ftmsorderbillsfees f : tmsorderbillsfeesList) {
                f.setfPid(pId);
                f.setOrgId(pId);
                f.setActId(1000L);
                f.setfStatus(itemstatus);
                f.setCreateTime(new Date());
                f.setCreateBy(loginUser.getUsername());
                if (ftmsorderbillsfeesMapper.insertFTmsorderbillsfees(f) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新费用数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotEmpty(plans) && !"[]".equals(plans)) {
            JSONArray planJson = JSONArray.parseArray(plans);
            List<Ftmsorderbillsplans> tmsorderbillsplansList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillsplans.class);
            int line = 0;
            for (Ftmsorderbillsplans p : tmsorderbillsplansList) {
                line++;
                p.setOrgId(pId);
                if (StringUtils.isNull(p.getBillStatus())) {
                    p.setBillStatus(itemstatus);
                }
                p.setCreateTime(new Date());
                p.setCreateBy(loginUser.getUsername());
                if (ftmsorderbillsplansMapper.insertftmsorderbillsplans(p) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新调度数据失败，若多次失败请联系管理员");
                }
                if (Objects.equals(itemstatus, 6)) {
                    Ftmsorderbillscntrs ftmsorderbillscntrs = ftmsorderbillscntrsMapper.selectftmsorderbillscntrsById(p.getpId());
                    long qty = ftmsorderbillscntrs.getCntrPlanQty() + p.getCntrQty();
                    if (qty > ftmsorderbillscntrs.getCntrQty()) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("业务调度第" + line + "行调度数量超出计划箱量");
                    }
                    if (ftmsorderbillscntrsMapper.updateTmsorderbillScntrsQty(p) <= 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("更新派车数据失败，若多次失败请联系管理员");
                    }
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 提交计划下单
     *
     * @param tmsorder  主表
     * @param scntrs    明细
     * @param fees      费用表
     * @param plans     调度表
     * @param loginUser 用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertftmsorderbills(String tmsorder, String scntrs, String attachs, String fees, String plans, LoginUser loginUser) {
        Map<String, Object> map = new HashMap<>();
        long pId = 0L;
        Ftmsorderbills tmsorderbills = JSONArray.parseObject(tmsorder, Ftmsorderbills.class);
        if (StringUtils.isNull(tmsorderbills.getBillStatus())) {
            return AjaxResult.error("未找到单据状态，请确认");
        }
        if (tmsorderbills.getBillStatus() == 6L) {
            if (StringUtils.isNull(scntrs) || "[]".equals(scntrs)) {
                return AjaxResult.error("未找到计划货量数据，请确认");
            }
            tmsorderbills.setPostDate(new Date());
            String status = dataValidation(scntrs, attachs, fees, plans, null);
            if (StringUtils.isNotEmpty(status)) {
                return AjaxResult.error(status);
            }
            if (StringUtils.isNotEmpty(plans) && !"[]".equals(plans)) {
                tmsorderbills.setPlanUserId(loginUser.getUser().getUserId());
                tmsorderbills.setPlanUserName(loginUser.getUser().getNickName());
            }
        }
        tmsorderbills.setActId(1000L);
        if (StringUtils.isEmpty(tmsorderbills.getBillNo())) {
            // 生成流水号
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getSerialNumber("JH", time);
            tmsorderbills.setBillNo(billNo);
        }
        if (StringUtils.isNull(tmsorderbills.getId())) {
            // 代表新建单据直接提交
            tmsorderbills.setCreateTime(new Date());
            tmsorderbills.setCreateBy(loginUser.getUsername());
            if (ftmsorderbillsMapper.insertftmsorderbills(tmsorderbills) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新计划数据失败，若多次失败请联系管理员");
            }
            pId = tmsorderbills.getId();
        } else {
            // 代表保存过在提交
            pId = tmsorderbills.getId();
            tmsorderbills.setUpdateTime(new Date());
            tmsorderbills.setUpdateBy(loginUser.getUsername());
            if (ftmsorderbillsMapper.updateftmsorderbills(tmsorderbills) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新计划数据失败，若多次失败请联系管理员");
            }
        }
        map.put("tmsorder", tmsorderbills);
        ftmsorderbillsfeesMapper.deleteFTmsorderbillsfeesByPId(pId);
        ftmsorderbillscntrsMapper.deleteftmsorderbillscntrsByPId(pId);
        ftmsorderbillsplansMapper.deleteftmsorderbillsplansByOrgId(pId);
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachsByPId(pId);
        AjaxResult ajaxResult = updateItem(pId, tmsorderbills.getBillStatus(), scntrs, attachs, fees, plans, loginUser);
        String code = ajaxResult.get("code").toString();
        if ("500".equals(code)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ajaxResult;
        }
        map.put("fees", ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesByPId(pId));
        map.put("plans", ftmsorderbillsplansMapper.selectftmsorderbillsplansByOrgId(pId));
        map.put("scntrs", ftmsorderbillscntrsMapper.selectftmsorderbillscntrsByPId(pId));

        //新增保存后逻辑 20210707 dongyongwei
        //1计划中 状态
        setFtmsorderbillsBillStatus(pId,1L);

        return AjaxResult.success(map);
    }

    /**
     * 修改订单主
     *
     * @param ftmsorderbills 订单主
     * @return 结果
     */
    @Override
    public int updateftmsorderbills(Ftmsorderbills ftmsorderbills) {
        ftmsorderbills.setUpdateTime(DateUtils.getNowDate());
        return ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
    }

    /**
     * 批量删除订单主
     *
     * @param ids 需要删除的订单主ID
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteftmsorderbillsByIds(Long[] ids) {
        int line = 0;
        for (Long l : ids) {
            line++;
            Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(l);
            if (ftmsorderbills.getBillStatus() > 6) {
                return AjaxResult.error("所选数据第" + line + "条数据状态已操作调度不允许删除");
            }
            ftmsorderbillsMapper.deleteftmsorderbillsById(l);
            ftmsorderbillscntrsMapper.deleteftmsorderbillscntrsByPId(l);
            ftmsorderbillsplansMapper.deleteftmsorderbillsplansByPId(l);
        }
        return AjaxResult.success();
    }

    /**
     * 删除订单主信息
     *
     * @param id 订单主ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteftmsorderbillsById(Long id) {
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(id);
        if (ftmsorderbills.getBillStatus() > 6) {
            return 0;
        }
        ftmsorderbillsMapper.deleteftmsorderbillsById(id);
        ftmsorderbillscntrsMapper.deleteftmsorderbillscntrsByPId(id);
        ftmsorderbillsplansMapper.deleteftmsorderbillsplansByPId(id);
        return 1;
    }

    /**
     * 判断是否允许变更
     *
     * @param ftmsorderbills 计划下达信息
     * @return 结果
     */
    @Override
    public AjaxResult planStatusChange(Ftmsorderbills ftmsorderbills) {
        Ftmsorderbills tmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(ftmsorderbills.getId());
        boolean billStatus = false;
        if (ftmsorderbills.getActId() == 1000) {
            // 计划变更
            billStatus = true;
        }
        if (billStatus && tmsorderbills.getBillStatus() == 3L) {
            return AjaxResult.error("计划单据已撤销无法变更");
        } else if (billStatus && tmsorderbills.getBillStatus() < 6L) {
            return AjaxResult.error("计划单据未提交无法变更");
        }
        if (!billStatus && tmsorderbills.getBillStatus() == 30L) {
            return AjaxResult.error("调度单据已被撤销无法变更");
        } else if (!billStatus && tmsorderbills.getBillStatus() < 60L) {
            return AjaxResult.error("调度单据未提交无法变更");
        }
        return AjaxResult.success();
    }

    /**
     * 计划下达变更提交
     *
     * @param tmsorder  计划
     * @param scntrs    箱型箱量
     * @param attachs   附件
     * @param fees      费用
     * @param plans     调度
     * @param loginUser 用户
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertPlanChange(String tmsorder, String scntrs, String attachs, String fees, String plans, LoginUser loginUser) {
        Ftmsorderbills tmsorderbills = JSONArray.parseObject(tmsorder, Ftmsorderbills.class);
        long pId = tmsorderbills.getId();
        tmsorderbills.setBillStatus(6L);
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(tmsorderbills.getId());
        ProjectBillsHistory projectBillsHistory = new ProjectBillsHistory();
        projectBillsHistory.setProjectId(pId);
        projectBillsHistory.setActId(1100L);
        // 计划变更流水号
        Date time = new Date();
        projectBillsHistory.setSerialNumber(billnoSerialServiceImpl.getSerialNumber("JHBGBF", time));
        projectBillsHistory.setHistoryDate(new Date());
        projectBillsHistory.setHistoryUser(loginUser.getUser().getUserId());
        String billsJson = JSON.toJSONString(ftmsorderbills);
        projectBillsHistory.setHistoryBody1(billsJson);
        if (billsHistoryMapper.insertProjectBillsHistory(projectBillsHistory) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新备份信息失败，若多次出现请联系管理员");
        }
        ftmsorderbillsfeesMapper.deleteFTmsorderbillsfeesByPId(pId);
        ftmsorderbillscntrsMapper.deleteftmsorderbillscntrsByPId(pId);
        ftmsorderbillsplansMapper.deleteftmsorderbillsplansByOrgId(pId);
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachsByPId(pId);
        // 箱型箱量
        JSONArray scntrsJson = JSONArray.parseArray(scntrs);
        List<Ftmsorderbillscntrs> tmsorderbillscntrsList = JSONObject.parseArray(scntrsJson.toJSONString(), Ftmsorderbillscntrs.class);
        for (Ftmsorderbillscntrs s : tmsorderbillscntrsList) {
            s.setPId(pId);
            s.setOrgId(pId);
            s.setBillStatus(6L);
            s.setCreateTime(new Date());
            s.setCreateBy(loginUser.getUsername());
            if (ftmsorderbillscntrsMapper.insertftmsorderbillscntrs(s) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新货量数据失败，若多次失败请联系管理员");
            }
        }
        if (StringUtils.isNotEmpty(plans) && !"{}".equals(plans)) {
            JSONArray planJson = JSONArray.parseArray(plans);
            List<Ftmsorderbillsplans> tmsorderbillsplansList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillsplans.class);
            int line = 0;
            boolean status = false;
            for (Ftmsorderbillsplans p : tmsorderbillsplansList) {
                line++;
                for (Ftmsorderbillscntrs cntr : tmsorderbillscntrsList) {
                    if (p.getCntrId().equals(cntr.getCntrId())) {
                        status = true;
                        break;
                    }
                }
                if (!status) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("调拨第" + line + "行箱型箱量异常");
                }
            }
            tmsorderbills.setPlanUserId(loginUser.getUser().getUserId());
            tmsorderbills.setPlanUserName(loginUser.getUser().getNickName());
        }
        AjaxResult ajaxResult = updateItem(pId, 6, null, attachs, fees, plans, loginUser);
        String ajaxCode = ajaxResult.get("code").toString();
        if ("500".equals(ajaxCode)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ajaxResult;
        }
        tmsorderbills.setUpdateTime(new Date());
        tmsorderbills.setUpdateBy(loginUser.getUsername());
        if (ftmsorderbillsMapper.updateftmsorderbills(tmsorderbills) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新计划失败，若多次出现请联系管理员");
        }
        return AjaxResult.success();
    }

    /**
     * 验证数组数据是否存在必填项未填写
     *
     * @param scntrs  货量
     * @param attachs 附件
     * @param fees    费用
     * @param plans   调度
     * @param cars    派车
     * @return 结果
     */
    public String dataValidation(String scntrs, String attachs, String fees, String plans, String cars) {
        //  判断计划货量是否符合
        if (StringUtils.isNotEmpty(scntrs) && !"[]".equals(scntrs)) {
            JSONArray scntrsJson = JSONArray.parseArray(scntrs);
            List<Ftmsorderbillscntrs> tmsorderbillscntrsList = JSONObject.parseArray(scntrsJson.toJSONString(), Ftmsorderbillscntrs.class);
            int line = 0;
            for (Ftmsorderbillscntrs s : tmsorderbillscntrsList) {
                line++;
                if (StringUtils.isNull(s.getCntrId())) {
                    return "计划货量第" + line + "行未找到箱型数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(s.getPriceType())) {
                    return "计划货量第" + line + "行未找到计价方式数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(s.getCntrQty())) {
                    return "计划货量第" + line + "行未找到计划货量数据，若多次失败请联系管理员";
                }
            }
        }
        //  判断附件是否符合
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            JSONArray attachJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(attachJson.toJSONString(), Ftmsorderbillsattachs.class);
            int line = 0;
            for (Ftmsorderbillsattachs s : tmsorderbillsattachsList) {
                line++;
                if (StringUtils.isEmpty(s.getAttachUrl())) {
                    return "附件第" + line + "行未找到附件路径数据，若多次失败请联系管理员";
                }
            }
        }
        //  判断费用是否符合
        if (StringUtils.isNotEmpty(fees) && !"[]".equals(fees)) {
            JSONArray feesJson = JSONArray.parseArray(fees);
            List<Ftmsorderbillsfees> tmsorderbillsfeesList = JSONObject.parseArray(feesJson.toJSONString(), Ftmsorderbillsfees.class);
            int line = 0;
            for (Ftmsorderbillsfees f : tmsorderbillsfeesList) {
                line++;
                if (StringUtils.isNull(f.getfCorpid())) {
                    return "费用信息第" + line + "行未找到结算单位数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(f.getfFeeid())) {
                    return "费用信息第" + line + "行未找到费用数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(f.getfFeeunitid())) {
                    return "费用信息第" + line + "行未找到计费单位数据，若多次失败请联系管理员";
                }
            }
        }
        //  判断调度是否符合
        if (StringUtils.isNotEmpty(plans) && !"[]".equals(plans)) {
            JSONArray planJson = JSONArray.parseArray(plans);
            List<Ftmsorderbillsplans> tmsorderbillsplansList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillsplans.class);
            int line = 0;
            for (Ftmsorderbillsplans p : tmsorderbillsplansList) {
                line++;
                if (StringUtils.isNull(p.getCntrId())) {
                    return "调度安排第" + line + "行未找到箱型数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(p.getCarcorPid())) {
                    return "调度安排第" + line + "行未找到车队数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(p.getCntrQty())) {
                    return "调度安排第" + line + "行未找到调度安排货量数据，若多次失败请联系管理员";
                }
            }
        }
        //  判断派车是否符合
        if (StringUtils.isNotEmpty(cars) && !"[]".equals(cars)) {
            JSONArray carsJson = JSONArray.parseArray(cars);
            List<Ftmsorderbillscars> tmsorderbillscarsList = JSONObject.parseArray(carsJson.toJSONString(), Ftmsorderbillscars.class);
            int line = 0;
            for (Ftmsorderbillscars c : tmsorderbillscarsList) {
                line++;
                if (StringUtils.isNull(c.getCntrId())) {
                    return "派车第" + line + "行未找到箱型数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(c.getCarcorPid())) {
                    return "派车第" + line + "行未找到箱型数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(c.getCntrQty())) {
                    return "派车第" + line + "行未找到货量数据，若多次失败请联系管理员";
                } else if (StringUtils.isNull(c.getCarregNo())) {
                    return "派车第" + line + "行未找到车号数据，若多次失败请联系管理员";
                } else if (StringUtils.isEmpty(c.getDriverName())) {
                    return "派车第" + line + "行未找到司机姓名数据，若多次失败请联系管理员";
                } else if (StringUtils.isEmpty(c.getDriverTel())) {
                    return "派车第" + line + "行未找到联系电话数据，若多次失败请联系管理员";
                }
            }
        }
        return null;
    }

    /**
     * 验证对象数据是否存在必填项未填写
     *
     * @param scntrs  货量
     * @param attachs 附件
     * @param fees    费用
     * @param plans   调度
     * @param cars    派车
     * @return 结果
     */
    public String objValidation(String scntrs, String attachs, String fees, String plans, String cars) {
        //  判断计划货量是否符合
        if (StringUtils.isNotEmpty(scntrs) && !"{}".equals(scntrs)) {
            Ftmsorderbillscntrs s = JSONArray.parseObject(scntrs, Ftmsorderbillscntrs.class);
            if (StringUtils.isNull(s.getCntrId())) {
                return "计划货量未找到箱型数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(s.getPriceType())) {
                return "计划货量未找到计价方式数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(s.getCntrQty())) {
                return "计划货量未找到计划货量数据，若多次失败请联系管理员";
            }
        }
        //  判断附件是否符合
        if (StringUtils.isNotEmpty(attachs) && !"{}".equals(attachs)) {
            Ftmsorderbillsattachs a = JSONArray.parseObject(attachs, Ftmsorderbillsattachs.class);
            if (StringUtils.isEmpty(a.getAttachUrl())) {
                return "附件未找到附件路径数据，若多次失败请联系管理员";
            }
        }
        //  判断费用是否符合
        if (StringUtils.isNotEmpty(fees) && !"{}".equals(fees)) {
            Ftmsorderbillsfees f = JSONArray.parseObject(fees, Ftmsorderbillsfees.class);
            if (StringUtils.isNull(f.getfCorpid())) {
                return "费用信息未找到结算单位数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(f.getfFeeid())) {
                return "费用信息行未找到费用数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(f.getfFeeunitid())) {
                return "费用信息未找到计费单位数据，若多次失败请联系管理员";
            }
        }
        //  判断调度是否符合
        if (StringUtils.isNotEmpty(plans) && !"{}".equals(plans)) {
            Ftmsorderbillsplans p = JSONArray.parseObject(plans, Ftmsorderbillsplans.class);
            if (StringUtils.isNull(p.getCntrId())) {
                return "调度安排未找到箱型数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(p.getCarcorPid())) {
                return "调度安排未找到车队数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(p.getCntrQty())) {
                return "调度安排未找到调度安排货量数据，若多次失败请联系管理员";
            }
        }
        //  判断派车是否符合
        if (StringUtils.isNotEmpty(cars) && !"{}".equals(cars)) {
            Ftmsorderbillscars c = JSONArray.parseObject(cars, Ftmsorderbillscars.class);
            if (StringUtils.isNull(c.getCntrId())) {
                return "派车未找到箱型数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(c.getCarcorPid())) {
                return "派车未找到车队数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(c.getCntrQty())) {
                return "派车未找到货量数据，若多次失败请联系管理员";
            } else if (StringUtils.isNull(c.getCarregNo())) {
                return "派车未找到车号数据，若多次失败请联系管理员";
            } else if (StringUtils.isEmpty(c.getDriverName())) {
                return "派车未找到司机姓名数据，若多次失败请联系管理员";
            } else if (StringUtils.isEmpty(c.getDriverTel())) {
                return "派车未找到联系电话数据，若多次失败请联系管理员";
            }
        }
        return null;
    }

    /**
     * 计划操作撤回
     *
     * @param ftmsorderbills 计划数据
     * @param loginUser      登陆人
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult planCancel(Ftmsorderbills ftmsorderbills, LoginUser loginUser) {
        Ftmsorderbills sorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(ftmsorderbills.getId());
        boolean billsStatus = false;
        if (sorderbills.getActId() == 1000) {
            // 计划下达
            billsStatus = true;
        }
        if (billsStatus && sorderbills.getBillStatus() == 3L) {
            return AjaxResult.error("该数据计划已撤销");
        } else if (!billsStatus && sorderbills.getBillStatus() == 30L) {
            return AjaxResult.error("该数据调度已撤销");
        }
        if (billsStatus && sorderbills.getBillStatus() < 6L) {
            return AjaxResult.error("该计划未提交，不可撤销");
        } else if (!billsStatus && sorderbills.getBillStatus() < 60L) {
            return AjaxResult.error("该调度未提交，不可撤销");
        }
        Ftmsorderbillsplans tmsorderbillsplans = new Ftmsorderbillsplans();
        tmsorderbillsplans.setOrgId(sorderbills.getId());
        if (ftmsorderbillsplansMapper.selectftmsorderbillsplansCountList(tmsorderbillsplans) > 0) {
            return AjaxResult.error("该计划已进行调度安排，不可撤销");
        }
        if (billsStatus) {
            ftmsorderbills.setBillStatus(3L);
        } else {
            ftmsorderbills.setBillStatus(30L);
        }
        if (ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("计划变更失败，若多次出现请联系管理员");
        }
        // 计划下达撤销，修改后续派车模块状态
        Ftmsorderbillsplans ftmsorderbillsplans = new Ftmsorderbillsplans();
        ftmsorderbillsplans.setOrgId(ftmsorderbills.getId());
        ftmsorderbillsplans.setBillStatus(3L);
        ftmsorderbillsplansMapper.updateTmsorderSplanStatusByOrgId(ftmsorderbillsplans);
        // 计划下达撤销，修改后续计划箱量模块状态
        Ftmsorderbillscntrs ftmsorderbillscntrs = new Ftmsorderbillscntrs();
        ftmsorderbillscntrs.setOrgId(ftmsorderbills.getId());
        ftmsorderbillscntrs.setBillStatus(3L);
        ftmsorderbillscntrsMapper.updateTmsorderCntrStatusByOrgId(ftmsorderbillscntrs);
        // 计划下达撤销，修改后续计划箱量模块状态
        Ftmsorderbillscars ftmsorderbillscars = new Ftmsorderbillscars();
        ftmsorderbillscars.setOrgId(ftmsorderbills.getId());
        ftmsorderbillscars.setBillStatus(3L);
        ftmsorderbillscarsMapper.updateTmsorderCarStatusByOrgId(ftmsorderbillscntrs);
        return AjaxResult.success();
    }

    /**
     * 列表页查询条件
     *
     * @param ftmsorderbills 查询条件
     * @return 结果
     */
    @Override
    public List<Map<String, Object>> selectftmsorderbillsMapList(Ftmsorderbills ftmsorderbills) {
        return ftmsorderbillsMapper.selectftmsorderbillsMapList(ftmsorderbills);
    }

    /**
     * 设置订单表的状态方法
     *
     * @param id         订单主表ID
     * @param billStatus 数据字典订单状态值
     * @since 20210707 dongyongwei
     */
    @Override
    public void setFtmsorderbillsBillStatus(Long id, Long billStatus) {

        logger.debug("setFtmsorderbillsBillStatus,id={},billStatus={}",id,billStatus);

        /*
        业务逻辑:
        1计划中 录入单据 
        2待调度 点击提交计划  
        3调度中 计划量和调度量比较 计划量大于0 调度量<>0  计划量>调度量
        4待派车 计划量和调度量比较 计划量大于0 计划量=调度量
        5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
        6待回单 调度量和派车量比较 调度量大于0 调度量=派车
        7回单中 派车量和回单量比较 派车量大于0 回单量<>0   派车量>回单量 
        8回单完成 派车量和回单量比较 派车量大于0 派车量=回单量
        */
        //获取正在操作的订单信息
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(id);

        if("1".equals(String.valueOf(billStatus))){
            logger.debug("更新状态码为:{}",1);
           //保存按钮下新增记录,1计划中
            ftmsorderbills.setBillStatus(billStatus);
            ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
        }

        if("2".equals(String.valueOf(billStatus))){
            logger.debug("更新状态码为:{}",2);
            //保存按钮下新增记录,2待调度
            ftmsorderbills.setBillStatus(billStatus);
            ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
        }

        if("3".equals(String.valueOf(billStatus))){
            //3调度中 计划量和调度量比较 计划量大于0 调度量<>0  计划量>调度量
            //4待派车 计划量和调度量比较 计划量大于0 计划量=调度量
            //取订单对应的F_TMSORDERBILLSCNTRS表数据
            List<Ftmsorderbillscntrs> listFtmsorderbillscntrs = ftmsorderbillscntrsMapper.selectftmsorderbillscntrsByPId(id);
            if(listFtmsorderbillscntrs.size()>0){
                //判断>0证明有数据,取出来写相应逻辑
                Ftmsorderbillscntrs ftmsorderbillscntrs = listFtmsorderbillscntrs.get(0);
                //1获取计划量
                Long cntrQty = ftmsorderbillscntrs.getCntrQty();
                //2获取调度量
                Long cntrPlanQty = ftmsorderbillscntrs.getCntrPlanQty();
                //3获取未安排调度量
                Long cntrBlcQty = ftmsorderbillscntrs.getCntrBlcQty();

                if(cntrQty >0 && cntrPlanQty!=0 && cntrQty>cntrPlanQty){
                    logger.debug("更新状态码为:{}",3);
                    ftmsorderbills.setBillStatus(3L);
                    ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
                }
                if(cntrQty >0 && cntrQty==cntrPlanQty){
                    logger.debug("更新状态码为:{}",4);
                    ftmsorderbills.setBillStatus(4L);
                    ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
                }
            }

        }

        if("5".equals(String.valueOf(billStatus))){
            //派车环节加入判断
            //5派车中 调度量和派车量比较 调度量大于0 派车<>0   调度量>派车
            //6待回单 调度量和派车量比较 调度量大于0 调度量=派车
            //取订单对应的F_TMSORDERBILLSCNTRS表数据
            List<Ftmsorderbillscntrs> listFtmsorderbillscntrs = ftmsorderbillscntrsMapper.selectftmsorderbillscntrsByPId(id);
            if(listFtmsorderbillscntrs.size()>0){
                //判断>0证明有数据,取出来写相应逻辑
                Ftmsorderbillscntrs ftmsorderbillscntrs = listFtmsorderbillscntrs.get(0);
                //取调度量
                Long cntrPlanQty = ftmsorderbillscntrs.getCntrPlanQty();
                //取派车量
                Long planQty = ftmsorderbillscntrs.getPlanQty();
                if(cntrPlanQty>0 && planQty !=0 && cntrPlanQty > planQty){
                    logger.debug("更新状态码为:{}",5);
                    ftmsorderbills.setBillStatus(5L);
                    ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
                }
                if(cntrPlanQty>0 && cntrPlanQty == planQty){
                    logger.debug("更新状态码为:{}",6);
                    ftmsorderbills.setBillStatus(6L);
                    ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
                }

            }

        }

        if("7".equals(String.valueOf(billStatus))){
            //7回单中 派车量和回单量比较 派车量大于0 回单量<>0   派车量>回单量 
            //8回单完成 派车量和回单量比较 派车量大于0 派车量=回单量
            //取订单对应的F_TMSORDERBILLSCNTRS表数据
            List<Ftmsorderbillscntrs> listFtmsorderbillscntrs = ftmsorderbillscntrsMapper.selectftmsorderbillscntrsByPId(id);
            if(listFtmsorderbillscntrs.size()>0){
                //判断>0证明有数据,取出来写相应逻辑
                Ftmsorderbillscntrs ftmsorderbillscntrs = listFtmsorderbillscntrs.get(0);
                //取派车量
                Long planQty = ftmsorderbillscntrs.getPlanQty();
                //取回单量
                Ftmsorderbillscars ftmsorderbillscarsQuery = new Ftmsorderbillscars();
                ftmsorderbillscarsQuery.setOrgId(id);
                ftmsorderbillscarsQuery.setOrderStatus(80L);
                List<Ftmsorderbillscars> ftmsorderbillscarsList = ftmsorderbillscarsMapper.selectftmsorderbillscarsList(ftmsorderbillscarsQuery);
                //回单量
                Long carByOrderStatus80 = 0L;
                if(ftmsorderbillscarsList.size()>0){
                    for (int i = 0; i < ftmsorderbillscarsList.size(); i++) {
                        carByOrderStatus80 = carByOrderStatus80 +ftmsorderbillscarsList.get(i).getCntrQty();
                    }
                }

                logger.debug("派车量:{},回单量:{}",planQty,carByOrderStatus80);

                if(planQty >0 && carByOrderStatus80 !=0 && planQty>carByOrderStatus80){
                    logger.debug("更新状态码为:{}",7);
                    ftmsorderbills.setBillStatus(7L);
                    ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
                }
                if(planQty >0 && planQty==carByOrderStatus80){
                    logger.debug("更新状态码为:{}",8);
                    ftmsorderbills.setBillStatus(8L);
                    ftmsorderbillsMapper.updateftmsorderbills(ftmsorderbills);
                }
            }
        }

    }

}
