/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.youchain.basicdata.service.impl;

import com.youchain.basicdata.domain.*;
import com.youchain.basicdata.repository.AreaRepository;
import com.youchain.basicdata.repository.BigItemRepository;
import com.youchain.basicdata.repository.BillTypeRepository;
import com.youchain.businessdata.domain.PlanPickDetail;
import com.youchain.businessdata.domain.Spareparts;
import com.youchain.businessdata.inputJson.buttenJson.ManualGeneration;
import com.youchain.businessdata.inputJson.buttenJson.ProductionPlanButton;
import com.youchain.businessdata.repository.PlanPickDetailRepository;
import com.youchain.businessdata.service.PlanPickDetailService;
import com.youchain.businessdata.service.SparepartsService;
import com.youchain.exception.BadRequestException;
import com.youchain.utils.*;
import lombok.RequiredArgsConstructor;
import com.youchain.basicdata.repository.ProductionPlanRepository;
import com.youchain.basicdata.service.ProductionPlanService;
import com.youchain.basicdata.service.dto.ProductionPlanDto;
import com.youchain.basicdata.service.dto.ProductionPlanQueryCriteria;
import com.youchain.basicdata.service.mapstruct.ProductionPlanMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.YearMonth;
import java.util.*;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletResponse;

/**
 * @author JiangKun
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2024-01-04
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class ProductionPlanServiceImpl implements ProductionPlanService {

    private final ProductionPlanRepository productionPlanRepository;
    private final ProductionPlanMapper productionPlanMapper;
    private final BillTypeRepository billTypeRepository;
    private final PlanPickDetailRepository planPickDetailRepository;
    private final PlanPickDetailService planPickDetailService;
    private final CodeUtils codeUtils;
    private final EntityManager entityMapper;
    private final SparepartsService sparepartsService;
    private final BigItemRepository bigItemRepository;
    private final AreaRepository areaRepository;

    @Override
    public Map<String, Object> queryAll(ProductionPlanQueryCriteria criteria, Pageable pageable) {
        Page<ProductionPlan> page = productionPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        return PageUtil.toPage(page.map(productionPlanMapper::toDto));
    }

    @Override
    public List<ProductionPlanDto> queryAll(ProductionPlanQueryCriteria criteria) {
        return productionPlanMapper.toDto(productionPlanRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    @Override
    @Transactional
    public ProductionPlanDto findById(Long id) {
        ProductionPlan productionPlan = productionPlanRepository.findById(id).orElseGet(ProductionPlan::new);
        ValidationUtil.isNull(productionPlan.getId(), "ProductionPlan", "id", id);
        return productionPlanMapper.toDto(productionPlan);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ProductionPlanDto create(ProductionPlan resources) {
        return productionPlanMapper.toDto(productionPlanRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ProductionPlan resources) {
        ProductionPlan productionPlan = productionPlanRepository.findById(resources.getId()).orElseGet(ProductionPlan::new);
        ValidationUtil.isNull(productionPlan.getId(), "ProductionPlan", "id", resources.getId());
        productionPlan.copy(resources);
        productionPlanRepository.save(productionPlan);
    }

    @Override
    public void deleteAll(Long[] ids) {
        for (Long id : ids) {
            productionPlanRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<ProductionPlanDto> all, HttpServletResponse response) throws Exception {
        List<Map<String, Object>>  list=ExcelDownUtils.CreateMap(all,"ProductionPlan");
        FileUtil.downloadExcel(list, response);
    }
    @Override
    public String manualGenerationSavePlanPick(List<ProductionPlan> plans, int num, String batch, AutomaticPlanDetail detail, Boolean isLast, Timestamp batchTime) {
        //获取最新单号
        String code =  codeUtils.getCode_yyMMdd("JH-",3);
        List<PlanPickDetail> ppd_his = planPickDetailRepository.findByCode(code);
        if(ppd_his.size()>0){
            throw new BadRequestException(code+"单号已存在");
        }
        BillType billType = billTypeRepository.findByName(BaseStatus.BT_DD);
        for (int i = 0; i < num; i++) {
            ProductionPlan p = plans.get(i);
            PlanPickDetail ppd = planPickDetailRepository.findPlanPickData(code, p.getBigItem().getId());
            if (!Objects.isNull(ppd)) {
                //备货数量
                ppd.setOrderQuantity(ppd.getOrderQuantity() + 1d);
                ppd.setEndNo(p.getMachineNo());
                planPickDetailService.update(ppd);
            }else {
                ppd = new PlanPickDetail();
                ppd.setBigItem(p.getBigItem());
                ppd.setStartNo(p.getMachineNo());
                ppd.setEndNo(p.getMachineNo());
                ppd.setOrderQuantity(1d);//每次叫料加上对应的铺线数量
                ppd.setZone(p.getRkArea());
                ppd.setBillType(billType);
                ppd.setCode(code);
                ppd.setRemark(batch);
                ppd.setBatchTime(batchTime);
                ppd.setGcCode(p.getRkArea().getGcCode());
                ppd.setPxDetailId(detail.getId());
                ppd.setIsLast(isLast);
                planPickDetailService.create(ppd);
            }
            p.setProjectNo(code);
            this.update(p);
        }
        return code;
    }

    @Override
    public List<ProductionPlan> piLiangHaoYong(ProductionPlanVo productionPlanVo) {
        Long id = productionPlanVo.getId();
        Integer number = productionPlanVo.getNumber();
        String hql = " from ProductionPlan t where t.id >="+id+"and t.rkArea.id = "+productionPlanVo.getAreaId()+" and t.statue='UN_CONSUME' order by t.id ASC";
        Query query = entityMapper.createQuery(hql);
        query.setMaxResults(number);
        List<ProductionPlan> resultList = query.getResultList();
        if (!resultList.isEmpty()){
            return resultList;
        }
        return  null;
    }

    public HashMap<String,String> getEndIdNO(String gw,int qty){
        List<ProductionPlan> minList = productionPlanRepository.getLimitPlan(gw,1);
        HashMap<String,String> map=new HashMap<>();
        if(minList.size()<=0){
            map.put("startNum","无数据");
            map.put("endNum","无数据");

        }else{
            ProductionPlan minPlan=minList.get(0);

            String startNum=minPlan.getIdno();
            log.info("startNum"+startNum);
            String qz=startNum.substring(0,4);
            String sz=startNum.substring(4,startNum.length());
            String endNum=qz+String.format("%0"+sz.length()+"d",Integer.parseInt(sz)+qty-1);
            map.put("startNum",startNum);
            map.put("endNum",endNum);
        }
        return map;

    }
    public void scsxHaoyong(List<ProductionPlan> productionPlans,Long areaId,String des){
        for (ProductionPlan productionPlan: productionPlans){
            if(!productionPlan.getStatue().equals(BizStatus.UN_CONSUME)){
                throw new BadRequestException(productionPlan.getIdno()+"状态不正确，不能重复耗用");
            }
            productionPlan.setStatue(BizStatus.CONSUME);
            productionPlan.setTakeUpTime(new Timestamp(new Date().getTime()));
            this.update(productionPlan);
        }
        Map<String,Integer> map = new HashMap<>();
        Map<String,String> mapIds = new HashMap<>();
        for(ProductionPlan productionPlan : productionPlans){
            Long id = productionPlan.getBigItem().getId();
            String kyqz=productionPlan.getIdno()==null?null:productionPlan.getIdno().substring(0,2);
            String key=id+"]"+kyqz;

            if(map.containsKey(key)){
                map.put(key,map.get(key)+1);
                mapIds.put(key,mapIds.get(key)+","+productionPlan.getId());
            }else {
                map.put(key,1);
                mapIds.put(key,productionPlan.getId()+"");
            }
        }
        for(String key : map.keySet()){
            Spareparts spareparts = new Spareparts();
            Area area=areaRepository.getById(areaId);
            spareparts.setStationType(area.getWorkingStation());
            spareparts.setShArea(area);
            spareparts.setStatus("UN_CONSUME");
            spareparts.setDate(new Timestamp(new Date().getTime()));
            String[] str=key.split("]");
            spareparts.setKyQz(str[1]);
            spareparts.setSourceId(mapIds.get(key));
            BigItem bigItem = bigItemRepository.getById(Long.parseLong(str[0]));
//            bigItem.setId(key);
            spareparts.setBigItemId(bigItem);
            spareparts.setOrderQuantity(map.get(key));
            spareparts.setDescription(des);
            sparepartsService.create(spareparts);

            //自动耗用
            sparepartsService.hySpareParts(spareparts.getId());
        }
    }
}