package com.sw.mes.production.controller;

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

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.nacos.common.utils.CollectionUtils;
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.context.BaseContextHandler;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.response.ResponsePage;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.BeanUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.core.utils.EasyExcelUtils;
import com.sw.mes.core.utils.PageUtil;
import com.sw.mes.core.utils.RequestPage;
import com.sw.mes.core.utils.StringUtils;
import com.sw.mes.production.dto.TruncationReccutCDto;
import com.sw.mes.production.dto.TruncationReccutDetailsDto;
import com.sw.mes.production.dto.TruncationReccutDto;
import com.sw.mes.production.entity.TruncationReccut;
import com.sw.mes.production.entity.TruncationReccutDetails;
import com.sw.mes.production.service.TruncationReccutDetailsService;
import com.sw.mes.production.service.TruncationReccutService;
import com.sw.mes.yb.pad.entity.ProductionBackCuttingRecord;
import com.sw.mes.yb.pad.entity.ProductionPaintingLine;
import com.sw.mes.yb.pad.entity.ProductionPaintingLineDetail;
import com.sw.mes.yb.pad.service.ProductionPaintingLineDetailService;
import com.sw.mes.yb.pad.service.ProductionPaintingLineService;
import com.sw.mes.yb.pad.service.ProductionRecutService;
import com.sw.mes.yb.production.entity.LongCrystal;
import com.sw.mes.yb.production.service.LongCrystalService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@RestController
@RequestMapping("/truncationReccut")
@Slf4j
@Api(description = "截断反切接口")
public class TruncationReccutController {
    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private TruncationReccutService truncationReccutService;

    @Autowired
    private TruncationReccutDetailsService truncationReccutDetailsService;

    @Autowired
    private ProductionPaintingLineService productionPaintingLineService;

    @Autowired
    private ProductionPaintingLineDetailService productionPaintingLineDetailService;

    @Autowired
    private WipStorageService wipStorageService;

    @Autowired
    private LongCrystalService longCrystalService;
    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;
    
    @Autowired
    private ProductionRecutService productionRecutService;

    @ApiOperation(value = "分页查询截断反切列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "rows", value = "行数", dataType = "integer", paramType = "query"), @ApiImplicitParam(name = "page", value = "页码", dataType = "integer", paramType = "query"),})
    @GetMapping("/listByPage")
    public Result<ResponsePage<TruncationReccutDto>> listByPage(ServletRequest request, @ApiIgnore RequestPage requestPage) {
        Specification<TruncationReccut> specification = DynamicSpecifications.bySearchFilter(request, TruncationReccut.class);
        Page<TruncationReccut> page = truncationReccutService.findByExample(specification, PageUtil.createPageable(requestPage));
        List<TruncationReccutDto> dtos = page.getContent().stream().map(entity -> toLazyDto(entity)).collect(Collectors.toList());
        ResponsePage responsePage = new ResponsePage(dtos, page.getTotalElements());
        return ResultGenerator.success(responsePage);
    }

    @ApiOperation(value = "获取所有截断反切")
    @GetMapping("/listAll")
    public Result<List<TruncationReccutDto>> listAll(ServletRequest request) {
        Specification<TruncationReccut> specification = DynamicSpecifications.bySearchFilter(request, TruncationReccut.class);
        List<TruncationReccut> truncationReccuts = truncationReccutService.findByExampleSort(specification, null);
        List<TruncationReccutDto> truncationReccutDtos = truncationReccuts.stream().map(entity -> toLazyDto(entity)).collect(Collectors.toList());
        return ResultGenerator.success(truncationReccutDtos);
    }

    @ApiOperation(value = "截断反切导出(最多可导出1W条)")
    @GetMapping("/export")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "search_GTE_gmtCreate", value = "开始时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "search_LTE_gmtCreate", value = "结束时间", dataType = "String", paramType = "query"),
    })
    public void export(ServletRequest request, HttpServletResponse response) {
        try {
            RequestPage requestPage = new RequestPage();
            requestPage.setRows(10000);
            Specification<TruncationReccut> specification = DynamicSpecifications.bySearchFilter(request, TruncationReccut.class);
            Page<TruncationReccut> page = truncationReccutService.findByExample(specification, PageUtil.createPageable(requestPage));
            List<TruncationReccutDto> dtos = page.getContent().stream().map(entity -> toLazyDto(entity)).collect(Collectors.toList());
            EasyExcelUtils.write(response, TruncationReccutDto.class, "截断反切导出", "截断反切导出", dtos);
        } catch (Exception e) {
            throw new RuntimeException("截断反切记录导出失败，错误信息：" + e.getMessage());
        }
    }

    @ApiOperation(value = "截断反切详细信息")
    @GetMapping("/{id}")
    public Result<TruncationReccutDto> get(@PathVariable @ApiParam(value = "截断反切id") Long id) {
        TruncationReccut truncationReccut = truncationReccutService.get(id);
        if (null == truncationReccut) return ResultGenerator.fail("该截断反切不存在");
        return ResultGenerator.success(toEagerDto(truncationReccut));
    }

    @ApiOperation(value = "创建截断反切")
    @PostMapping("/create")
    public Result<List<String>> create(@RequestBody @Valid @ApiParam(value = "截断反切对象") TruncationReccutCDto truncationReccutcDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        
        ProductionPaintingLineDetail lineDetail = productionPaintingLineDetailService.getDetailByNo(truncationReccutcDto.getCrystalNo());
        if (lineDetail == null) {
            return ResultGenerator.fail("晶段信息不存在");
        }
        
        List<PlanProcessingOrder> planProcessingOrderList = planProcessingOrderService.findByCodeOrderByIdDesc(truncationReccutcDto.getCrystalNo());
        if (CollectionUtils.isNotEmpty(planProcessingOrderList)){
            WipStorage currentWipStorage = planProcessingOrderList.get(0).getWipStorage();
            if (null != currentWipStorage && StringUtils.equals(EnumValuesFactory.WipStorageCode.毛棒截断.getValue(),currentWipStorage.getProcessName())
                    && null != currentWipStorage.getStatus() && currentWipStorage.getStatus() == EnumValuesFactory.WipStorageStatus.已进站.getKey()){
                
            	LongCrystal longCrystal = null;
            	TruncationReccut truncationReccut = modelMapper.map(truncationReccutcDto, TruncationReccut.class);
                if(lineDetail.getCrystalId()!=null) {
                	longCrystal = longCrystalService.get(lineDetail.getCrystalId());
                	if(longCrystal!=null) {
                		truncationReccut.setSpecs(longCrystal.getSpecs());
                        truncationReccut.setCrysatlId(longCrystal.getId());
                	}
                }
                truncationReccut.setUserCreate(BaseContextHandler.getUsername());
                truncationReccut.setGmtCreate(new Date());
                List<TruncationReccutDetails> truncationReccutDetailss = new ArrayList<>();
                
                int totalLenth = 0;
                for (TruncationReccutDetailsDto truncationReccutDetailsDto : truncationReccutcDto.getTruncationReccutDetailsDtos()) {
                	TruncationReccutDetails truncationReccutDetails = modelMapper.map(truncationReccutDetailsDto, TruncationReccutDetails.class);
                    totalLenth += (truncationReccutDetails.getLength()==null?0:truncationReccutDetails.getLength());
                    truncationReccutDetailss.add(truncationReccutDetails);
				}
                
                
                //计算减掉晶段有效长度
                BigDecimal barLength = lineDetail.getLength();
                int length = barLength.intValue()-totalLenth;
                lineDetail.setLength(new BigDecimal(length));
                
                //多次录入截断反切累加
                int addOldLength = totalLenth;
                if(lineDetail.getCrackLength()!=null) {
                	addOldLength = totalLenth+lineDetail.getCrackLength().intValue();
                }
                lineDetail.setCrackLength(new BigDecimal(addOldLength));
                //保存计算后划线详情信息
                productionPaintingLineDetailService.saveOrUpdate(lineDetail);
                
                
                //保存圆棒反切记录
                ProductionBackCuttingRecord record = new ProductionBackCuttingRecord();
                record.setSegmentNo(lineDetail.getNo());
                record.setBarLength(barLength);
                record.setBackLength(lineDetail.getLength());
                record.setLineEndTime(new Date());
                record.setLineStartTime(truncationReccutcDto.getGmtCreate());
                record.setUserName(BaseContextHandler.getUsername());
                record.setCutLength(new BigDecimal(totalLenth));
                record.setCause(truncationReccut.getCause());
                record.setKnifeNum(truncationReccutcDto.getTruncationReccutDetailsDtos().size());
                record.setStatus(false);
                record.setBackCutType(4);
                record.setLogType("JDFQ");
                record.setTeamGroup(BaseContextHandler.getUserTeamGroup());
                record.setClassNo(BaseContextHandler.getUserClassNo());
                productionRecutService.saveOrUpdate(record);

                try {
                    return ResultGenerator.success(truncationReccutService.save(truncationReccut, truncationReccutDetailss, longCrystal));
                } catch (Exception e) {
                    e.printStackTrace();
                    return ResultGenerator.fail("信息创建失败，请重试");
                }
            }
        }
        
        return ResultGenerator.fail("该晶段不在毛棒截断,不支持截断反切");
        
    }

    @ApiOperation(value = "更新截断反切")
    @PostMapping("/update")
    public Result update(@RequestBody @Valid @ApiParam(value = "截断反切") TruncationReccutDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        if (dto.getId() == null) {
            return ResultGenerator.fail("id不能为空");
        }
        TruncationReccut entity = truncationReccutService.get(dto.getId());
        if (entity == null) {
            return ResultGenerator.fail("原信息不存在");
        }
        try {
            TruncationReccut entityfromFto = fromDto(dto);
            BeanUtils.copyProperties(entityfromFto, entity, BeanUtil.getIgnoreProperties(entityfromFto, null, null));
            truncationReccutService.saveOrUpdate(entity);
            return ResultGenerator.success();
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    /**
     * 生成截断反切回收料编号
     *
     * @param truncationReccutcDto 反切
     * @param bindingResult
     * @return
     */
    @ApiOperation(value = "生成截断反切回收料编号")
    @PostMapping("/getSectionNos")
    public Result<TruncationReccutCDto> getSectionNos(@RequestBody @Valid @ApiParam(value = "截断反切") TruncationReccutCDto truncationReccutcDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultGenerator.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        
        ProductionPaintingLineDetail lineDetail = productionPaintingLineDetailService.getDetailByNo(truncationReccutcDto.getCrystalNo());
        if (lineDetail == null) {
            return ResultGenerator.fail("晶段信息不存在");
        }
        
        ProductionPaintingLine line = productionPaintingLineService.get(lineDetail.getOperateDrawId());
        
        List<PlanProcessingOrder> planProcessingOrderList = planProcessingOrderService.findByCodeOrderByIdDesc(line.getCrystalNo());
        if (CollectionUtils.isNotEmpty(planProcessingOrderList)){
            WipStorage currentWipStorage = planProcessingOrderList.get(0).getWipStorage();
            if (null != currentWipStorage && StringUtils.equals(EnumValuesFactory.WipStorageCode.毛棒截断.getValue(),currentWipStorage.getProcessName())
                    && null != currentWipStorage.getStatus() && currentWipStorage.getStatus() == EnumValuesFactory.WipStorageStatus.已进站.getKey()){
                
            	//毛棒截断站点才能继续流程
            	int lengthCount = 0;
                int count = 0;
                for (TruncationReccutDetailsDto truncationReccutDetailsDto : truncationReccutcDto.getTruncationReccutDetailsDtos()) {
                    lengthCount += truncationReccutDetailsDto.getLength();
                    count ++;
                    truncationReccutDetailsDto.setSectionNo(truncationReccutcDto.getCrystalNo() + "0" + count);
                }
                truncationReccutcDto.setCutLenght(lengthCount);
                truncationReccutcDto.setGmtCreate(new Date());
                if (lengthCount > lineDetail.getLength().intValue()) {
                    return ResultGenerator.fail("反切总长度不能大于划线有效长度");
                }
                return ResultGenerator.success(truncationReccutcDto);
            }
        }
        
        return ResultGenerator.fail("当前晶段不在毛棒截断,不循序截断反切");
    }

    @ApiOperation(value = "删除截断反切")
    @PostMapping("/delete")
    public Result remove(@ApiParam(value = "id集合,逗号分隔,如2,4", type = "query") @RequestParam Long[] ids) {
        for (Long id : ids) {
            truncationReccutService.deleted(id);
        }
        return ResultGenerator.success();
    }

    public TruncationReccutDto toLazyDto(TruncationReccut entity) {
        return modelMapper.map(entity, TruncationReccutDto.class);
    }

    public TruncationReccutDto toEagerDto(TruncationReccut entity) {
        TruncationReccutDto dto = modelMapper.map(entity, TruncationReccutDto.class);
        return dto;
    }

    public TruncationReccut fromDto(TruncationReccutDto dto) {
        return modelMapper.map(dto, TruncationReccut.class);
    }


}
