package com.ruoyi.orderManagement.service.impl;

import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.orderManagement.domain.*;
import com.ruoyi.orderManagement.mapper.*;
import com.ruoyi.orderManagement.service.IftmsorderbillsplansService;
import com.ruoyi.warehouseBusiness.service.impl.BillnoSerialServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 订单调度Service业务层处理
 *
 * @author ruoyi
 * @date 2021-02-22
 */
@Service
public class FtmsorderbillsplansServiceImpl implements IftmsorderbillsplansService {
    @Autowired
    private FtmsorderbillsMapper ftmsorderbillsMapper;

    @Autowired
    private BillnoSerialServiceImpl billnoSerialServiceImpl;

    @Autowired
    private FtmsorderbillscarsMapper ftmsorderbillscarsMapper;

    @Autowired
    private FtmsorderbillscntrsMapper ftmsorderbillscntrsMapper;

    @Autowired
    private FtmsorderbillsplansMapper ftmsorderbillsplansMapper;

    @Autowired
    private ProjectBillsHistoryMapper projectBillsHistoryMapper;

    @Autowired
    private FtmsorderbillsattachsMapper ftmsorderbillsattachsMapper;

    /**
     * 查询订单调度
     *
     * @param id 订单调度ID
     * @return 订单调度
     */
    @Override
    public AjaxResult selectftmsorderbillsplansById(Long id) {
        Map<String, Object> map = new HashMap<>();
        Ftmsorderbillsplans tmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(id);
        if (StringUtils.isNull(tmsorderbillsplans)) {
            return AjaxResult.error("未找到调度信息，请确认");
        }
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(tmsorderbillsplans.getOrgId());
        Ftmsorderbillscars tmsorderbillscars = new Ftmsorderbillscars();
        tmsorderbillscars.setPId(tmsorderbillscars.getId());
        List<Ftmsorderbillscars> tmsorderbillscarsList = ftmsorderbillscarsMapper.selectftmsorderbillscarsList(tmsorderbillscars);
        map.put("tmsorder", ftmsorderbills);
        map.put("plans", tmsorderbillsplans);
        map.put("cars", tmsorderbillscarsList);
        return AjaxResult.success(map);
    }

    /**
     * 查询订单调度列表
     *
     * @param ftmsorderbillsplans 订单调度
     * @return 订单调度
     */
    @Override
    public List<Ftmsorderbillsplans> selectftmsorderbillsplansList(Ftmsorderbillsplans ftmsorderbillsplans) {
        return ftmsorderbillsplansMapper.selectftmsorderbillsplansList(ftmsorderbillsplans);
    }

    /**
     * 新增订单调度
     *
     * @param ftmsorderbillsplans 订单调度
     * @return 结果
     */
    @Override
    public int insertftmsorderbillsplans(Ftmsorderbillsplans ftmsorderbillsplans) {
        ftmsorderbillsplans.setCreateTime(DateUtils.getNowDate());
        return ftmsorderbillsplansMapper.insertftmsorderbillsplans(ftmsorderbillsplans);
    }

    /**
     * 修改订单调度
     *
     * @param ftmsorderbillsplans 订单调度
     * @return 结果
     */
    @Override
    public int updateftmsorderbillsplans(Ftmsorderbillsplans ftmsorderbillsplans) {
        ftmsorderbillsplans.setUpdateTime(DateUtils.getNowDate());
        return ftmsorderbillsplansMapper.updateftmsorderbillsplans(ftmsorderbillsplans);
    }

    /**
     * 批量删除订单调度
     *
     * @param ids 需要删除的订单调度ID
     * @return 结果
     */
    @Override
    public int deleteftmsorderbillsplansByIds(Long[] ids) {
        return ftmsorderbillsplansMapper.deleteftmsorderbillsplansByIds(ids);
    }

    /**
     * 删除订单调度信息
     *
     * @param id 订单调度ID
     * @return 结果
     */
    @Override
    public int deleteftmsorderbillsplansById(Long id) {
        return ftmsorderbillsplansMapper.deleteftmsorderbillsplansById(id);
    }

    /**
     *  单条订单调度提交
     * @param tmsorder  计划表数据
     * @param plans     调度表数据
     * @param loginUser 操作人
     * @return  结果
     */
    @Override
    @Transactional
    public AjaxResult schedulingSave(String tmsorder, String plans, LoginUser loginUser) {
        // 计划数据
        Ftmsorderbills tmsorderbills = JSONArray.parseObject(tmsorder, Ftmsorderbills.class);
        long pId = tmsorderbills.getId();
        // 调拨数据
        Ftmsorderbillsplans tmsorderbillsplans = JSONArray.parseObject(plans, Ftmsorderbillsplans.class);
        // 箱型箱量数据
        Ftmsorderbillscntrs ftmsorderbillscntrs = ftmsorderbillscntrsMapper.selectftmsorderbillscntrsById(tmsorderbillsplans.getPId());
        long qty = ftmsorderbillscntrs.getCntrPlanQty() + tmsorderbillsplans.getCntrQty();
        if (ftmsorderbillscntrs.getCntrBlcQty() < qty) {
            return AjaxResult.error("调度数量超出计划箱量不可提交");
        }
        ftmsorderbillscntrs.setCntrPlanQty(qty);
        if (ftmsorderbillscntrsMapper.updateftmsorderbillscntrs(ftmsorderbillscntrs) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新派车数据失败，若多次失败请联系管理员");
        }
        tmsorderbillsplans.setOrgId(pId);
        tmsorderbillsplans.setBillStatus(6L);
        tmsorderbillsplans.setCreateTime(new Date());
        tmsorderbillsplans.setCreateBy(loginUser.getUsername());
        if (ftmsorderbillsplansMapper.insertftmsorderbillsplans(tmsorderbillsplans) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("新增调度数据失败，若多次失败请联系管理员");
        }
        return AjaxResult.success();
    }

    /**
     *  单条订单调度撤销/删除
     *
     * @param plans     调度表数据
     * @param type      类型
     * @param loginUser 操作人
     * @return  结果
     */
    @Override
    public AjaxResult schedulingRevoke(Ftmsorderbillsplans plans, String type, LoginUser loginUser) {
        long pId = plans.getId();
        Ftmsorderbillsplans ftmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(plans.getId());
        // 查询箱量
        Ftmsorderbillscntrs ftmsorderbillscntrs = ftmsorderbillscntrsMapper.selectftmsorderbillscntrsById(plans.getPId());
        long planQty = ftmsorderbillscntrs.getCntrPlanQty() - plans.getCntrQty();
        ftmsorderbillscntrs.setCntrPlanQty(planQty);
        if (ftmsorderbillscntrsMapper.updateftmsorderbillscntrs(ftmsorderbillscntrs) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新箱量数据失败，若多次出现请联系管理员");
        }
        // 删除操作
        if ("Remove".equals(type)) {
            if (ftmsorderbillsplans.getCarQty() > 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("该调度安排已派车，无法删除");
            }
            if (ftmsorderbillsplansMapper.deleteftmsorderbillsplansById(pId) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("删除订单数据失败，若多次出现请联系管理员");
            }
            return AjaxResult.success();
        }
        String planJson = JSON.toJSONString(ftmsorderbillsplans);
        Date time = new Date();
        // 调度备份流水号
        String billNo = billnoSerialServiceImpl.getSerialNumber("DDBF", time);
        ProjectBillsHistory projectBillsHistory = new ProjectBillsHistory();
        projectBillsHistory.setActId(1010L);
        projectBillsHistory.setProjectId(pId);
        projectBillsHistory.setSerialNumber(billNo);
        projectBillsHistory.setHistoryBody1(planJson);
        projectBillsHistory.setHistoryDate(new Date());
        projectBillsHistory.setHistoryUser(loginUser.getUser().getUserId());
        if (projectBillsHistoryMapper.insertProjectBillsHistory(projectBillsHistory) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新备份数据失败，若多次出现请联系管理员");
        }
        plans.setUpdateTime(new Date());
        plans.setUpdateBy(loginUser.getUsername());
        if (ftmsorderbillsplansMapper.updateftmsorderbillsplans(plans) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新调度数据失败，若多次出现请联系管理员");
        }
        return AjaxResult.success();
    }

    /**
     *  保存订单调度
     * @param tmsorder  主表id
     * @param scntrs    计划货量
     * @param attachs   附件
     * @param plans     调度安排
     * @param loginUser 登录用户
     * @return  结果
     */
    @Override
    @Transactional
    public AjaxResult saveFtmsorderbills(String tmsorder, String scntrs, String attachs, String plans, LoginUser loginUser) {
        Ftmsorderbills tmsorderbills = JSONArray.parseObject(tmsorder, Ftmsorderbills.class);
        long pId = tmsorderbills.getId();
        ftmsorderbillscntrsMapper.deleteftmsorderbillscntrsByPId(pId);
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachsByPId(pId);
        if (StringUtils.isNotNull(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(2L);
                s.setCreateTime(new Date());
                s.setCreateBy(loginUser.getUsername());
                if (ftmsorderbillscntrsMapper.insertftmsorderbillscntrs(s) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新货量数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotNull(attachs) && !"[]".equals(attachs)) {
            JSONArray feesJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(feesJson.toJSONString(), Ftmsorderbillsattachs.class);
            for (Ftmsorderbillsattachs t : tmsorderbillsattachsList) {
                t.setId(null);
                t.setPId(pId);
                t.setOrgId(pId);
                t.setActId(1010L);
                t.setBillStatus(2L);
                t.setCreateBy(loginUser.getUsername());
                t.setCreateTime(new Date());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(t) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     *  提交订单调度
     * @param tmsorder  主表id
     * @param scntrs    计划货量
     * @param attachs   附件
     * @param plans     调度安排
     * @param loginUser 登录用户
     * @return  结果
     */
    @Override
    @Transactional
    public AjaxResult insertftmsorderbills(String tmsorder, String scntrs, String attachs, String plans, LoginUser loginUser) {
        Ftmsorderbills tmsorderbills = JSONArray.parseObject(tmsorder, Ftmsorderbills.class);
        long pId = tmsorderbills.getId();
        ftmsorderbillscntrsMapper.deleteftmsorderbillscntrsByPId(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.isNotNull(attachs) && !"[]".equals(attachs)) {
            JSONArray feesJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(feesJson.toJSONString(), Ftmsorderbillsattachs.class);
            for (Ftmsorderbillsattachs t : tmsorderbillsattachsList) {
                t.setId(null);
                t.setPId(pId);
                t.setOrgId(pId);
                t.setActId(1010L);
                t.setBillStatus(6L);
                t.setCreateBy(loginUser.getUsername());
                t.setCreateTime(new Date());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(t) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        // 调度安排
        /*JSONArray planJson = JSONArray.parseArray(plans);
        List<Ftmsorderbillsplans> tmsorderbillsplansList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillsplans.class);
        for (Ftmsorderbillsplans p : tmsorderbillsplansList) {
            p.setOrgId(pId);
            p.setBillStatus(6L);
            p.setCreateBy(loginUser.getUsername());
            p.setCreateTime(new Date());
            if (ftmsorderbillsplansMapper.insertftmsorderbillsplans(p) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新调度数据失败，若多次失败请联系管理员");
            }
        }*/
        return AjaxResult.success();
    }
}
