package com.sw.mes.fls.service.impl;


import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.fls.dao.TempTurnstoreTrayDao;
import com.sw.mes.fls.dto.ProductAssemblyInfoDto;
import com.sw.mes.fls.entity.TempTurnstoreTray;
import com.sw.mes.fls.entity.TempTurnstoreTrayItem;
import com.sw.mes.fls.service.TempTurnstoreTrayItemService;
import com.sw.mes.fls.service.TempTurnstoreTrayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
*/
@Service
@Transactional
public class TempTurnstoreTrayServiceImpl extends BaseServiceImpl<TempTurnstoreTray> implements TempTurnstoreTrayService {
    TempTurnstoreTrayDao dao;
	@Autowired
    public void setDao(TempTurnstoreTrayDao dao) {
        super.setBaseDao(dao);
        this.dao=dao;
    }

    @Autowired
    private TempTurnstoreTrayItemService tempTurnstoreTrayItemService;

    @Autowired
    private TempTurnstoreTrayService tempTurnstoreTrayService;

    @Override
    @Transactional(rollbackFor = Throwable.class, propagation = Propagation.REQUIRES_NEW)
    public TempTurnstoreTray saveTemp(ProductAssemblyInfoDto productAssemblyInfoDto) {
        //检查单晶在临时表中是否合法
        checkSectionNoInTemp(productAssemblyInfoDto);

        String trayName = productAssemblyInfoDto.getTrayName();//托位名称
        String sectionNo = productAssemblyInfoDto.getSectionNo();//打托单晶号
        Integer amount = productAssemblyInfoDto.getAmount();//打托总颗数
        Integer currentPosition = productAssemblyInfoDto.getCurrentPosition();//当前颗数

        //根据托位名称查询打托临时表（未完成托的、最新的）
        TempTurnstoreTray tempTurnstoreTray = tempTurnstoreTrayService.findByTrayName(trayName);
        TempTurnstoreTrayItem maxItem = null;
        if (tempTurnstoreTray != null){
            //查询托位名称最大的当前颗次
            maxItem = tempTurnstoreTrayItemService.findMaxCurrentPositionByTrayId(tempTurnstoreTray.getId());
        }

        //判断是否完成托
        Integer isFinish = isFinish(productAssemblyInfoDto,tempTurnstoreTray,maxItem);

        //保存临时表
        TempTurnstoreTray finishTempTurnstoreTray = saveTemp(productAssemblyInfoDto, isFinish, tempTurnstoreTray);

        return finishTempTurnstoreTray;
    }

    private void checkSectionNoInTemp(ProductAssemblyInfoDto productAssemblyInfoDto) {
        Map<String, Object> item = tempTurnstoreTrayItemService.findBySectionNoWithoutGrouped(productAssemblyInfoDto.getSectionNo());
        if (item.size()>0) {
            throw new RuntimeException("单晶"+productAssemblyInfoDto.getSectionNo()+"在托位["+item.get("tray_name")+"]准备组托中，请勿重复上报！");
        }
    }

    @Override
    public TempTurnstoreTray findByTrayName(String trayName) {
        List<TempTurnstoreTray> list = dao.findByTrayName(trayName);
        if (list != null && list.size() > 0){
            return list.get(0);
        }
        return null;
    }


    /**
     *
     * @param productAssemblyInfoDto
     * @param tempTurnstoreTray
     * @param maxItem
     * @return 1 当前托位名称为完成托，当前晶段是当前托最后一根
     *         2 当前托位名称为完成托，当前晶段是新托第一根，并创建新托
     *         0 当前托未完成or当前托不存在
     */
    private Integer isFinish(ProductAssemblyInfoDto productAssemblyInfoDto, TempTurnstoreTray tempTurnstoreTray, TempTurnstoreTrayItem maxItem) {
        String trayName = productAssemblyInfoDto.getTrayName();//托位名称
        String sectionNo = productAssemblyInfoDto.getSectionNo();//打托单晶号
        Integer amount = productAssemblyInfoDto.getAmount();//打托总颗数
        Integer currentPosition = productAssemblyInfoDto.getCurrentPosition();//当前颗数

        if (amount <= currentPosition){
            return 1; //当前颗次等于最大颗次，代表已完成托
        }else {
            if (tempTurnstoreTray == null){
                return 0;
            }
            if (null != maxItem && maxItem.getCurrentPosition() >= currentPosition){
                return 2; //当前颗次小于最大颗次，代表已完成托，当前为新的一托
            }else {
                return 0;
            }
        }
    }

    /**
     *
     * @param productAssemblyInfoDto
     * @param isFinish 1 当前托位名称为完成托，当前晶段是当前托最后一根
     *                 2 当前托位名称为完成托，当前晶段是新托第一根，并创建新托
     *                 0 当前托未完成or当前托不存在
     * @param tempTurnstoreTray
     * @return
     */
    private TempTurnstoreTray saveTemp(ProductAssemblyInfoDto productAssemblyInfoDto, Integer isFinish, TempTurnstoreTray tempTurnstoreTray) {
        String trayName = productAssemblyInfoDto.getTrayName();//托位名称
        String sectionNo = productAssemblyInfoDto.getSectionNo();//打托单晶号
        Integer amount = productAssemblyInfoDto.getAmount();//打托总颗数
        Integer currentPosition = productAssemblyInfoDto.getCurrentPosition();//当前颗数

        if (isFinish == 1) { //完成拖,并返回当前托
            tempTurnstoreTray.setFinished(1);
            tempTurnstoreTrayService.saveOrUpdate(tempTurnstoreTray); //标记当前托为完成拖

            //补充当前托明细
            suppleGroupItem(tempTurnstoreTray, sectionNo, currentPosition);
            return tempTurnstoreTray;
        } else if (isFinish == 2) {//完成托，并创建新托，并返回当前托
            tempTurnstoreTray.setFinished(1);
            tempTurnstoreTrayService.saveOrUpdate(tempTurnstoreTray); //标记当前托为完成拖
            //并创建新托
            createNewGroup(trayName, sectionNo, amount, currentPosition);

            return tempTurnstoreTray;
        } else {

            if (tempTurnstoreTray == null) {
                //创建新托
                TempTurnstoreTray tempTurnstoreTray1= createNewGroup(trayName, sectionNo, amount, currentPosition);
                return tempTurnstoreTray1;
            } else {
                tempTurnstoreTray.setFinished(0);
                //补充当前托明细
                suppleGroupItem(tempTurnstoreTray, sectionNo, currentPosition);
            }

            return tempTurnstoreTray;
        }

    }

    public void suppleGroupItem(TempTurnstoreTray tempTurnstoreTray, String sectionNo, Integer currentPosition) {
        TempTurnstoreTrayItem tempTurnstoreTrayItem = new TempTurnstoreTrayItem(sectionNo, currentPosition, tempTurnstoreTray.getId(), new Date());
        tempTurnstoreTrayItemService.saveOrUpdate(tempTurnstoreTrayItem);
    }

    public TempTurnstoreTray createNewGroup(String trayName, String sectionNo, Integer amount, Integer currentPosition) {
        TempTurnstoreTray newTempTurnstoreTray = new TempTurnstoreTray(trayName, amount, 0, new Date());
        tempTurnstoreTrayService.saveOrUpdate(newTempTurnstoreTray);

        TempTurnstoreTrayItem tempTurnstoreTrayItem = new TempTurnstoreTrayItem(sectionNo, currentPosition, newTempTurnstoreTray.getId(), new Date());
        tempTurnstoreTrayItemService.saveOrUpdate(tempTurnstoreTrayItem);
        return newTempTurnstoreTray;
    }
}
