package com.sw.mes.yb.pc.service.impl;


import com.sw.mes.base.system.dao.DictionaryItemDao;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.base.system.entity.DictionaryItem;
import com.sw.mes.enumvalue.SceneEnumValues;
import com.sw.mes.yb.pc.dao.FbjoinDao;
import com.sw.mes.yb.pc.dao.FbjoinDetailDao;
import com.sw.mes.yb.pc.entity.Fbjoin;
import com.sw.mes.yb.pc.entity.FbjoinDetail;
import com.sw.mes.yb.pc.service.FbjoinService;
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 java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class FbjoinServiceImpl extends BaseServiceImpl<Fbjoin> implements FbjoinService {
    FbjoinDao dao;

    @Autowired
    public void setDao(FbjoinDao dao) {
        super.setBaseDao(dao);
        this.dao = dao;
    }

    @Autowired
    FbjoinDetailDao fbjoinDetailDao;
/*
    @Autowired
    CheckOutDao checkOutDao;*/

    @Autowired
    DictionaryItemDao dictionaryItemDao;

    @Override
    public void unbind(Integer id) {
        Fbjoin fbjoinEntity = dao.getOne(id);
        fbjoinEntity.setUnbindUser(BaseContextHandler.getUsername());
        fbjoinEntity.setUnbindTime(new Date());
        fbjoinEntity.setState(SceneEnumValues.FbJoinStatus.已解绑.getValue());
        dao.save(fbjoinEntity);
        fbjoinDetailDao.updateStatusByfbjoinId(id, SceneEnumValues.FbJoinStatus.已解绑.getValue());
    }

    @Override
    public void deleteByMainId(Integer id) {
        dao.deleteById(id);
        fbjoinDetailDao.deleteByMainId(id);
    }

    @Override
    public void createBySectionNoFbList(List<String> sectionNoFbList) {
        if (sectionNoFbList == null || sectionNoFbList.size() == 0) {
            throw new RuntimeException("错误,单晶编号列表为空");
        }
        List<String> list = new ArrayList<>();
        for (String sectionNoFb : sectionNoFbList) {
            if (StringUtils.isNotBlank(sectionNoFb)) {
                list.add(sectionNoFb);
            }
        }
        if (list == null || list.size() <= 1) {
            throw new RuntimeException("错误,至少要填写两个单晶编号");
        }
        //长度范围卡控
        //从数据字典获取长度范围卡控值
        Boolean flag = false;
        List<BigDecimal> rangeList = getRange(list.size());
        //去明细表查看单晶状态
        List<FbjoinDetail> detailCheckList = fbjoinDetailDao.getListBySectionNoFbListAndStatus(list, SceneEnumValues.FbJoinStatus.未解绑.getValue());
        if (detailCheckList != null && detailCheckList.size() > 0) {
            String sectionNoFbError = "";
            for (FbjoinDetail entity : detailCheckList) {
                sectionNoFbError += entity.getSectionNoFb() + ",";
            }
            throw new RuntimeException("错误," + sectionNoFbError + "等单晶已绑定");
        }
       /* //从方棒检验表获取方棒检验信息
        List<CheckOut> checkOutList = checkOutDao.getBySectionNoFbListLast(list);
        if (checkOutList == null || checkOutList.size() == 0) {
            throw new RuntimeException("错误,根据单晶编号获取方棒检验信息失败");
        }
        if (list.size() != checkOutList.size()) {
            String sectionNoFbError = "";
            for (String str : list) {
                if (!checkOutList.contains(str)) {
                    sectionNoFbError += str + ",";
                }
            }
            throw new RuntimeException("错误," + sectionNoFbError + "等单晶查不到方棒 检验信息");
        }
        //方棒产品等级卡控
        List<String> productLevelList = new ArrayList<>();
        //总长度
        BigDecimal totalLength = new BigDecimal(0);
        for (CheckOut checkOut : checkOutList) {
            if (!productLevelList.contains(checkOut.getProductLevelFb())) {
                productLevelList.add(checkOut.getProductLevelFb());
            }
            if (checkOut.getLength() != null) {
                totalLength = totalLength.add(checkOut.getLength());
            }
        }
        if (productLevelList.size() != 1) {
            throw new RuntimeException("错误,方棒产品等级不一致");
        }
        //棒长总和+（拼数-1）*3
        totalLength = totalLength.add(new BigDecimal((list.size() - 1) * 3));

        if (rangeList.size() == 2) {
            if (totalLength.compareTo(rangeList.get(0)) >= 0 && totalLength.compareTo(rangeList.get(1)) <= 0) {
                flag = true;
            }
        } else if (rangeList.size() == 4) {
            if ((totalLength.compareTo(rangeList.get(0)) >= 0 && totalLength.compareTo(rangeList.get(1)) <= 0) ||
                    (totalLength.compareTo(rangeList.get(2)) >= 0 && totalLength.compareTo(rangeList.get(3)) <= 0)) {
                flag = true;
            }
        }
        if (!flag) {
            throw new RuntimeException("错误,长度卡控不在范围内");
        }
        //主表数据保存
        Fbjoin fbjoinEntity = new Fbjoin();
        fbjoinEntity.setId(null);
        fbjoinEntity.setSectionNoFb(list.get(0));
        fbjoinEntity.setSectionNoGroup(StringUtils.join(list, ","));
        fbjoinEntity.setProductLevelFb(productLevelList.get(0));
        fbjoinEntity.setJoinCount(list.size());
        fbjoinEntity.setTheoryWeight(checkOutList.stream().map(e -> e.getTheoryWeight() == null ? new BigDecimal(0) : e.getTheoryWeight()).reduce(BigDecimal.ZERO, BigDecimal::add));
        fbjoinEntity.setTotalLength(checkOutList.stream().map(e -> e.getLength() == null ? new BigDecimal(0) : e.getLength()).reduce(BigDecimal.ZERO, BigDecimal::add));
        String lengthGroup = "";
        //List<BigDecimal> lengthList = new ArrayList<>();
        for (String str : list) {
            CheckOut checkOut = checkOutList.stream().filter(o -> o.getSectionNoFb().trim().equalsIgnoreCase(str.trim())).findAny().orElse(null);
            if (checkOut != null) {
                //lengthList.add(checkOut.getLength()==null?new BigDecimal(0):checkOut.getLength());
                lengthGroup += checkOut.getLength() == null ? "0.00," : checkOut.getLength().toString() + ",";
            }
        }
        if (lengthGroup.contains(",")) {
            lengthGroup = lengthGroup.substring(0, lengthGroup.length() - 1);
        }
        //lengthGroup= StringUtils.join(lengthList,",");
        fbjoinEntity.setLengthGroup(lengthGroup);
        fbjoinEntity.setBindUser(BaseContextHandler.getUsername());
        Date nowTime = new Date();
        fbjoinEntity.setBindTime(nowTime);
        fbjoinEntity.setStatus(SceneEnumValues.FbJoinStatus.未解绑.getValue());
        dao.save(fbjoinEntity);
        //明细表数据保存
        List<FbjoinDetail> fbjoinDetailList = new ArrayList<>();
        for (CheckOut checkOut : checkOutList) {
            FbjoinDetail fbjoinDetailEntity = new FbjoinDetail();
            fbjoinDetailEntity.setId(null);
            fbjoinDetailEntity.setFbjoinId(fbjoinEntity.getId());
            fbjoinDetailEntity.setSectionNoFb(checkOut.getSectionNoFb());
            fbjoinDetailEntity.setStatus(SceneEnumValues.FbJoinStatus.未解绑.getValue());
            fbjoinDetailEntity.setCheckOutId(checkOut.getId());
            fbjoinDetailList.add(fbjoinDetailEntity);
        }
        fbjoinDetailDao.saveAll(fbjoinDetailList);*/
    }

    public List<BigDecimal> getRange(Integer joinCount) {
        List<BigDecimal> list = new ArrayList<>();
        List<DictionaryItem> dictionaryItemList = dictionaryItemDao.findByThemeValueAndEnable("JoinFbLengthRange", true);
        DictionaryItem dictionaryItem = dictionaryItemList.stream().filter(o -> o.getName().equalsIgnoreCase(joinCount.toString())).findAny().orElse(null);
        if (dictionaryItem == null) {
            throw new RuntimeException("错误," + joinCount.toString() + "拼无法找到数据字典长度卡控");
        }
        String val = dictionaryItem.getValue();
        if (StringUtils.isBlank(val)) {
            throw new RuntimeException("错误," + joinCount.toString() + "拼数据字典卡控格式错误");
        }
        String[] val1 = val.split(";");
        for (String str1 : val1) {
            if (str1.contains("-")) {
                String[] val2 = str1.split("-");
                if (val2.length == 2) {
                    for (String str2 : val2) {
                        list.add(new BigDecimal(str2));
                    }
                } else {
                    continue;
                }

            } else {
                continue;
            }
        }
        if (list.size() == 2 || list.size() == 4) {
            return list;
        } else {
            throw new RuntimeException("错误," + joinCount.toString() + "拼数据字典卡控格式错误");
        }
    }
}
