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


import com.alibaba.fastjson.JSON;
import com.sw.mes.base.workinprocess.entity.PlanProcessingOrder;
import com.sw.mes.base.workinprocess.service.PlanProcessingOrderService;
import com.sw.mes.core.base.BaseServiceImpl;
import com.sw.mes.core.entity.TurnstoreTrayItem;
import com.sw.mes.core.enums.EnumValuesFactory;
import com.sw.mes.core.response.Result;
import com.sw.mes.core.response.ResultGenerator;
import com.sw.mes.core.utils.DateUtil;
import com.sw.mes.core.utils.DynamicSpecifications;
import com.sw.mes.yb.turnstore.dao.TurnstoreTrayItemDao;
import com.sw.mes.yb.turnstore.dto.TurnstoreTrayItemDto;
import com.sw.mes.yb.turnstore.entity.TurnstoreTray;
import com.sw.mes.yb.turnstore.service.TurnstoreTrayItemService;
import com.sw.mes.yb.turnstore.service.TurnstoreTrayService;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author
 * @Description：
 * @Date: Create in
 * @Modified By:
 */
@Service
@Transactional
public class TurnstoreTrayItemServiceImpl extends BaseServiceImpl<TurnstoreTrayItem> implements TurnstoreTrayItemService {
    TurnstoreTrayItemDao dao;

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

    @Lazy
    @Autowired
    public TurnstoreTrayService turnstoreTrayService;

    @Autowired
    private PlanProcessingOrderService planProcessingOrderService;

    @Override
    public List<TurnstoreTrayItem> getItemsByTrayNo(String trayNo) {
        return dao.getItemsByTrayNo(trayNo);
    }

    @Override
    public List<TurnstoreTrayItem> getItemsByTrayId(Integer trayId) {
        return dao.getItemsByTrayId(trayId);
    }

    @Override
    /**
     * @Description 获取圆棒物料卡的信息
     * @Author Rj li
     * @Date 2020/12/21 14:58
     * @Param [trayId]
     * @Return java.util.List<com.sw.mes.turnstore.dto.TurnstoreTrayItemDto>
     */
    public Result getTurnstoreTrayItemDto(Integer trayId) {
        // 创建返回结果集
        Result<List<TurnstoreTrayItemDto>> result = new Result<>();
        try {
            // 调用dao 获取到对应结果集
            List<Map<String, Object>> itemsDtoByTrayId = this.dao.getItemsDtoByTrayId(trayId);
            if (!itemsDtoByTrayId.isEmpty()) {
                // 将其遍历转换
                List<TurnstoreTrayItemDto> collect = itemsDtoByTrayId.stream().map(entity -> JSON.parseObject(JSON.toJSONString(entity),
                        TurnstoreTrayItemDto.class)).collect(Collectors.toList());
                // 设置斜的参数
                // for (TurnstoreTrayItemDto turnstoreTrayItemDto : collect) {
                //   String xie = "";
                   /* if (turnstoreTrayItemDto.getSlopeT() != null) {
                        xie += "T" + turnstoreTrayItemDto.getSlopeT().toString() + " ";
                    }
                    if (turnstoreTrayItemDto.getSlopeW() != null) {
                        xie += "W" + turnstoreTrayItemDto.getSlopeW().toString() + " ";
                    }
                    turnstoreTrayItemDto.setXie(xie);*/
                //}
                return result.setData(collect);
            } else {
                return result.setData(result.getData());
            }
        } catch (Exception e) {
            return ResultGenerator.fail(e.getMessage());
        }
    }

    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse resp) {
        Specification<TurnstoreTrayItem> specification = DynamicSpecifications.bySearchFilter(request, TurnstoreTrayItem.class);
        List<TurnstoreTrayItem> turnstoreTrayItemList = findByExampleSort(specification, null);
        try {
            getExportExcel(turnstoreTrayItemList, request, resp);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public TurnstoreTrayItem findBySectionNo(String crystalNo) {
        List<TurnstoreTrayItem> trayItemList = dao.findBySectionNo(crystalNo);
        if (null != trayItemList && !trayItemList.isEmpty()) {
            return trayItemList.get(0);
        }
        return null;
    }

    @Override
    public TurnstoreTrayItem findBySectionNoAndState(String crystalNo, int state) {
        List<TurnstoreTrayItem> trayItemList = dao.findBySectionNoAndState(crystalNo, state);
        if (null != trayItemList && !trayItemList.isEmpty()) {
            return trayItemList.get(trayItemList.size() - 1);
        }
        return null;
    }

    @Override
    public void deleteByTrayId(Integer id) {
        List<TurnstoreTrayItem> itemsByTrayId = findItemsByTrayId(id);
        if (null != itemsByTrayId && !itemsByTrayId.isEmpty()) {
            for (TurnstoreTrayItem trayItem : itemsByTrayId) {
                //解锁组托状态
                PlanProcessingOrder planProcessingOrder = planProcessingOrderService.findByCode(trayItem.getSectionNo());
                if (null != planProcessingOrder) {
                    planProcessingOrder.setStatus(EnumValuesFactory.PlanProcessingOrderStatus.加工中.getKey());
                    planProcessingOrderService.saveOrUpdate(planProcessingOrder);
                }
            }
            dao.deleteByTrayId(id);
        }
    }

    @Override
    public List<TurnstoreTrayItem> findItemsByTrayId(Integer id) {
        return dao.getItemsByTrayId(id);
    }

    @Override
    public void updateTrayItemState(List<String> sectionNoList) {
        //更新组托明细状态
        String lastTrayNo = "";
        String trayNo = "";
        for (String sectionNo : sectionNoList) {
            TurnstoreTrayItem bySectionNo = findBySectionNo(sectionNo);
            if (null != bySectionNo) {
                bySectionNo.setState(3);
                trayNo = bySectionNo.getTrayNo();
                saveOrUpdate(bySectionNo);
            }
            //更新组托主表状态
            if (!lastTrayNo.equals(trayNo)) {
                TurnstoreTray byTrayNo = turnstoreTrayService.findByTrayNo(trayNo);
                byTrayNo.setState(2);
                turnstoreTrayService.saveOrUpdate(byTrayNo);
            }
            lastTrayNo = trayNo;
        }
    }

    @Override
    public TurnstoreTrayItem findByTrayNoAndSectionNo(String trayNo, String sectionNo) {
        List<TurnstoreTrayItem> trayItemList = dao.findByTrayNoAndSectionNo(trayNo, sectionNo);
        if (null != trayItemList && !trayItemList.isEmpty()) {
            return trayItemList.get(0);
        }
        return null;
    }

    @Override
    public List<TurnstoreTrayItem> findBySectionNoValidate(String sectionNo) {
        return dao.findBySectionNoValidate(sectionNo);
    }

    @Override
    public void updateOrderNoBySectionNo(String sectionNo, String orderNo) {
        dao.updateOrderNoBySectionNo(sectionNo, orderNo);
    }

    @Override
    public List<TurnstoreTrayItem> getData() {
        return dao.getData();
    }

    @Override
    public void updateOrderNoById(Integer id, String orderNo) {
        dao.updateOrderNoById(id, orderNo);
    }

    private void getExportExcel(List<TurnstoreTrayItem> turnstoreTrayItemList, HttpServletRequest request, HttpServletResponse resp) throws IOException {
        if (turnstoreTrayItemList.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("编号(SN)");
        row.createCell(4).setCellValue("单晶组合");
        row.createCell(5).setCellValue("型号(PN型号)");
        row.createCell(6).setCellValue("规格");
        row.createCell(7).setCellValue("工厂");
        row.createCell(8).setCellValue("库存地点");
        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("崩晶线");
        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("确认时间");

        for (int i = 0; i < turnstoreTrayItemList.size(); i++) {
            row = sheet.createRow(i + 1);
            TurnstoreTrayItem trayItem = turnstoreTrayItemList.get(i);
            row.createCell(0).setCellValue(i + 1);
            if (trayItem.getItemNo() != null) {
                row.createCell(1).setCellValue(trayItem.getItemNo());
            }
            if (trayItem.getTrayNo() != null) {
                row.createCell(2).setCellValue(trayItem.getTrayNo());
            }
            if (trayItem.getSectionNo() != null) {
                row.createCell(3).setCellValue(trayItem.getSectionNo());
            }
            if (trayItem.getSectionCompose() != null) {
                row.createCell(4).setCellValue(trayItem.getSectionCompose());
            }
            if (trayItem.getConductiveType() != null) {
                row.createCell(5).setCellValue(trayItem.getConductiveType());
            }
            if (trayItem.getProductTypeSecond() != null) {
                row.createCell(6).setCellValue("Φ" + trayItem.getProductTypeSecond());
            }
            if (trayItem.getFactory() != null) {
                row.createCell(7).setCellValue(trayItem.getFactory());
            }
            if (trayItem.getStockPlace() != null) {
                row.createCell(8).setCellValue(trayItem.getStockPlace());
            }
            if (trayItem.getActualWeight() != null) {
                row.createCell(9).setCellValue(trayItem.getActualWeight().doubleValue());
            }
            if (trayItem.getTheoryWeight() != null) {
                row.createCell(10).setCellValue(trayItem.getTheoryWeight().doubleValue());
            }
            if (trayItem.getWareHouseLength() != null) {
                row.createCell(11).setCellValue(trayItem.getWareHouseLength().doubleValue());
            }
            if (trayItem.getActualLength() != null) {
                row.createCell(12).setCellValue(trayItem.getActualLength().doubleValue());
            }
            if (trayItem.getCustomerType() != null) {
                row.createCell(13).setCellValue(trayItem.getCustomerType());
            }
            if (trayItem.getOrderNo() != null) {
                row.createCell(14).setCellValue(trayItem.getOrderNo());
            }
            if (trayItem.getEdgeBark() != null) {
                row.createCell(15).setCellValue(trayItem.getEdgeBark().doubleValue());
            }
            if (trayItem.getCollapseLine() != null) {
                row.createCell(16).setCellValue(trayItem.getCollapseLine().doubleValue());
            }
            if (trayItem.getIsBevel() != null) {
                row.createCell(17).setCellValue(trayItem.getIsBevel());
            }
            if (trayItem.getFineDiameter() != null) {
                row.createCell(18).setCellValue(trayItem.getFineDiameter().doubleValue());
            }
            if (trayItem.getFineCutLength() != null) {
                row.createCell(19).setCellValue(trayItem.getFineCutLength().doubleValue());
            }
            if (trayItem.getDistortion() != null) {
                row.createCell(20).setCellValue(trayItem.getDistortion().doubleValue());
            }
            if (trayItem.getLifeGrading() != null) {
                row.createCell(21).setCellValue(trayItem.getLifeGrading());
            }
            if (trayItem.getErrorMsg() != null) {
                row.createCell(22).setCellValue(trayItem.getErrorMsg());
            }
            if (trayItem.getRemark() != null) {
                row.createCell(23).setCellValue(trayItem.getRemark());
            }
            if (trayItem.getOperationTime() != null) {
                row.createCell(24).setCellValue(DateUtil.formatDate(trayItem.getOperationTime(), DateUtil.longFormat));
            }
            if (trayItem.getConfirmTime() != null) {
                row.createCell(25).setCellValue(DateUtil.formatDate(trayItem.getConfirmTime(), DateUtil.longFormat));
            }
        }
        sheet.setDefaultRowHeight((short) (20 * 20));
        //列宽自适应
        int num = 20;
        for (int i = 0; i <= num; i++) {
            sheet.autoSizeColumn(i);
        }
        String fileName = turnstoreTrayItemList.get(0).getTrayNo() + "_圆棒组托记录.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();
    }
}
