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.IftmsorderbillsService;
import com.ruoyi.orderManagement.statusTracking.domain.Ftmsorderbillsfees;
import com.ruoyi.orderManagement.statusTracking.mapper.FtmsorderbillsfeesMapper;
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 FtmsorderbillsServiceImpl implements IftmsorderbillsService {
    @Autowired
    private FtmsorderbillsMapper ftmsorderbillsMapper;

    @Autowired
    private ProjectBillsHistoryMapper billsHistoryMapper;

    @Autowired
    private FtmsorderbillscntrsMapper ftmsorderbillscntrsMapper;

    @Autowired
    private FtmsorderbillscarsMapper ftmsorderbillscarsMapper;

    @Autowired
    private FtmsorderbillsattachsMapper ftmsorderbillsattachsMapper;

    @Autowired
    private FtmsorderbillsfeesMapper ftmsorderbillsfeesMapper;

    @Autowired
    private BillnoSerialServiceImpl billnoSerialServiceImpl;

    @Autowired
    private FtmsorderbillsplansMapper ftmsorderbillsplansMapper;

    /**
     * 查询订单主
     *
     * @param id 订单主ID
     * @return 订单主
     */
    @Override
    public Map<String, Object> selectftmsorderbillsById(Long id) {
        Map<String, Object> map = new HashMap<>();
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(id);
        // 查询计划货量
        Ftmsorderbillscntrs ftmsorderbillscntrs = new Ftmsorderbillscntrs();
        ftmsorderbillscntrs.setPId(id);
        List<Ftmsorderbillscntrs> tmsorderbillsList = ftmsorderbillscntrsMapper.selectftmsorderbillscntrsList(ftmsorderbillscntrs);
        // 查询费用明细
        Ftmsorderbillsfees ftmsorderbillsfees = new Ftmsorderbillsfees();
        ftmsorderbillsfees.setfPid(id);
        List<Ftmsorderbillsfees> tmsorderbillsfeesList = ftmsorderbillsfeesMapper.selectFTmsorderbillsfeesList(ftmsorderbillsfees);
        // 查询调度安排明细
        Ftmsorderbillsplans ftmsorderbillsplans = new Ftmsorderbillsplans();
        ftmsorderbillsplans.setPId(id);
        List<Ftmsorderbillsplans> tmsorderbillsplansList = ftmsorderbillsplansMapper.selectftmsorderbillsplansList(ftmsorderbillsplans);
        map.put("tmsorder", ftmsorderbills);
        map.put("scntrs", tmsorderbillsList);
        map.put("fees", tmsorderbillsfeesList);
        map.put("plans", tmsorderbillsplansList);
        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 (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(itemstatus);
                s.setCreateBy(loginUser.getUsername());
                s.setCreateTime(new Date());
                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(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.isNotNull(fees) && !"[]".equals(fees)) {
            JSONArray feesJson = JSONArray.parseArray(fees);
            List<Ftmsorderbillsfees> tmsorderbillsfeesList = JSONObject.parseArray(feesJson.toJSONString(), Ftmsorderbillsfees.class);
            for (Ftmsorderbillsfees f : tmsorderbillsfeesList) {
                f.setfId(null);
                f.setfPid(pId);
                f.setOrgId(pId);
                f.setActId(1000L);
                f.setfStatus(itemstatus);
                f.setCreateBy(loginUser.getUsername());
                f.setCreateTime(new Date());
                if (ftmsorderbillsfeesMapper.insertFTmsorderbillsfees(f) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新费用数据失败，若多次失败请联系管理员");
                }
            }
        }
        if (StringUtils.isNotNull(plans) && !"[]".equals(plans)) {
            JSONArray planJson = JSONArray.parseArray(plans);
            List<Ftmsorderbillsplans> tmsorderbillsplansList = JSONObject.parseArray(planJson.toJSONString(), Ftmsorderbillsplans.class);
            for (Ftmsorderbillsplans p : tmsorderbillsplansList) {
                p.setPId(pId);
                p.setBillStatus(itemstatus);
                p.setCreateBy(loginUser.getUsername());
                p.setCreateTime(new Date());
                if (ftmsorderbillsplansMapper.insertftmsorderbillsplans(p) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新调度数据失败，若多次失败请联系管理员");
                }
                if (Objects.equals(itemstatus, 6)) {
                    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) {
        long pId = 0L;
        Ftmsorderbills tmsorderbills = JSONArray.parseObject(tmsorder, Ftmsorderbills.class);
        if (StringUtils.isNull(tmsorderbills.getBillStatus())) {
            return AjaxResult.error("未找到单据状态，请确认");
        }
        if (Objects.equals(tmsorderbills.getBillStatus(), 6)) {
            if (StringUtils.isNull(scntrs) || "[]".equals(scntrs)) {
                return AjaxResult.error("未找到计划货量数据，请确认");
            }
            tmsorderbills.setPostDate(new Date());
        }
        int tmsorderStatus = 0;
        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.setCreateBy(loginUser.getUsername());
            tmsorderbills.setCreateTime(new Date());
            tmsorderStatus = ftmsorderbillsMapper.insertftmsorderbills(tmsorderbills);
            pId = tmsorderbills.getId();
        } else {
            // 代表保存过在提交
            pId = tmsorderbills.getId();
            tmsorderbills.setUpdateBy(loginUser.getUsername());
            tmsorderbills.setUpdateTime(new Date());
            tmsorderStatus = ftmsorderbillsMapper.updateftmsorderbills(tmsorderbills);
        }
        if (tmsorderStatus <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新计划数据失败，若多次失败请联系管理员");
        }
        ftmsorderbillsfeesMapper.deleteFTmsorderbillsfeesByPId(pId);
        ftmsorderbillscntrsMapper.deleteftmsorderbillscntrsByPId(pId);
        ftmsorderbillsplansMapper.deleteftmsorderbillsplansByPId(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;
        }
        return AjaxResult.success();
    }

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

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

    /**
     * 删除订单主信息
     *
     * @param id 订单主ID
     * @return 结果
     */
    @Override
    public int deleteftmsorderbillsById(Long id) {
        return ftmsorderbillsMapper.deleteftmsorderbillsById(id);
    }


    /**
     *  判断是否允许变更
     * @param id    计划下达信息
     * @return  结果
     */
    @Override
    public boolean allowChanges(Long id) {
        Ftmsorderbills tmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(id);
        if (Objects.equals(tmsorderbills.getBillStatus(), 6)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *  计划下达变更提交
     * @param tmsorder  计划
     * @param scntrs    箱型箱量
     * @param attachs   附件
     * @param fees      费用
     * @param plans     调度
     * @param loginUser 用户
     * @return  结果
     */
    @Override
    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();
        if (!allowChanges(pId)) {
            return AjaxResult.error("该计划状态不是提交状态请确认");
        }
        Ftmsorderbills ftmsorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(tmsorderbills.getId());
        ProjectBillsHistory projectBillsHistory = new ProjectBillsHistory();
        projectBillsHistory.setProjectId(pId);
        projectBillsHistory.setActId(1100L);
        Date time = new Date();
        // 计划变更流水号
        String billNo = billnoSerialServiceImpl.getSerialNumber("JHBGBF", time);
        projectBillsHistory.setSerialNumber(billNo);
        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("更新备份信息失败，若多次出现请联系管理员");
        }
        tmsorderbills.setUpdateTime(new Date());
        tmsorderbills.setUpdateBy(loginUser.getUsername());
        if (ftmsorderbillsMapper.updateftmsorderbills(tmsorderbills) <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新计划失败，若多次出现请联系管理员");
        }
        ftmsorderbillsfeesMapper.deleteFTmsorderbillsfeesByPId(pId);
        ftmsorderbillscntrsMapper.deleteftmsorderbillscntrsByPId(pId);
        ftmsorderbillsplansMapper.deleteftmsorderbillsplansByPId(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("更新货量数据失败，若多次失败请联系管理员");
            }
        }
        AjaxResult ajaxResult = updateItem(pId, 6, null, attachs, fees, plans, loginUser);
        String code = ajaxResult.get("code").toString();
        if ("500".equals(code)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ajaxResult;
        }
        return AjaxResult.success();
    }

    /**
     * 计划操作撤回
     *
     * @param ftmsorderbills 计划数据
     * @param types
     * @param loginUser      登陆人
     * @return 结果
     */
    @Override
    public AjaxResult planCancel(Ftmsorderbills ftmsorderbills, String types, LoginUser loginUser) {
        Ftmsorderbills sorderbills = ftmsorderbillsMapper.selectftmsorderbillsById(ftmsorderbills.getId());
        // 撤销
        if ("planCancel".equals(types)) {
            if (sorderbills.getBillStatus() < 6) {
                return AjaxResult.error("该计划未提交，不可撤销");
            }
            if (ftmsorderbillscarsMapper.planSelectCarsCount(sorderbills) > 0) {
                return AjaxResult.error("该计划已存在提箱车辆，不可撤销");
            }
            // 计划下达撤销，修改后续模块状态
            if (ftmsorderbillsMapper.updateTmsordRearModule(ftmsorderbills) <= 0) {
                return AjaxResult.error("计划变更失败，若多次出现请联系管理员");
            }
        }
        return AjaxResult.success();
    }

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

}
