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


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.context.BaseContextHandler;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.yb.fls.service.MesToFlsService;
import com.sw.mes.yb.fls.utils.FlsResultDto;
import com.sw.mes.yb.mcs.event.EventPublishService;
import com.sw.mes.yb.mcs.event.PlanWaterLineManageToWmsEvent;
import com.sw.mes.yb.mcs.service.YbMesToMcsService;
import com.sw.mes.yb.mcs.utils.ResultDto;
import com.sw.mes.yb.plan.dao.PlanWaterLineManageDao;
import com.sw.mes.yb.plan.dao.PlanWaterLineManageRecordDao;
import com.sw.mes.yb.plan.dto.PlanWaterLineManageObj;
import com.sw.mes.yb.plan.dto.PlanWaterLineManageToWmsDto;
import com.sw.mes.yb.plan.entity.PlanWaterLineManage;
import com.sw.mes.yb.plan.entity.PlanWaterLineManageRecord;
import com.sw.mes.yb.plan.service.PlanWaterLineManageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sw.mes.yb.mcs.service.YbMesToMcsService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Slf4j
@Service
@Transactional
public class PlanWaterLineManageServiceImpl extends BaseServiceImpl<PlanWaterLineManage> implements PlanWaterLineManageService {
    PlanWaterLineManageDao dao;

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

    @Autowired
    private PlanWaterLineManageRecordDao dao1;

    @Autowired
    @Qualifier("eventPublishService")
    private EventPublishService eventPublishService;

    @Autowired
    YbMesToMcsService mesToMcsService;

    @Autowired
    MesToFlsService mesToFlsService;

    @Override
    public List<PlanWaterLineManageRecord> findPlanWaterLineById(Long id) {
        return dao1.findPlanWaterLineById(id);
    }

    @Override
    public Result saveOrUpdateRecord(PlanWaterLineManageObj dto) {
        PlanWaterLineManage obj = new PlanWaterLineManage();
        if (dto.getId() != null) {
            obj.setId(dto.getId());
            obj.setWaterLineName(dto.getWaterLineName());
            obj.setCacheNum(dto.getCacheNum());
            obj.setUpdateUserName(BaseContextHandler.getUsername());
            obj.setUpdateTime(new Date());
//            obj.setStrategy(dto.getStrategy());
        } else {
            obj.setUserId(BaseContextHandler.getUserID());
            obj.setUserName(BaseContextHandler.getUsername());
            obj.setWaterLineName(dto.getWaterLineName());
            obj.setCacheNum(dto.getCacheNum());
            obj.setCreateTime(new Date());
//            obj.setStrategy(dto.getStrategy());
        }
        if (dto.getRecordList() != null) {
            List<PlanWaterLineManageRecord> list = dto.getRecordList();
            if (list.stream().mapToInt(PlanWaterLineManageRecord::getPercent).sum() != 100) {
                return ResultGenerator.fail("订单百分比填写有误");
            } else {
                dao.save(obj);
                dao1.deleteByFid(dto.getId());
                //下发水位线对象
                //==============================================================================
                //List<OrderConfigDto> orderConfigDtos = new ArrayList<>();
                //for (PlanWaterLineManageRecord planWaterLineManageRecord : list) {
                //    planWaterLineManageRecord.setPid(obj.getId());
                //    dao1.save(planWaterLineManageRecord);

//                //    //下发水位线信息对象
                //    OrderConfigDto orderConfigDto = new OrderConfigDto();
                //    orderConfigDto.setOrderNo(planWaterLineManageRecord.getAufnr());
                //    orderConfigDto.setCount(dto.getCacheNum() * planWaterLineManageRecord.getPercent() / 100);
                //    orderConfigDto.setArea(dto.getWaterLineName());
                //    orderConfigDtos.add(orderConfigDto);
                //}
                //==============================================================================变更原因：之前代码是下发给mcs，现在下发给wms，入参变化
                PlanWaterLineManageToWmsDto planWaterLineManageToWmsDto=new PlanWaterLineManageToWmsDto();
                //List<PlanWaterLineManageRecordToWmsDto>planWaterLineManageRecordToWmsDtoList=new ArrayList();
//                planWaterLineManageToWmsDto.setStrategy(dto.getStrategy());
                planWaterLineManageToWmsDto.setTotalNum(dto.getCacheNum());
                JSONArray jsonArray = new JSONArray();
                for (PlanWaterLineManageRecord planWaterLineManageRecord : list) {
                    //保存记录
                    planWaterLineManageRecord.setPid(obj.getId());
                    dao1.save(planWaterLineManageRecord);

                    JSONObject object = new JSONObject();
                    object.put("orderNo",planWaterLineManageRecord.getAufnr());
                    object.put("percentage",planWaterLineManageRecord.getPercent());
                    // 优先级
                    object.put("priorityValue",planWaterLineManageRecord.getPriorityValue());
                    object.put("specs",planWaterLineManageRecord.getSpecs());
                    object.put("onceNum",planWaterLineManageRecord.getOnceNum());
                    object.put("sideLengthRange",planWaterLineManageRecord.getSideLengthRange());
                    jsonArray.add(object);
//                    PlanWaterLineManageRecordToWmsDto planWaterLineManageRecordToWmsDto=new PlanWaterLineManageRecordToWmsDto();
//                    planWaterLineManageRecordToWmsDto.setOrderNo(planWaterLineManageRecord.getAufnr());
//                    planWaterLineManageRecordToWmsDto.setPercentage(planWaterLineManageRecord.getPercent());
//                    planWaterLineManageRecordToWmsDtoList.add(planWaterLineManageRecordToWmsDto);
                }
                planWaterLineManageToWmsDto.setDetails(jsonArray);
                // 点位
                planWaterLineManageToWmsDto.setPoint(dto.getWaterLineName());
                //==============================================================================
                if (planWaterLineManageToWmsDto!=null) {
                    try {
                        //eventPublishService.publishEvent(new OrderConfigEvent(this, orderConfigDtos));
                        //eventPublishService.publishEvent(new PlanWaterLineManageToWmsEvent(this, planWaterLineManageToWmsDto));
                        FlsResultDto resultDto = mesToFlsService.planWaterLineManageToWmsDto(planWaterLineManageToWmsDto);
                        // ResultDto resultDto = mesToMcsService.planWaterLineManageToWmsDto(planWaterLineManageToWmsDto);
                        if (resultDto == null || resultDto.getCode() == null || resultDto.getCode() != 200) {
                            return ResultGenerator.fail(resultDto.getMessage());
                        }
                    } catch (Exception e) {
                        log.error("水位线信息下发");
                    }
                }
                return ResultGenerator.success();
            }
        } else {
            return ResultGenerator.fail("详细信息不能为空");
        }
    }

    @Override
    public PlanWaterLineManageRecord selectOneOrder(String dopant, String conductiveType,String specs, String productType) {
        return dao1.selectOneOrder(dopant,  conductiveType,  specs, productType);
    }

    @Override
    public List<PlanWaterLineManageRecord> selectAllOrder(String dopant, String conductiveType,String specs, String ybProductGrade, String resLevel, String SideLengthRange) {
        return dao1.selectAllOrder(dopant,  conductiveType,  specs, ybProductGrade, resLevel, SideLengthRange);
    }

    @Override
    public List<PlanWaterLineManageRecord> selectOrders(String dopant, String conductiveType, String specs, String sideLengthRange, String ybLevel, String resLevel) {
        return dao1.selectOrders(dopant, conductiveType, specs, sideLengthRange, ybLevel, resLevel);
    }
}
