package com.prolog.eis.service.shelves.impl;

import com.prolog.eis.dao.shelves.LimitedGoodsAllocationMapper;
import com.prolog.eis.dto.shelves.LocationLimitedDto;
import com.prolog.eis.dto.shelves.LimitedGoodsAllocationInfoDto;
import com.prolog.eis.dto.shelves.LocationLimitedDetailDto;
import com.prolog.eis.model.shelves.LimitedGoodsAllocationInfo;
import com.prolog.eis.service.shelves.DataDictionaryService;
import com.prolog.eis.service.shelves.LocationLimitedService;
import com.prolog.framework.common.message.RestMessage;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

public class LocationLimitedServiceImpl implements LocationLimitedService {

    @Resource
    private LimitedGoodsAllocationMapper limitedGoodsAllocationMapper;

    @Autowired
    private DataDictionaryService dataDictionaryService;

    @Override
    public List<LimitedGoodsAllocationInfo> getLimitedGoodsAllocationInfo(LocationLimitedDto dto) {
        List<LimitedGoodsAllocationInfo> goodsAllocationInfos = limitedGoodsAllocationMapper.getLimitedGoodsAllocationInfo(dto);
        if(!goodsAllocationInfos.isEmpty()){
            List<Map<String, Object>> maps = dataDictionaryService.queryDataDictionaryByCode(dto.getCode());
            return goodsAllocationInfos.stream().map(x ->{
                List<Map<String, Object>> stateValues = maps.stream().filter(m -> m.get("stateValues").equals(x.getGoodsBigType().toString())).collect(Collectors.toList());
                if(!stateValues.isEmpty()) x.setGoodsBigTypeStr(stateValues.get(0).get("stateDescription").toString());
                return x;
            }).collect(Collectors.toList());
        }else {
            return new ArrayList<>();
        }
    }

    @Override
    public List<LocationLimitedDetailDto> getLimitedGoodsAllocationDetails(LocationLimitedDto dto) {
        String str= limitedGoodsAllocationMapper.getLimitedGoodsAllocationDetails(dto.getId());
        List<LocationLimitedDetailDto> list=null;
        if(str!=null&& !str.equals("")){
            list=new ArrayList<>();
            String[] limitedArea_List = str.split(",");
            for (int i = 0; i < limitedArea_List.length; i++) {
                LocationLimitedDetailDto detailsDto = new LocationLimitedDetailDto();
                detailsDto.setId(i+1);
                detailsDto.setLimitedArea(limitedArea_List[i]);
                list.add(detailsDto);
            }
        }
        return list;
    }

    @Override
    public RestMessage<List<LimitedGoodsAllocationInfoDto>> insertLimitedGoodsAllocationInfo(List<LimitedGoodsAllocationInfo> limited_goods_allocation_info) {
        for (LimitedGoodsAllocationInfo each : limited_goods_allocation_info){
            each.setCreateBy("QnUser");
            each.setCreateTime(new Date());
        }
        limitedGoodsAllocationMapper.insertLimitedGoodsAllocationInfoNoDetails(limited_goods_allocation_info);
        return RestMessage.newInstance(true,"200", "货位限定信息新增成功",null);
    }

    @Override
    public RestMessage updateLimitedGoodsAllocationInfo(List<LimitedGoodsAllocationInfo> limited_goods_allocation_info) {
        for (LimitedGoodsAllocationInfo each : limited_goods_allocation_info){
            each.setUpdateBy("QnUesr");
            each.setUpdateTime(new Date());
        }
        limitedGoodsAllocationMapper.updateLimitedGoodsAllocationInfo(limited_goods_allocation_info);
        return RestMessage.newInstance(true,"200", "货位限定信息修改成功",null);
    }

    @Override
    public RestMessage updateLimitedGoodsAllocationDetails(List<LimitedGoodsAllocationInfoDto> dto) {
        List<LimitedGoodsAllocationInfo> limitedGoodsAllocationInfoList = new ArrayList<>();
        for(LimitedGoodsAllocationInfoDto each:dto){
            String str= limitedGoodsAllocationMapper.getLimitedGoodsAllocationDetails(each.getId().toString());
            String[] strList = str.split(",");
            List<String> list=new ArrayList<>(Arrays.asList(strList));
            Map<String,String> map=each.getLimitedArea();
            if(map!=null){
                for(Map.Entry<String,String> entry:map.entrySet()){
                    Integer pos=Integer.parseInt(entry.getKey());
                    if(pos<=list.size()){
                        list.set(pos - 1, entry.getValue());
                    }else {
                        list.add(entry.getValue());
                    }
                }
            }
            StringJoiner limitedArea = new StringJoiner(",");
            for (String i:list){
                limitedArea.add(i);
            }
            LimitedGoodsAllocationInfo limitedGoodsAllocationInfo = LimitedGoodsAllocationInfo.builder().id(each.getId()).
                    limitedArea(limitedArea.toString()).build();
            limitedGoodsAllocationInfoList.add(limitedGoodsAllocationInfo);
        }
        limitedGoodsAllocationMapper.updateLimitedGoodsAllocationDetails(limitedGoodsAllocationInfoList);
        return RestMessage.newInstance(true,"200", "货位限定明细信息修改成功",null);
    }

    @Override
    public RestMessage insertLimitedGoodsAllocationDetails(List<LimitedGoodsAllocationInfo> dto) {
        for(LimitedGoodsAllocationInfo each:dto){
            LimitedGoodsAllocationInfo info = limitedGoodsAllocationMapper.findById(each.getId(), LimitedGoodsAllocationInfo.class);
            if(StringUtils.isEmpty(info.getLimitedArea())) {
                info.setLimitedArea(each.getLimitedArea());
            }else {
                info.setLimitedArea(info.getLimitedArea()+","+each.getLimitedArea());
            }
            limitedGoodsAllocationMapper.update(info);
        }
        return RestMessage.newInstance(true,"200", "货位限定信息新增成功",null);
    }

    @Override
    public RestMessage  deleteLimitedGoodsAllocationInfo(LocationLimitedDto dto) {
        limitedGoodsAllocationMapper.deleteLimitedGoodsAllocationInfo(dto.getId());
        return RestMessage.newInstance(true,"200", "货位限定信息删除成功",null);
    }

    @Override
    public RestMessage deleteLimitedGoodsAllocationDetails(LocationLimitedDetailDto dto) {
        String str= limitedGoodsAllocationMapper.getLimitedGoodsAllocationDetails(dto.getId().toString());
        String[] strList = str.split(",");
        List<String> list=new ArrayList<>(Arrays.asList(strList));
        if(dto.getDetailId()<=list.size()){
            list.remove(dto.getDetailId()-1);
        }
        StringJoiner limitedArea = new StringJoiner(",");
        for (String i:list){
            limitedArea.add(i);
        }
        limitedGoodsAllocationMapper.updateLimitedGoodsAllocationDetail(dto.getId(),limitedArea.toString());
        return RestMessage.newInstance(true,"200", "货位限定信息明细删除成功",null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestMessage importLimitedGoodsAllocationInfo(MultipartFile file) throws IOException {
        if (file == null)
            return RestMessage.newInstance(false,"401", "货位限定信息导入失败,上传文件不能为空", null);
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return RestMessage.newInstance(false, "402","货位限定信息导入失败,上传文件格式不正确", null);
        }
        boolean isExcel2003 = true;
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb = null;
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }
        Sheet sheet = wb.getSheetAt(0);
        List<LimitedGoodsAllocationInfo> importData = new ArrayList<>();
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            LimitedGoodsAllocationInfo eachRowInfo = new LimitedGoodsAllocationInfo();
            Cell cell = null;
            cell = row.getCell(0);
            if (cell != null && cell.getCellTypeEnum() != CellType.BLANK) // 分别判断单元格是否为空
                eachRowInfo.setGoodsOwnerId(cell.getStringCellValue());
            cell = row.getCell(1);
            if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)
                eachRowInfo.setGoodsOwnerName(row.getCell(1).getStringCellValue());
            cell = row.getCell(2);
            if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)
                eachRowInfo.setGoodsBarcode(row.getCell(2).getStringCellValue());
            cell = row.getCell(3);
            if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)
                eachRowInfo.setGoodsName(row.getCell(3).getStringCellValue());
            cell = row.getCell(4);
            if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)
                eachRowInfo.setGoodsType(row.getCell(4).getStringCellValue());
            cell = row.getCell(5);
            if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)
                eachRowInfo.setGoodsBigType(null != row.getCell(5).getStringCellValue() ? Integer.valueOf(row.getCell(5).getStringCellValue()) : null);
            cell = row.getCell(6);
            if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)
                eachRowInfo.setCreateBy(row.getCell(6).getStringCellValue());
            cell = row.getCell(7);
            if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)
                eachRowInfo.setNotes(row.getCell(7).getStringCellValue());
            StringJoiner goodsAllocationInfo = new StringJoiner(",");
            for (int col = 8; col <= row.getLastCellNum(); col++) { // 单元格为空时停止读取
                cell = row.getCell(col);
                if (cell != null && cell.getCellTypeEnum() != CellType.BLANK)//跳过其中的空单元格
                    goodsAllocationInfo.add(cell.getStringCellValue());
            }
            eachRowInfo.setLimitedArea(goodsAllocationInfo.toString());
            importData.add(eachRowInfo);
        }
        limitedGoodsAllocationMapper.insertLimitedGoodsAllocationInfo(importData);
        return RestMessage.newInstance(true, "200","货位限定信息导入成功", null);
    }


}
