package com.ruoyi.orderManagement.service.impl;

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

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.finance.domain.TFeeDo;
import com.ruoyi.finance.mapper.TFeeDoMapper;
import com.ruoyi.orderManagement.domain.*;
import com.ruoyi.orderManagement.mapper.*;
import com.ruoyi.orderManagement.service.IftmsorderbillscarsService;
import com.ruoyi.orderManagement.statusTracking.domain.Ftmsorderbillsfees;
import com.ruoyi.orderManagement.statusTracking.mapper.FtmsorderbillsfeesMapper;
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 FtmsorderbillscarsServiceImpl implements IftmsorderbillscarsService {
    @Autowired
    private TFeeDoMapper tFeeDoMapper;

    @Autowired
    private FtmsorderbillsMapper ftmsorderbillsMapper;

    @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);
        return map;
    }

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

    /**
     * 保存车队派车
     *
     * @param tmsorder  主表id
     * @param attachs   附件表
     * @param fees      费用表
     * @param cars      车俩安排表
     * @param loginUser 操作人
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult saveftmsorderbillscars(String tmsorder, String attachs, String fees, String cars, LoginUser loginUser) {
        Ftmsorderbills tmsorderbills = JSONArray.parseObject(tmsorder, Ftmsorderbills.class);
        long pId = tmsorderbills.getId();
        ftmsorderbillscarsMapper.deleteftmsorderbillscarsByPId(pId);
        ftmsorderbillsfeesMapper.deleteFTmsorderbillsfeesByPId(pId);
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachsByPId(pId);
        if (StringUtils.isNotNull(cars) && !"[]".equals(cars)) {
            JSONArray planJson = JSONArray.parseArray(cars);
            List<Ftmsorderbillscars> tmsorderbillscarsList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillscars.class);
            int line = 0;
            for (Ftmsorderbillscars s : tmsorderbillscarsList) {
                if (StringUtils.isNull(s.getPId())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("车辆安排数据第" + line + "行数据未找到箱型id，请确认");
                }
                s.setOrgId(pId);
                s.setOrderStatus(0L);
                s.setMblno(tmsorderbills.getMblno());
                s.setBillStatus(2L);
                s.setCreateTime(new Date());
                s.setCreateBy(loginUser.getUsername());
                if (ftmsorderbillscarsMapper.insertftmsorderbillscars(s) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新派车数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotNull(attachs) && !"[]".equals(attachs)) {
            JSONArray planJson = JSONArray.parseArray(attachs);
            List<Ftmsorderbillsattachs> tmsorderbillsattachsList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillsattachs.class);
            for (Ftmsorderbillsattachs a : tmsorderbillsattachsList) {
                a.setPId(pId);
                a.setActId(1020L);
                a.setBillStatus(2L);
                a.setCreateBy(loginUser.getUsername());
                a.setCreateTime(new Date());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(a) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotNull(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(1020L);
                f.setfBillstatus(2L);
                f.setCreateBy(loginUser.getUsername());
                f.setCreateTime(new Date());
                if (ftmsorderbillsfeesMapper.insertFTmsorderbillsfees(f) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新费用数据失败，若多次失败请联系管理员");
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 提交车队派车
     *
     * @param tmsorder  主表id
     * @param attachs   附件表
     * @param fees      费用表
     * @param cars      车俩安排表
     * @param loginUser 操作人
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertftmsorderbillscars(String tmsorder, String attachs, String fees, String cars, LoginUser loginUser) {
        Ftmsorderbills tmsorderbills = JSONArray.parseObject(tmsorder, Ftmsorderbills.class);
        long pId = tmsorderbills.getId();
        ftmsorderbillscarsMapper.deleteftmsorderbillscarsByPId(pId);
        ftmsorderbillsfeesMapper.deleteFTmsorderbillsfeesByPId(pId);
        ftmsorderbillsattachsMapper.deleteftmsorderbillsattachsByPId(pId);
        JSONArray planJson = JSONArray.parseArray(cars);
        List<Ftmsorderbillscars> tmsorderbillscarsList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillscars.class);
        for (Ftmsorderbillscars s : tmsorderbillscarsList) {
            s.setBillStatus(6L);
            s.setCreateTime(new Date());
            s.setCreateBy(loginUser.getUsername());
            if (ftmsorderbillscarsMapper.updateftmsorderbillscars(s) <= 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(pId);
                a.setActId(1020L);
                a.setBillStatus(6L);
                a.setCreateBy(loginUser.getUsername());
                a.setCreateTime(new Date());
                if (ftmsorderbillsattachsMapper.insertftmsorderbillsattachs(a) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新附件数据失败，若多次失败请联系管理员");
                }
            }
        }
        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(pId);
                a.setActId(1020L);
                a.setfBillstatus(6L);
                a.setCreateTime(new Date());
                a.setCreateBy(loginUser.getUsername());
                if (ftmsorderbillsfeesMapper.insertFTmsorderbillsfees(a) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新费用数据失败，若多次失败请联系管理员");
                }
            }
        }
        return AjaxResult.success();
    }

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

    /**
     * 批量删除车队派车
     *
     * @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) {
        if ("add".equals(status)) {
            ftmsorderbillscars.setPlanDate(new Date());
            ftmsorderbillscars.setOrderStatus(10L);
            ftmsorderbillscars.setBillStatus(6L);
            ftmsorderbillscars.setUpdateTime(new Date());
            ftmsorderbillscars.setUpdateBy(loginUser.getUsername());
            Ftmsorderbillsplans ftmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(ftmsorderbillscars.getPId());
            long carQty = ftmsorderbillsplans.getCarQty() + 1;
            if (ftmsorderbillsplans.getCntrQty() < carQty) {
                return AjaxResult.error("派车数量超出调度安排数量，请确认");
            }
            ftmsorderbillsplans.setCarQty(carQty);
            if (ftmsorderbillsplansMapper.updateftmsorderbillsplans(ftmsorderbillsplans) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新调度数据失败，若多次失败请联系管理员");
            }
            if (ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscars) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新车辆安排数据失败，若多次失败请联系管理员");
            }
            ftmsorderbillscars.setPId(ftmsorderbillscars.getId());
            ftmsorderbillscars.setId(null);
            ftmsorderbillscars.setBillStatus(2L);
            ftmsorderbillscars.setPlanDate(new Date());
            ftmsorderbillscars.setCreateTime(new Date());
            ftmsorderbillscars.setCreateBy(loginUser.getUsername());
            ftmsorderbillscars.setUpdateBy(null);
            ftmsorderbillscars.setUpdateTime(null);
            if (ftmsorderbillscarsMapper.insertftmsorderbillscars(ftmsorderbillscars) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新状态数据失败，若多次失败请联系管理员");
            }
        }
        if ("Revoke".equals(status)) {
            if (ftmsorderbillscars.getOrderStatus() > 30) {
                return AjaxResult.error("该安排车辆已经装卸货，无法撤回");
            }

            Ftmsorderbillscars scars = new Ftmsorderbillscars();
            scars.setPId(ftmsorderbillscars.getId());

            List<Ftmsorderbillscars> scarsList = ftmsorderbillscarsMapper.selectftmsorderbillscarsIdList(scars);
            boolean occStatus = false;
            for (Ftmsorderbillscars scar : scarsList) {
                if (!occStatus) {
                    TFeeDo tFeeDo = new TFeeDo();
                    tFeeDo.setfPid(scar.getId());
                    // 需要确认
//                    tFeeDoMapper.selectTFeeDoCount();
                }
            }

            if (ftmsorderbillscars.getStlAmtCr().compareTo(BigDecimal.ZERO) == 1 || ftmsorderbillscars.getStlAmtDr().compareTo(BigDecimal.ZERO) == 1) {
                return AjaxResult.error("该安排车辆已经发生结算金额，无法撤回");
            }
            ftmsorderbillscars.setOrderStatus(10L);
            Ftmsorderbillsplans ftmsorderbillsplans = ftmsorderbillsplansMapper.selectftmsorderbillsplansById(ftmsorderbillscars.getPId());
            long carQty = ftmsorderbillsplans.getCarQty() - 1;
            ftmsorderbillsplans.setCarQty(carQty);
            if (ftmsorderbillsplansMapper.updateftmsorderbillsplans(ftmsorderbillsplans) <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新调度数据失败，若多次失败请联系管理员");
            }
        }
        if (ftmsorderbillscarsMapper.updateftmsorderbillscars(ftmsorderbillscars) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新车辆安排数据失败，若多次失败请联系管理员");
        }
        return AjaxResult.success(ftmsorderbillscars);
    }

    // 派车单条删除
    @Transactional
    public AjaxResult vehicleArrangementRemove (Ftmsorderbillscars ftmsorderbillscars, LoginUser loginUser) {
        Long pId = ftmsorderbillscars.getId();

        Ftmsorderbills ftmsorderbills = new Ftmsorderbills();
        ftmsorderbills.setId(pId);
        ftmsorderbillscarsMapper.planSelectCarsCount(ftmsorderbills);


        return AjaxResult.success();
    }

}
