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



import com.sw.mes.core.api.auth.AuthFeignClient;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.dto.Convert;
import com.sw.mes.core.dto.auth.UserDto;
import com.sw.mes.core.enums.EnumValues;
import com.sw.mes.core.response.Result;
import com.sw.mes.yb.accessory.dao.AccessoryMaterialOutDao;
import com.sw.mes.yb.accessory.dto.EquipAccessCreateDto;
import com.sw.mes.yb.accessory.dto.EquipmentAccessoryListByPageDto;
import com.sw.mes.yb.accessory.entity.*;
import com.sw.mes.yb.accessory.service.*;
import com.sw.mes.yb.production.entity.EquipmentExtendState;
import com.sw.mes.yb.production.service.EquipmentExtendStateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;


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

    @Autowired
    private AccessoryApplyService accessoryApplyService;

	@Autowired
    private AccessoryOrderService accessoryOrderService;

	@Autowired
    private AuthFeignClient authFeignClient;

	@Autowired
    private EquipmentAccessoryService equipmentAccessoryService;

	@Autowired
    private AccessoryReturnService accessoryReturnService;

    @Override
    public AccessoryMaterialOut findByUniqueCode(String goodsCode) {
        List<AccessoryMaterialOut> list = dao.findByUniqueCodeOrderByIdDesc(goodsCode);
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void saveMaterialOut(AccessoryMaterialOut accessoryMaterialOut) {
        saveOrUpdate(accessoryMaterialOut);

        AccessoryApply accessoryApply = accessoryApplyService.findByPickNo(accessoryMaterialOut.getPickNo());
        if (accessoryApply == null){
            throw new RuntimeException("要料单号"+accessoryMaterialOut.getPickNo()+"有误");
        }

        if (EnumValues.PickInfoStatus.REJECTED.getKey().equals(accessoryApply.getState())){
            throw new RuntimeException("辅料要料申请"+accessoryMaterialOut.getPickNo()+"已拒绝！无法发料！");
        }

        if (EnumValues.PickInfoStatus.ENDDING.getKey().equals(accessoryApply.getState())){
            throw new RuntimeException("辅料要料申请"+accessoryMaterialOut.getPickNo()+"已出库！");
        }

        AccessoryReturn accessoryReturn = accessoryReturnService.findByAccessoryId(accessoryApply.getEquipmentAccessory().getId().intValue());
        if (accessoryReturn != null && EnumValues.AccessoryReturnStatus.REJECTED.getKey().equals(accessoryReturn.getState())){
            throw new RuntimeException("辅料退库申请"+accessoryReturn.getOrderNum()+"已拒绝！无法发料！");
        }

        String codes = accessoryApply.getMaterial().getCodes();

        if (!accessoryMaterialOut.getEquipment().getId().equals(accessoryApply.getEquipment().getId())) {
            throw new RuntimeException(accessoryMaterialOut.getPickNo()+"与所申请设备不同！");
        }

//        if (!accessoryMaterialOut.getProductNo().equals(codes)){
//            throw new RuntimeException(accessoryMaterialOut.getPickNo()+"与所申请辅料模型不同！");
//        }

        accessoryApply.setState(EnumValues.PickInfoStatus.ENDDING.getKey());
        accessoryApply.setStateDate(new Date());

        accessoryApplyService.saveOrUpdate(accessoryApply);

        Result<UserDto> user = authFeignClient.findByWorkNo(accessoryMaterialOut.getReceiverCode());

        EquipmentAccessory entity = accessoryApply.getEquipmentAccessory();

        //如果发料的料号与原监控料号不同，则生成新的监控
        if (entity.getMaterial().getCodes().equals(accessoryMaterialOut.getProductNo()) && entity.getNum() == 0) {
            AccessoryOrder order = new AccessoryOrder();
            order.setCreateDate(new Date());
            order.setCreateUser(accessoryMaterialOut.getReceiverName());
            order.setUserClassNo(accessoryApply.getUserClassNo());
            order.setUserTeamGroup(accessoryApply.getUserTeamGroup());

            if (user == null || user.getData()==null){
                order.setCreateUserId(-1);
            }else {
                order.setCreateUserId(user.getData().getId());
            }

            order.setEquipment(entity.getEquipment());
            order.setOrg(entity.getMaterial());
            order.setTarget(accessoryMaterialOut.getMaterial());

            EquipmentAccessoryListByPageDto detail = equipmentAccessoryService.getDetail(entity.getId());
//        order.setOrgAttritionRate(detail == null ? null : detail.getAttritionRate());

            order.setUseTime(detail == null ? entity.getUseTime() : detail.getUseTime());
            order.setTargetUseTime(0D);

            order.setRemark("退料原因:"+ Optional.ofNullable(accessoryReturn).map(AccessoryReturn::getReason).orElse("")
                    +";要料原因:"+ Optional.ofNullable(accessoryApply).map(AccessoryApply::getReason).orElse(""));
            order.setOrgFactory(entity.getFactory());
            order.setTargetFactory(accessoryMaterialOut.getSupplierName());
            order.setOrgGoodsCode(entity.getGoodsCode());
            order.setTargetGoodsCode(accessoryMaterialOut.getUniqueCode());
            order.setOrgBatchNo(entity.getBatchNo());
            order.setTargetBatchNo(accessoryMaterialOut.getBatchNum());

            order.setApplyUser("");
            order.setApplyDate(null);

            //更换数量
            order.setChangeCount(accessoryMaterialOut.getNum());
            order.setDeviceNo(entity.getDeviceNo());

            order.setOrgEngraving(entity.getEngraving());
            order.setTargetEngraving(accessoryMaterialOut.getEngraving());
            order.setOrgCarbonFelt(entity.getCarbonFelt());
            order.setTargetCarbonFelt(accessoryMaterialOut.getCarbonFelt());

            accessoryOrderService.saveOrUpdate(order);

            entity.setAccessoryMaterialOut(accessoryMaterialOut);
            entity.setUnitName(accessoryMaterialOut.getUnitName());
            entity.setBind(1);
            entity.setFactory(accessoryMaterialOut.getSupplierName());
            entity.setGoodsCode(accessoryMaterialOut.getUniqueCode());
            entity.setWarning(accessoryMaterialOut.getMaterial().getWarning());
            entity.setWarnTime(accessoryMaterialOut.getMaterial().getWarnTime());
            entity.setUseLife(accessoryMaterialOut.getMaterial().getUseLife());
            entity.setUseTime(accessoryMaterialOut.getUseTime());
            entity.setUsedTime(0d);
            entity.setNum(entity.getNum() + accessoryMaterialOut.getNum());
            entity.setBatchNo(accessoryMaterialOut.getBatchNum());
            entity.setMaterial(accessoryMaterialOut.getMaterial());

            entity.setEngraving(accessoryMaterialOut.getEngraving());
            entity.setCarbonFelt(accessoryMaterialOut.getCarbonFelt());
            entity.setAccessoryType(accessoryMaterialOut.getAccessoryType());
            entity.setRemark(accessoryMaterialOut.getReamrk());


            if (user == null || user.getData()==null) {
                entity.setOperateUserId(-1);
            }else {
                entity.setOperateUserId(user.getData().getId());
            }
            entity.setOperateUser(accessoryMaterialOut.getReceiverName());
            entity.setOperateDate(new Date());

            if (entity.getWarning()) { //TODO 可能需要改判定方式
                if (entity.getMaterial().getUseLife() == null || entity.getMaterial().getWarnTime() == null) {
                    throw new RuntimeException("辅料编号："+entity.getMaterial().getCodes()+"--额定寿命或预警寿命为空");
                }
                Integer time = entity.getMaterial().getUseLife().intValue() - entity.getUseTime().intValue() - entity.getMaterial().getWarnTime().intValue();
                Calendar date = Calendar.getInstance();
                date.setTime(entity.getOperateDate());
                date.add(Calendar.HOUR_OF_DAY, time);
                entity.setWarningDate(date.getTime());
            } else {
                entity.setWarningDate(null);
            }

            entity.setApplyDate(null);
            entity.setApplyUser("");
            entity.setButtonStatus(1);
            entity.setApplyButton(0);
            equipmentAccessoryService.saveOrUpdate(entity);
        }else {
            entity.setBind(1);
            entity.setApplyDate(null);
            entity.setApplyUser("");
            entity.setButtonStatus(1);
            entity.setApplyButton(0);
            equipmentAccessoryService.saveOrUpdate(entity);
            EquipAccessCreateDto dto = buildEquipAccessCreateDto(accessoryMaterialOut);
            equipmentAccessoryService.saveOrUpdate(dto);
        }
    }

    private EquipAccessCreateDto buildEquipAccessCreateDto(AccessoryMaterialOut accessoryMaterialOut) {
        EquipAccessCreateDto equipAccessCreateDto = new EquipAccessCreateDto();
        equipAccessCreateDto.setDeviceNo(accessoryMaterialOut.getDeviceNo());
        equipAccessCreateDto.setGoodsCode(accessoryMaterialOut.getUniqueCode());
        equipAccessCreateDto.setBatchNo(accessoryMaterialOut.getBatchNum());
        equipAccessCreateDto.setUseTime(Convert.toInt(accessoryMaterialOut.getUseTime()));
        equipAccessCreateDto.setMaterialId(Convert.toInt(accessoryMaterialOut.getMaterial().getId()));
        equipAccessCreateDto.setNum(accessoryMaterialOut.getNum());
        equipAccessCreateDto.setEngraving(accessoryMaterialOut.getEngraving());
        equipAccessCreateDto.setCarbonFelt(accessoryMaterialOut.getCarbonFelt());
        equipAccessCreateDto.setAccessoryType(accessoryMaterialOut.getAccessoryType());
        equipAccessCreateDto.setRemark(accessoryMaterialOut.getReamrk());

        return equipAccessCreateDto;
    }

    @Override
    public AccessoryMaterialOut findByPickNo(String pickNo) {
        List<AccessoryMaterialOut> list = dao.findByPickNo(pickNo);
        if (list.size() > 0){
            return list.get(0);
        }
        return null;
    }
}
