package com.sunda.spmsweb.wmscontroller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.service.IFileOperationService;
import com.sunda.spmsorder.util.ExcelUtils;
import com.sunda.spmswms.entity.Whs;
import com.sunda.spmswms.entity.WhsStorage;
import com.sunda.spmswms.service.IWhsStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;

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.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 仓库储位信息表 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-03-18
 */
@RestController
@RequestMapping("/whsStorage")
@Api(tags = "仓库储位信息表", description = "仓库储位信息接口")
public class WhsStorageController {

    @Autowired
    IWhsStorageService iWhsStorageService;

    @Autowired
    IFileOperationService iFileOperationService;


    @RequestMapping("/getWhsStorageList")
    @ApiOperation(value = "获取全部仓库储位信息",notes = "获取全部仓库储位信息 \n" +
            "{\n" +
            "\t\"whsCode\": [\"2134\", \"1061\"],\n" +
            "\t\"werks\": [\"CN01\"]\n" +
            "}", httpMethod = "POST")
    public ResponseResult getWhsStorageList(@RequestBody JSONObject jsonObject){

        try {
            List<String> whsCode=jsonObject.containsKey("whsCode")? (List)jsonObject.getJSONArray("whsCode") :null;
            List<String> werks=jsonObject.containsKey("werks")? (List)jsonObject.getJSONArray("werks") :null;

            if(whsCode==null || werks==null ) {
                throw new Exception("仓库代码或是工厂代码为空");
            }

            return ResponseResult.success().add("whsStorageList", iWhsStorageService.getAllWhsStorageList(whsCode,werks));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("获取仓库信息储位出错");
        }
    }


    @RequestMapping("/getWhsStorageOldList")
    @ApiOperation(value = "获取旧件仓库储位信息",notes = "获取旧件仓库储位信息 \n" +
            "{\n" +
            "\t\"whsCode\": [\"2134\", \"1061\"],\n" +
            "\t\"werks\": [\"CN01\"]\n" +
            "}", httpMethod = "POST")
    public ResponseResult getWhsStorageOldList(@RequestBody JSONObject jsonObject){

        try {
            List<String> whsCode=jsonObject.containsKey("whsCode")? (List)jsonObject.getJSONArray("whsCode") :null;
            List<String> werks=jsonObject.containsKey("werks")? (List)jsonObject.getJSONArray("werks") :null;

            if(whsCode==null || werks==null ) {
                throw new Exception("仓库代码或是工厂代码为空");
            }

            return ResponseResult.success().add("whsStorageList", iWhsStorageService.getAllWhsStorageOldList(whsCode,werks));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("获取仓库信息储位出错");
        }
    }

    @RequestMapping("/getWhsStorageListAll")
    @ApiOperation(value = "获取全部仓库储位信息连带已经删除的储位",notes = "获取全部仓库储位信息连带已经删除的储位 \n" +
            "{\n" +
            "\t\"whsCode\": [\"2134\", \"1061\"],\n" +
            "\t\"werks\": [\"CN01\"]\n" +
            "}", httpMethod = "POST")
    @RequiresPermissions("whsStorage-getWhsStorageListAll")
    public ResponseResult getWhsStorageListAll(@RequestBody JSONObject jsonObject){

        try {
            List<String> whsCode=jsonObject.containsKey("whsCode")? (List)jsonObject.getJSONArray("whsCode") :null;
            List<String> werks=jsonObject.containsKey("werks")? (List)jsonObject.getJSONArray("werks") :null;

            if(whsCode==null || werks==null ) {
                throw new Exception("仓库代码或是工厂代码为空");
            }

            return ResponseResult.success().add("whsStorageList", iWhsStorageService.getWhsStorageListAll(whsCode,werks));
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("获取仓库信息储位出错");
        }
    }

    @RequestMapping("/createWhsStorage")
    @ApiOperation(value = "新建仓库储位",notes = "新建仓库储位", httpMethod = "POST")
    @RequiresPermissions("whsStorage-createWhsStorage")
    public ResponseResult createWhsStorage(@RequestBody WhsStorage whsStorage){

        return iWhsStorageService.createWhsStorage(whsStorage);
    }



    @RequestMapping("/uploadWhsStorage")
    @ApiOperation(value = "上传储位管理Excel文件导入", notes = "请求参数示例：{ avatar: file}", httpMethod = "POST")
    @RequiresPermissions("whsStorage-uploadWhsStorage")
    @ResponseBody
    public ResponseResult uploadMaterialPic(@RequestParam(value = "avatar") MultipartFile avatar, String uploadType){
        if (avatar.isEmpty()) {
            return ResponseResult.error("不能上传空文件");
        }else {
            Sheet sheet = null;
            Row row;
            File temp = null;
            InputStream is;
            try {
                // 另存文件名
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                Calendar calendar = Calendar.getInstance();
                String fileName = df.format(calendar.getTime()) + avatar.getOriginalFilename();
                // 1.附件缓存路径
                String filePath = iFileOperationService.saveMaterialApplicationPic(avatar, fileName);
                System.out.println("fileName" + filePath);
                // 2.上传附件至minIO文件服务器
                //String fileUrl = iFileOperationService.fileUploader(fileName, filePath);
                //return ResponseResult.success().add("imageUrl",fileUrl);
                temp = new File(filePath);
                is = new FileInputStream(temp);
                Workbook wb;
                Map<String, PictureData> sheetIndexPicMap;
                if (temp.getName().toLowerCase().endsWith(".xls")) {
                    wb = new HSSFWorkbook(is);
                    sheet = wb.getSheetAt(0);// 读取第一个sheet
                } else if (temp.getName().toLowerCase().endsWith(".xlsx")) {
                    wb = new XSSFWorkbook(is);
                    sheet = wb.getSheetAt(0);// 读取第一个sheet
                } else {
                    return ResponseResult.error("只支持excel格式文件！");
                }
                // 得到总行数
                int rowNum = sheet.getLastRowNum();
                if (rowNum <= 1) {
                    return ResponseResult.error("请检查文件内容是否为空！");
                }
                try {
                    List<WhsStorage> whsStorages = new ArrayList<WhsStorage>();
                    for (int i = 2; i <= rowNum; i++) {//
                        row = sheet.getRow(i);
                        // 手工转化
                        if (row == null){
                            continue;
                        }
                        WhsStorage whsStorage=new WhsStorage();
                        if(row.getCell(0)!=null){
                            row.getCell(0).setCellType(CellType.STRING);
                            whsStorage.setWerks(row.getCell(0).getRichStringCellValue().getString());//工厂代码
                        }else{
                            return ResponseResult.error("第"+i+"行“工厂代码”不能为空！");
                        }
                        if(row.getCell(1)!=null){
                            row.getCell(1).setCellType(CellType.STRING);
                            whsStorage.setWhsLocationCode(row.getCell(1).getRichStringCellValue().getString());//仓库地点代码
                        }else{
                            return ResponseResult.error("第"+i+"行“仓库地点代码”不能为空！");
                        }
                        if(row.getCell(2)!=null){
                            row.getCell(2).setCellType(CellType.STRING);
                            whsStorage.setStorageArea(row.getCell(2).getRichStringCellValue().getString());//库区
                        }else{
                            return ResponseResult.error("第"+i+"行“库区”不能为空！");
                        }
                        if(row.getCell(3)!=null){
                            row.getCell(3).setCellType(CellType.STRING);
                            whsStorage.setShelfNo(row.getCell(3).getRichStringCellValue().getString());//货架架子编号
                        }else{
                            return ResponseResult.error("第"+i+"行“货架架子编号”不能为空！");
                        }
                        if(row.getCell(4)!=null){
                            row.getCell(4).setCellType(CellType.STRING);
                            whsStorage.setShelfLayer(row.getCell(4).getRichStringCellValue().getString());//货架架子层数编号
                        }else{
                            return ResponseResult.error("第"+i+"行“货架架子层数编号”不能为空！");
                        }
                        if(row.getCell(5)!=null){
                            row.getCell(5).setCellType(CellType.STRING);
                            whsStorage.setShelfCell(row.getCell(5).getRichStringCellValue().getString());//货架层上格子编号
                        }else{
                            return ResponseResult.error("第"+i+"行“货架层上格子编号”不能为空！");
                        }
                        if(row.getCell(6)!=null){
                            row.getCell(6).setCellType(CellType.STRING);
                            whsStorage.setStorageNo(row.getCell(6).getRichStringCellValue().getString());//储位编号（架号+层号+格子号）
                        }else{
                            return ResponseResult.error("第"+i+"行“储位编号”不能为空！");
                        }
                        // 国内仓导入储位信息储位类型默认01
                        if (StringUtils.isNotBlank(uploadType) && "CN".equals(uploadType)) {
                        	whsStorage.setStorageType("01");//储位类型
                        } else {
                        	if(row.getCell(7)!=null){
                        		row.getCell(7).setCellType(CellType.STRING);
                        		whsStorage.setStorageType(row.getCell(7).getRichStringCellValue().getString());//储位类型
                        	}
                        }
                        if(row.getCell(8)!=null){
                            row.getCell(8).setCellType(CellType.STRING);
                            whsStorage.setStorageInfo(row.getCell(8).getRichStringCellValue().getString());//储位信息说明
                        }
                        if(row.getCell(9)!=null){
                            row.getCell(9).setCellType(CellType.STRING);
                            whsStorage.setStorageStatus(row.getCell(9).getRichStringCellValue().getString());//储位状态（默认1启用，0停用）
                        }
                        if(row.getCell(10)!=null){
                            row.getCell(10).setCellType(CellType.STRING);
                            whsStorage.setRemarks(row.getCell(10).getRichStringCellValue().getString());//备注说明
                        }
                        if(row.getCell(11)!=null){
                            row.getCell(11).setCellType(CellType.STRING);
                            whsStorage.setRemarksEn(row.getCell(11).getRichStringCellValue().getString());//英文描述
                        }
                        whsStorages.add(whsStorage);
                    }
                    ResponseResult res = iWhsStorageService.batchCreateWhsStorage(whsStorages);
                    if(100==res.getCode()){
                        return ResponseResult.error(res.getMsg());
                    }
                }catch (Exception e) {
                    return ResponseResult.error(e.getMessage());
                }
            }catch (Exception e) {
                return ResponseResult.error(e.getMessage());
            } finally {
                if (temp != null) {
                    boolean newFile = temp.delete();
                    if(!newFile){
                        //log.error(temp+"删除失败");
                    }
                }
            }

            return ResponseResult.success().add("msg","S");
        }
    }


}
