package com.sw.mes.stocktaking;

import com.alibaba.fastjson.JSONObject;
import com.sw.mes.base.workinprocess.dao.WipStorageHistoryDao;
import com.sw.mes.base.workinprocess.dto.PlanProcessingOrderWipStorageDto;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.entity.WipStorage;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.base.workinprocess.service.WipStorageService;
import com.sw.mes.core.api.system.FbFeignClients;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.exception.BusinessException;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultCode;
import com.sw.mes.inspect.entity.YbInspectData;
import com.sw.mes.inspect.service.YbInspectDataService;
import com.sw.mes.yb.printer.dto.FbCheckOutDataDto;
import com.sw.mes.yb.production.entity.LongCrystal;
import com.sw.mes.yb.production.service.LongCrystalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

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

/**
 * @Author：wanjia
 * @Date：2024/3/15 09:12
 */
@Service
@Slf4j
@Transactional
public class StocktakingService extends BaseServiceImpl<Stocktaking> {

    private StocktakingDAO stocktakingDAO;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private YbInspectDataService ybInspectDataService;

    @Autowired
    private WipStorageHistoryDao wipStorageHistoryDao;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Autowired
    private FbFeignClients fbFeignClients;

    @Autowired
    private LongCrystalService longCrystalService;

    @Autowired
    public void setBaseDao(StocktakingDAO baseDao) {
        this.stocktakingDAO = baseDao;
        super.setBaseDao(baseDao);
    }


    /**
     * 批量写入接口
     *
     * @param stocktakings
     * @return
     */
    public int insert(List<Stocktaking> stocktakings) throws BusinessException {
        if (CollectionUtils.isEmpty(stocktakings)) {
            return 0;
        }
        //更新时间和置空id
        stocktakings.forEach(stocktaking -> {
            stocktaking.setId(null);
            stocktaking.setGmtCreate(new Date());
        });
        try {
            List<Stocktaking> result = stocktakingDAO.saveAll(stocktakings);
            if (result != null) {
                return result.size();
            }
        } catch (Exception e) {
            log.error("error_in_stocktaking_insert", e);
            throw new BusinessException("数据写入错误!!");
        }
        return 0;
    }


    /**
     * 根据晶编查再制品信息
     *
     * @param sectionNo
     * @return
     */
    public Stocktaking queryStocktaking(String sectionNo) {
        Result<PlanProcessingOrderWipStorageDto> result = wipStorageService.queryCurrentStation(sectionNo);
        if (null == result || null == result.getData()) {
            throw new BusinessException("无法查询到在制品信息，晶编号：" + sectionNo);
        }
        if (result.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BusinessException(result.getMessage());
        }

        Stocktaking stocktaking = new Stocktaking();
        //给基础信息
        stocktaking.setSectionNo(sectionNo);
        stocktaking.setUsername(BaseContextHandler.getUsername());
        stocktaking.setGmtCreate(new Date());
        //在制品信息
        WipStorage storage = result.getData().getWipStorage();
        PlanProcessingOrder planProcessingOrder = result.getData().getPlanProcessingOrder();
        stocktaking.setWipStorageStation(storage.getProcessName());
        stocktaking.setWeight(planProcessingOrder.getWeight());//todo 这个重量是否对？
        stocktaking.setLength(planProcessingOrder.getLength());

        String processName = storage.getProcessName();
        Integer status = storage.getStatus();
        if ((StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.方棒检验.getValue()) &&
                status.equals(EnumValuesFactory.WipStorageStatus.已进站.getKey())) ||
                StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.方棒截断.getValue()) ||
                StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.粘方棒.getValue())) {
            Result dataByFbSectionNo = fbFeignClients.findDataByFbSectionNo(sectionNo);
            if (dataByFbSectionNo != null && dataByFbSectionNo.getCode() == 200) {
                FbCheckOutDataDto fbCheckOutDataDto = JSONObject.parseObject(JSONObject.toJSONString(dataByFbSectionNo.getData()), FbCheckOutDataDto.class);
                stocktaking.setLength(fbCheckOutDataDto.getLength());
//                //如果重量不为空，且>0
//                if (null != fbCheckOutDataDto.getWeight() && fbCheckOutDataDto.getWeight().compareTo(new BigDecimal(0)) > 0) {
//                    stocktaking.setWeight(fbCheckOutDataDto.getWeight());
//                } else {
//                    stocktaking.setWeight(fbCheckOutDataDto.getTheoryWeightFb());
//                }
                stocktaking.setWeight(fbCheckOutDataDto.getTheoryWeightFb());
                stocktaking.setMaterialCode(fbCheckOutDataDto.getMaterialCode());
                stocktaking.setProductLevel(fbCheckOutDataDto.getProductLevelFb());
            } else {//先不阻塞流程
                log.error("盘账时，查找方棒检验信息不存在，晶编：{}", sectionNo);
            }
        } else if ((StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.方棒检验.getValue()) &&
                status.equals(EnumValuesFactory.WipStorageStatus.待进站.getKey())) ||
                (StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.圆棒检验.getValue()) &&
                        status.equals(EnumValuesFactory.WipStorageStatus.已进站.getKey())) ||
                StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.粘圆棒.getValue()) ||
                StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.圆棒截断.getValue()) ||
                StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.磨倒.getValue()) ||
                StringUtils.equals(processName, EnumValuesFactory.WipStorageCode.开方.getValue())) {
            YbInspectData ybInspectData = ybInspectDataService.findBySectionNo(sectionNo);
            if (null != ybInspectData) {
                stocktaking.setLength(ybInspectData.getActualLength());
//                if (null != ybInspectData.getActualWeight() && ybInspectData.getActualWeight().compareTo(new BigDecimal(0)) > 0) {
//                    stocktaking.setWeight(ybInspectData.getActualWeight());
//                } else {
//                    stocktaking.setWeight(ybInspectData.getTheoryWeight());
//                }
                stocktaking.setWeight(ybInspectData.getTheoryWeight());
                stocktaking.setMaterialCode(ybInspectData.getMaterialCode());
                stocktaking.setProductLevel(ybInspectData.getProductLevel());
            } else {
                log.error("盘账时，查找圆棒检验信息不存在，晶编：{}", sectionNo);
            }
        } else {
            LongCrystal byCrystalNo = longCrystalService.findByCrystalNo(sectionNo);
            if (byCrystalNo != null) {
                stocktaking.setLength(byCrystalNo.getLength());
                stocktaking.setWeight(byCrystalNo.getWeight());
                stocktaking.setMaterialCode(byCrystalNo.getProductCode());
            } else {
                log.error("盘账时，查找长晶棒信息不存在，晶编：{}", sectionNo);
            }
        }
        return stocktaking;
    }
}
