package com.op.mes.service.impl;

import java.util.*;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.op.common.core.context.SecurityContextHolder;
import com.op.common.core.utils.DateUtils;
import com.op.common.core.utils.uuid.IdUtils;
import com.op.common.core.web.domain.AjaxResult;
import com.op.mes.domain.*;
import com.op.mes.domain.dto.ProOrderDTO;
import com.op.mes.domain.dto.SplitOrderDTO;
import com.op.mes.domain.vo.LineAndShiftVo;
import com.op.mes.mapper.ProOrderWorkorderBatchMapper;
import com.op.mes.mapper.ProOrderWorkorderMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.op.mes.mapper.ProOrderMapper;
import com.op.mes.service.IProOrderService;
import org.springframework.transaction.annotation.Transactional;

import static com.op.common.core.web.domain.AjaxResult.error;
import static com.op.common.core.web.domain.AjaxResult.success;

/**
 * 订单Service业务层处理
 *
 * @author Open Platform
 * @date 2023-07-13
 */
@Service
public class ProOrderServiceImpl implements IProOrderService {
    @Autowired
    private ProOrderMapper proOrderMapper;
    @Autowired
    private ProOrderWorkorderMapper proOrderWorkorderMapper;
    @Autowired
    private ProOrderWorkorderBatchMapper proOrderWorkorderBatchMapper;

    /**
     * 获取换算值
     *
     * @return
     */
    @Override
    @DS("master")
    public List<Convert> getConvert() {
        return proOrderMapper.selectConvert();
    }

    /**
     * 提交拆分订单接口
     *
     * @param splitOrderDTO
     * @return
     */
    @Override
    @Transactional
    @DS("#header.poolName")
    public AjaxResult subSplitOrder(SplitOrderDTO splitOrderDTO) {
        boolean checkout = true;
        // 校验批次编号是否存在（重复问题）
        List<String> batchCodes = proOrderMapper.selectBatchCodes();
        for (int i = 0; i < batchCodes.size(); i++) {
            for (int j = 0; j < splitOrderDTO.getFormFields().size(); j++) {
                if (batchCodes.get(i).equals(splitOrderDTO.getFormFields().get(j).getBatchCode())) {
                    checkout = false;
                }
            }
        }

        // 如果不重复
        if (checkout) {
            // 判断是否为底层节点
            int checkEnd = 0;
            // 创建ProOrderWorkorder对象用于数据更新减少io
            ProOrderWorkorder updateWorker = new ProOrderWorkorder();
            ProOrder product = new ProOrder();
            BeanUtils.copyProperties(splitOrderDTO.getProduct(), product);
            // 设置通用属性
            ProOrderWorkorder proOrderWorkorder = setCommonWorkAttribute(product, splitOrderDTO.getProductDate(), splitOrderDTO.getProdLineCode(), splitOrderDTO.getShiftId());
            // 生成对应工单表
            // 一级
            ProOrderWorkorder firWorkOrder = setWorkOrder(proOrderWorkorder, product);
            // 更新到数据库
            proOrderWorkorderMapper.insertProOrderWorkorder(firWorkOrder);
            // 创建通用批次表对象
            ProOrderWorkorderBatch workBatch = setCommonBatchAttribute();
            // 生成批次表并更新到数据库
            setBatch(workBatch, splitOrderDTO.getFormFields(), firWorkOrder.getWorkorderId());

            // 二级
            if (splitOrderDTO.getProduct().getChildren() != null) {
                // 判断加1
                checkEnd += 1;

                List<ProOrderDTO> secProOrderList = splitOrderDTO.getProduct().getChildren();
                BeanUtils.copyProperties(secProOrderList.get(0), product);
                // 设置父工单
                proOrderWorkorder.setParentOrder(firWorkOrder.getWorkorderCode());
                ProOrderWorkorder secWorkOrder = setWorkOrder(proOrderWorkorder, product);
                // 更新到数据库
                proOrderWorkorderMapper.insertProOrderWorkorder(secWorkOrder);
                // 生成批次表并更新到数据库
                setBatch(workBatch, splitOrderDTO.getFormFields(), secWorkOrder.getWorkorderId());

                // 三级
                if (secProOrderList.get(0).getChildren() != null) {
                    // 判断加1
                    checkEnd += 1;

                    List<ProOrderDTO> thiProOrderList = secProOrderList.get(0).getChildren();
                    BeanUtils.copyProperties(thiProOrderList.get(0), product);
                    // 设置父工单
                    proOrderWorkorder.setParentOrder(secWorkOrder.getWorkorderCode());
                    ProOrderWorkorder thiWorkOrder = setWorkOrder(proOrderWorkorder, product);
                    // 设置为底层节点
                    thiWorkOrder.setIsEnd(1);
                    // 更新到数据库
                    proOrderWorkorderMapper.insertProOrderWorkorder(thiWorkOrder);
                    // 生成批次表并更新到数据库
                    setBatch(workBatch, splitOrderDTO.getFormFields(), thiWorkOrder.getWorkorderId());
                }

                // 设置为底层节点
                if (checkEnd == 1){
                    updateWorker.setWorkorderId(secWorkOrder.getWorkorderId());
                    updateWorker.setIsEnd(1);
                    proOrderWorkorderMapper.updateProOrderWorkorder(updateWorker);
                }

            }

            // 设置为底层节点
            if (checkEnd == 1){
                updateWorker.setWorkorderId(firWorkOrder.getWorkorderId());
                updateWorker.setIsEnd(1);
                proOrderWorkorderMapper.updateProOrderWorkorder(updateWorker);
            }

            return success();

        }

        return error(500, "批次号不能重复");
    }

    /**
     * 获取工单信息列表
     *
     * @param id
     * @return
     */
    @Override
    @DS("#header.poolName")
    public AjaxResult getWorkOrderList(String id) {
        // 通过订单id查询所有工单信息list
        List<ProOrderWorkorder> proOrderWorkorderList = proOrderWorkorderMapper.selectFirWorkOrder(id);
        // 母工单循环遍历
        for (int i = 0;i < proOrderWorkorderList.size();i++){
            // 通过设备code查询出机型名称
            String prodLineName = proOrderMapper.selectProdLineName(proOrderWorkorderList.get(i).getProdLineCode());
            // 通过工单id查询批次号
            List<String> batchCodeList = proOrderMapper.selectBatchCodesById(proOrderWorkorderList.get(i).getWorkorderId());
            List<StringBuilder> batchCodes = new ArrayList<>();
            // 格式化数据
            for (int j = 0;j < batchCodeList.size();j++){
                batchCodes.add(new StringBuilder(batchCodeList.get(j)).append(";").append("\n"));
            }
            // 通过母工单workorder_id查询子工单
            // 二级
            List<ProOrderWorkorder> secProOrderWorkorder = proOrderWorkorderMapper.selectChildWorkOrder(proOrderWorkorderList.get(i).getWorkorderCode());
            if (secProOrderWorkorder.size() > 0 && secProOrderWorkorder != null){
                // 三级
                List<ProOrderWorkorder> thiProOrderWorkorders = proOrderWorkorderMapper.selectChildWorkOrder(secProOrderWorkorder.get(0).getWorkorderCode());
                if (thiProOrderWorkorders.size() > 0 && thiProOrderWorkorders != null){
                    // 将三级放入二级child
                    thiProOrderWorkorders.get(0).setProdLineCode(prodLineName);
                    thiProOrderWorkorders.get(0).setBatchCodeList(batchCodes);
                    secProOrderWorkorder.get(0).setChildren(thiProOrderWorkorders);
                }
                // 将二级放入到母工单child
                secProOrderWorkorder.get(0).setProdLineCode(prodLineName);
                secProOrderWorkorder.get(0).setBatchCodeList(batchCodes);
                proOrderWorkorderList.get(i).setChildren(secProOrderWorkorder);
            }
            proOrderWorkorderList.get(i).setProdLineCode(prodLineName);
            proOrderWorkorderList.get(i).setBatchCodeList(batchCodes);
        }
        return success(proOrderWorkorderList);
    }

    /**
     * 获取当前订单信息列表
     *
     * @param id
     * @return
     */
    @Override
    @DS("#header.poolName")
    public AjaxResult getOrderList(String id) {
        // 注意判空不为空则放入 （避免空指针）
        // 通过母工单id查询母订单详情
        ProOrder proOrder = proOrderMapper.selectProOrderById(id);
        // 查询二级
        List<ProOrder> secProOrderList = proOrderMapper.selectChildProOrderByCode(proOrder.getOrderCode());
        if (secProOrderList != null || secProOrderList.size() > 0) {
            // 查询三级
            List<ProOrder> thiProOrderList = proOrderMapper.selectChildProOrderByCode(secProOrderList.get(0).getOrderCode());
            if (thiProOrderList != null || thiProOrderList.size() > 0) {
                // 将三级Order放入二级
                secProOrderList.get(0).setChildren(thiProOrderList);
            }
        }
        // 将二级Order放入母订单
        proOrder.setChildren(secProOrderList);

        return success(proOrder);
    }

    /**
     * 获取成型机
     *
     * @return
     */
    @Override
    @DS("#header.poolName")
    public LineAndShiftVo getProdLineShift() {
        LineAndShiftVo lineAndShiftVo = new LineAndShiftVo(proOrderMapper.selectProdLine(), proOrderMapper.selectProShift());
        return lineAndShiftVo;
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public ProOrder selectProOrderById(String id) {
        return proOrderMapper.selectProOrderById(id);
    }

    /**
     * 查询订单列表
     *
     * @param proOrder 订单
     * @return 订单
     */
    @Override
    @DS("#header.poolName")
    public List<ProOrder> selectProOrderList(ProOrder proOrder) {
        return proOrderMapper.selectProOrderList(proOrder);
    }

    /**
     * 新增订单
     *
     * @param proOrder 订单
     * @return 结果
     */
    @Override
    @DS("#header.poolName")
    public int insertProOrder(ProOrder proOrder) {
        proOrder.setId(IdUtils.fastSimpleUUID());
        proOrder.setCreateTime(DateUtils.getNowDate());
        return proOrderMapper.insertProOrder(proOrder);
    }

    /**
     * 修改订单
     *
     * @param proOrder 订单
     * @return 结果
     */
    @Override
    @DS("#header.poolName")
    public int updateProOrder(ProOrder proOrder) {
        proOrder.setUpdateTime(DateUtils.getNowDate());
        return proOrderMapper.updateProOrder(proOrder);
    }

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    @DS("#header.poolName")
    public int deleteProOrderByIds(String[] ids) {
        return proOrderMapper.deleteProOrderByIds(ids);
    }

    /**
     * 删除订单信息
     *
     * @param id 订单主键
     * @return 结果
     */
    @Override
    @DS("#header.poolName")
    public int deleteProOrderById(String id) {
        return proOrderMapper.deleteProOrderById(id);
    }

    /**
     * 设置工单通用属性
     *
     * @param proOrder
     * @return
     */
    private ProOrderWorkorder setCommonWorkAttribute(ProOrder proOrder, Date date, String proLineCode, String shiftId) {
        ProOrderWorkorder proOrderWorkorder = new ProOrderWorkorder();
        // 更新者
        proOrderWorkorder.setUpdateBy(SecurityContextHolder.getUserName());
        // 创建者
        proOrderWorkorder.setCreateBy(SecurityContextHolder.getUserName());
        // 工单生产日期
        proOrderWorkorder.setProductDate(date);
        // 产品（物料）编码
        proOrderWorkorder.setProductCode(proOrder.getProdCode());
        // TODO 产品（物料）名称
        proOrderWorkorder.setProductName("测试ing");
        // 产品（物料）规格型号
        proOrderWorkorder.setProductSpc(proOrder.getProdSpc());
        // 产线
        proOrderWorkorder.setProdLineCode(proLineCode);
        // 班次
        proOrderWorkorder.setShiftId(shiftId);
        // TODO 产品类型(pro_type)
        // 单据状态(1为正常)
        proOrderWorkorder.setStatus("1");
        return proOrderWorkorder;
    }

    /**
     * 设置工单属性
     *
     * @param proOrderWorkorder
     * @param proOrder
     * @return
     */
    private ProOrderWorkorder setWorkOrder(ProOrderWorkorder proOrderWorkorder, ProOrder proOrder) {
        // 获取当前时间
        Date date = new Date();
        // 订单表更新时间/更新者
        proOrder.setUpdateBy(SecurityContextHolder.getUserName());
        proOrder.setUpdateTime(date);
        // 更新订单表
        proOrderMapper.updateOrder(proOrder);
        // 生成对应的工单表
        // 生成id
        proOrderWorkorder.setWorkorderId(IdUtils.fastSimpleUUID());
        // 生成工单号
        proOrderWorkorder.setWorkorderCode("GD" + DateUtils.parseDateToStr(DateUtils.YYYYMMDDHHMMSSsss, date));
        // TODO 工单名称
        proOrderWorkorder.setWorkorderName("测试ing");
        // 订单id
        proOrderWorkorder.setOrderId(proOrder.getId());
        // 订单编码
        proOrderWorkorder.setOrderCode(proOrder.getOrderCode());
        // 单位
        proOrderWorkorder.setUnit(proOrder.getUnit());
        // 已拆分数量
        proOrderWorkorder.setQuantitySplit(Long.valueOf(proOrder.getAtrr1()));
        // TODO 工艺编码
        // TODO 所有父节点
        return proOrderWorkorder;
    }

    /**
     * 设置批次表通用
     *
     * @return
     */
    private ProOrderWorkorderBatch setCommonBatchAttribute() {
        ProOrderWorkorderBatch workBatch = new ProOrderWorkorderBatch();
        Date date = new Date();
        // 更新者
        workBatch.setUpdateBy(SecurityContextHolder.getUserName());
        // 创建者
        workBatch.setCreateBy(SecurityContextHolder.getUserName());
        // 设置单据状态（1正常）
        workBatch.setStatus("1");
        return workBatch;
    }

    /**
     * 生成批次表并更新至数据库
     *
     * @param workBatch
     * @param batchList
     * @param workOrderId
     */
    private void setBatch(ProOrderWorkorderBatch workBatch, List<Batch> batchList, String workOrderId) {
        // 工单id
        workBatch.setWorkorderId(workOrderId);
        // TODO 产品类型
        for (int i = 0; i < batchList.size(); i++) {
            // 生成批次id
            workBatch.setBatchId(IdUtils.fastSimpleUUID());
            Batch batch = batchList.get(i);
            // 获取批次号
            workBatch.setBatchCode(batch.getBatchCode());
            // 获取批次数量
            workBatch.setBatchQuantity(batch.getBatchQuantity());
            // 更新至数据库
            proOrderWorkorderBatchMapper.insertProOrderWorkorderBatch(workBatch);
        }
    }

}