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


import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.yb.production.dto.LoadingTask.LoadingTaskDto;
import com.sw.mes.yb.production.dto.LoadingTask.LoadingTaskLogDto;
import com.sw.mes.yb.production.entity.*;
import com.sw.mes.yb.production.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.modelmapper.ModelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sw.mes.yb.production.dao.LoadingTaskLogDao;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


/**
* @Author
* @Description：
* @Date: Create in
* @Modified By:
 */
@Service
@Transactional
public class LoadingTaskLogServiceImpl extends BaseServiceImpl<LoadingTaskLog> implements LoadingTaskLogService {
    @Autowired
    ModelMapper modelMapper;
    @Autowired
    BlastFurnaceDetailService blastFurnaceDetailService;
    @Autowired
    BlastFurnaceDetailLogService blastFurnaceDetailLogService;
    @Autowired
    LoadingTaskService loadingTaskService;

    LoadingTaskLogDao dao;

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

    @Override
    public LoadingTaskLog saveByLoadingTask(LoadingTask entity) {
        LoadingTaskLog loadingTaskLog = modelMapper.map(entity, LoadingTaskLog.class);
        if (entity.getRawStatus() != LoadingTaskDto.rawStatus_0 && entity.getRawStatus() != LoadingTaskDto.rawStatus_6) {
//            LoadingTaskLog loadingTaskLogOld = dao.findByLotNoWithRecipeUserName(entity.getLotNo());
//            if(null != loadingTaskLogOld){
//            	loadingTaskLog.setId(loadingTaskLogOld.getId());
//                loadingTaskLog.setRecipeUserName(loadingTaskLogOld.getRecipeUserName());
//                loadingTaskLog.setRecipeTime(loadingTaskLogOld.getRecipeTime());
//            }else{
                loadingTaskLog.setRecipeUserName(entity.getUserName());
                loadingTaskLog.setRecipeTime(entity.getOperationTime());
                loadingTaskLog.setLoadingTaskId(entity.getId());
//            }

            saveOrUpdate(loadingTaskLog);


            blastFurnaceDetailLogService.deleteByLoadingTaskId(entity.getId());


            List<BlastFurnaceDetail> blastFurnaceDetailList = blastFurnaceDetailService.getBlastFurnaceDetailList(entity.getId());
            if (blastFurnaceDetailList != null && blastFurnaceDetailList.size()>0){
                for (BlastFurnaceDetail blastFurnaceDetail : blastFurnaceDetailList) {
                    BlastFurnaceDetailLog blastFurnaceDetailLog = modelMapper.map(blastFurnaceDetail, BlastFurnaceDetailLog.class);
                    blastFurnaceDetailLog.setId(null);
                    blastFurnaceDetailLogService.saveOrUpdate(blastFurnaceDetailLog);
                }
            }
        }
        return loadingTaskLog;
    }

    /**
     * 导出配料明细
     *
     * @param request
     * @param resp
     */
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse resp) {
        Specification<LoadingTaskLog> specification = DynamicSpecifications.bySearchFilter(request, LoadingTaskLog.class);
        List<LoadingTaskLog> loadingTaskLogs = this.findByExampleSort(specification, null);
        List<LoadingTaskLogDto> dtos = loadingTaskLogs.stream()
                .map(loadingTaskLog -> toLazyDto(loadingTaskLog))
                .collect(Collectors.toList());
        List<LoadingTaskLogDto> exprotDtos = new ArrayList<>();
        for (LoadingTaskLogDto dto : dtos) {
            LoadingTask loadingTask = loadingTaskService.get(dto.getLoadingTaskId());
            if (null != loadingTask) {
                dto.setHjPlate(loadingTask.getAlloyBrand());
                dto.setHjType(loadingTask.getAlloyType());
                dto.setHjWeight(loadingTask.getAlloyWeight());
                dto.setBfWeight(loadingTask.getBariumWeight());
            }
            List<BlastFurnaceDetailLog> blastFurnaceDetailLogs = blastFurnaceDetailLogService.findByBlastFurnaceId(dto.getLoadingTaskId());
            if (CollectionUtils.isNotEmpty(blastFurnaceDetailLogs)) {
                for (BlastFurnaceDetailLog blastFurnaceDetailLog : blastFurnaceDetailLogs
                ) {
                    LoadingTaskLogDto loadingTaskLogDto = new LoadingTaskLogDto();
                    BeanUtils.copyProperties(dto, loadingTaskLogDto);
                    loadingTaskLogDto.setItemNumber(blastFurnaceDetailLog.getProductCode());
//                    loadingTaskLogDto.setMaterial(blastFurnaceDetailLog.getMaterialCode());
                    if (null != blastFurnaceDetailLog.getMaterialName()){
                        loadingTaskLogDto.setMaterial(blastFurnaceDetailLog.getMaterialName());
                    }
                    loadingTaskLogDto.setBatch(blastFurnaceDetailLog.getBatchNo());
                    loadingTaskLogDto.setBrand(blastFurnaceDetailLog.getFactoryBrand());
                    loadingTaskLogDto.setZlWeight(blastFurnaceDetailLog.getWeight());
                    loadingTaskLogDto.setBucketForty(blastFurnaceDetailLog.getBucketForty());
                    loadingTaskLogDto.setBucketTen(blastFurnaceDetailLog.getBucketTen());
                    exprotDtos.add(loadingTaskLogDto);
                }
            }
        }
        try {
            getExportExcel(exprotDtos, request, resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public LoadingTaskLog getByLoadingTaskId(Long id) {
        return dao.getByLoadingTaskId(id);
    }

    @Override
    public List<LoadingTaskLog> findBylLoadingTaskId(Long id) {
        return dao.findBylLoadingTaskId(id);
    }

    public LoadingTaskLogDto toLazyDto(LoadingTaskLog entity) {
        return modelMapper.map(entity, LoadingTaskLogDto.class);
    }


    private void getExportExcel(List<LoadingTaskLogDto> list, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        if (list.isEmpty()) {
            return;
        }
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("导出装料任务记录");
        HSSFRow row;
        row = sheet.createRow(0);
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("设备编号");
        row.createCell(2).setCellValue("炉次号");
        row.createCell(3).setCellValue("任务类型");
        row.createCell(4).setCellValue("状态");
        row.createCell(5).setCellValue("产品规格");
        row.createCell(6).setCellValue("产品等级");
        row.createCell(7).setCellValue("掺杂剂");
        row.createCell(8).setCellValue("SAP订单号");
        row.createCell(9).setCellValue("产品料号");
        row.createCell(10).setCellValue("产品类别");
        row.createCell(11).setCellValue("装料重量");
        row.createCell(12).setCellValue("配料人");
        row.createCell(13).setCellValue("配料时间");
        row.createCell(14).setCellValue("操作原因");
        row.createCell(15).setCellValue("修改人");
        row.createCell(16).setCellValue("修改时间");

        //TODO 17~20 四个字段暂未确定
        row.createCell(17).setCellValue("合金牌号");
        row.createCell(18).setCellValue("合金类型");
        row.createCell(19).setCellValue("合金重量");
        row.createCell(20).setCellValue("钡粉重量");

        row.createCell(21).setCellValue("料号");
        row.createCell(22).setCellValue("物料名称");
        row.createCell(23).setCellValue("批次号");
        row.createCell(24).setCellValue("厂牌");
        row.createCell(25).setCellValue("重量");
//        row.createCell(26).setCellValue("箱数(40KG)");
//        row.createCell(27).setCellValue("箱数(10KG)");

        for (int i = 0; i < list.size(); i++) {
            row = sheet.createRow(i + 1);
            LoadingTaskLogDto loadingTaskLogDto = list.get(i);
            row.createCell(0).setCellValue(i + 1);
            if (loadingTaskLogDto.getEquipmentCode() != null) {
                row.createCell(1).setCellValue(loadingTaskLogDto.getEquipmentCode());
            }
            if (loadingTaskLogDto.getLotNo() != null) {
                row.createCell(2).setCellValue(loadingTaskLogDto.getLotNo());
            }
            if (loadingTaskLogDto.getRawType() != null) {
                row.createCell(3).setCellValue(loadingTaskLogDto.getRawType() == 0 ? "初始装料":loadingTaskLogDto.getRawType().toString());
            }
            if (loadingTaskLogDto.getRawStatus() != null) {
               String rawStatusName = "";
                switch (loadingTaskLogDto.getRawStatus()){
                    case 0:
                        rawStatusName = "新建";
                        break;
                    case 1:
                        rawStatusName = "生产";
                        break;
                    case 2:
                        rawStatusName = "已取消";
                        break;
                    case 3:
                        rawStatusName = "自动完工";
                        break;
                    case 4:
                        rawStatusName = "人工完工";
                        break;
                    case 5:
                        rawStatusName = "退料";
                        break;
                    case 6:
                        rawStatusName = "等待";
                        break;

                }
                row.createCell(4).setCellValue(rawStatusName);
            }
            if (loadingTaskLogDto.getSpecs() != null) {
                row.createCell(5).setCellValue(loadingTaskLogDto.getSpecs());
            }
            if (loadingTaskLogDto.getProductGrade() != null) {
                row.createCell(6).setCellValue(loadingTaskLogDto.getProductGrade());
            }
            if (loadingTaskLogDto.getDopant() != null) {
                row.createCell(7).setCellValue(loadingTaskLogDto.getDopant());
            }
            if (loadingTaskLogDto.getSapNo() != null) {
                row.createCell(8).setCellValue(loadingTaskLogDto.getSapNo());
            }
            if (loadingTaskLogDto.getProductCode() != null) {
                row.createCell(9).setCellValue(loadingTaskLogDto.getProductCode());
            }
            if (loadingTaskLogDto.getProductType() != null) {
                row.createCell(10).setCellValue(loadingTaskLogDto.getProductType());
            }
            if (loadingTaskLogDto.getRealWeight() != null) {
                row.createCell(11).setCellValue(loadingTaskLogDto.getRealWeight().doubleValue());
            }
            if (loadingTaskLogDto.getUserName() != null) {
                row.createCell(12).setCellValue(loadingTaskLogDto.getUserName());
            }
            if (loadingTaskLogDto.getOperationTime() != null) {
                row.createCell(13).setCellValue(DateUtil.formatDate(loadingTaskLogDto.getOperationTime(), DateUtil.longFormat));
            }
            if (loadingTaskLogDto.getOperationCause() != null) {
                row.createCell(14).setCellValue(loadingTaskLogDto.getOperationCause());
            }
            if (loadingTaskLogDto.getRecipeUserName() != null) {
                row.createCell(15).setCellValue(loadingTaskLogDto.getRecipeUserName());
            }
            if (loadingTaskLogDto.getRecipeTime() != null) {
                row.createCell(16).setCellValue(DateUtil.formatDate(loadingTaskLogDto.getRecipeTime(), DateUtil.longFormat));
            }
            if (loadingTaskLogDto.getHjPlate() != null) {
                row.createCell(17).setCellValue(loadingTaskLogDto.getHjPlate());
            }
            if (loadingTaskLogDto.getHjType() != null) {
                row.createCell(18).setCellValue(loadingTaskLogDto.getHjType());
            }
            if (null!=loadingTaskLogDto.getHjWeight()) {
                row.createCell(19).setCellValue(loadingTaskLogDto.getHjWeight().toString());
            }
            if (loadingTaskLogDto.getBfWeight() != null) {
                row.createCell(20).setCellValue(loadingTaskLogDto.getBfWeight().toString());
            }

            if (loadingTaskLogDto.getItemNumber() != null) {
                row.createCell(21).setCellValue(loadingTaskLogDto.getItemNumber());
            }
            if (loadingTaskLogDto.getMaterial() != null) {
                row.createCell(22).setCellValue(loadingTaskLogDto.getMaterial());
            }
            if (loadingTaskLogDto.getBatch() != null) {
                row.createCell(23).setCellValue(loadingTaskLogDto.getBatch());
            }
            if (loadingTaskLogDto.getBrand() != null) {
                row.createCell(24).setCellValue(loadingTaskLogDto.getBrand());
            }
            if (loadingTaskLogDto.getZlWeight() != null) {
                row.createCell(25).setCellValue(loadingTaskLogDto.getZlWeight().toString());
            }
//            if (loadingTaskLogDto.getBucketForty() != null) {
//                row.createCell(26).setCellValue(loadingTaskLogDto.getBucketForty());
//            }
//            if (loadingTaskLogDto.getBucketTen() != null) {
//                row.createCell(27).setCellValue(loadingTaskLogDto.getBucketTen());
//            }

        }
        sheet.setDefaultRowHeight((short) (20 * 20));
        //列宽自适应
        int num = 16;
        for (int i = 0; i <= num; i++) {
            sheet.autoSizeColumn(i);
        }
        String fileName = "配料记录表.xls";
        //乱码解决
        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            // win10 ie edge 浏览器 和其他系统的ie
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            // fe
            fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }
        //输出Excel文件
        OutputStream output = resp.getOutputStream();
        resp.reset();
        resp.setHeader("Content-disposition", "attachment; filename=" + fileName);
        resp.setContentType("application/msexcel");
        wb.write(output);
        output.flush();
        output.close();
    }
}
