package com.sunda.spmsweb.ordercontroller;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
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.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.MaterialDeliveryBoards;
import com.sunda.spmsorder.entity.MaterialSap;
import com.sunda.spmsorder.entity.vo.MaterialDeliveryBoardsQueryVO;
import com.sunda.spmsorder.service.IFileOperationService;
import com.sunda.spmsorder.service.IMaterialSapService;
import com.sunda.spmsorder.service.IMaterialSpmsService;
import com.sunda.spmsweb.util.ExportExcel;
import com.sunda.spmsweb.util.JWTUtil;
import com.sunda.spmswms.dto.WhsSearchDTO;
import com.sunda.spmswms.entity.SapDeliveryNote;
import com.sunda.spmswms.service.ISapDeliveryNoteService;

/**
 * <p>
 * 物料表SPMS 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2020-11-13
 */
@RestController
@RequestMapping("/materialSpms")
@Api(tags = "SPMS 物料信息接口", description = "关联备件目录和物料的关系")
public class MaterialSpmsController {
	
	@Autowired
	private IMaterialSpmsService iMaterialSpmsService;
	
	@Autowired
    IFileOperationService iFileOperationService;
	
	@Autowired
	IMaterialSapService iMaterialSapService;
	
	@Autowired
	ISapDeliveryNoteService iSapDeliveryNoteService;
	
	@RequestMapping("/getMaterialSap")
    @ApiOperation(value = "分页查询物料/交货单仓租计费板位数维护表", notes = "分页查询；\n" +
            "可选输入物料编号/交货单模糊查找：materialNo = 130011853；\n" +
            "必填：当前页pageNo，页码大小pageSize；\n" +
            "{\n" +
            "\t\"materialNo\": \"130011853\",\n" +
            "\t\"pageNo\": \"1\",\n" +
            "\t\"pageSize\": \"20\"\n" +
            "}", httpMethod = "POST")
    public ResponseResult getMaterialSap(@RequestBody MaterialDeliveryBoardsQueryVO record) {
        try {
            return iMaterialSpmsService.getMaterialDeliveryBoardsList(record);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }
	
	@RequestMapping("/updateMaterialDeliverBoards")
    @ApiOperation(value = "修改物料/交货单仓租计费板位数维护表", notes = "修改物料/交货单仓租计费板位数维护表；\n" +
            "{\n" +
            "\t\"materialNo\": \"130011853\",\n" +
            "\t\"deliveryNoteSap\": \"130011853\",\n" +
            "\t\"boards\": \"1\",\n" +
            "\t\"materialType\": \"20\"\n" +
            "}", httpMethod = "POST")
	@RequiresPermissions("materialSpms-updateMaterialDeliverBoards")
    public ResponseResult updateMaterialDeliverBoards(@RequestBody MaterialDeliveryBoards record) {
        try {
        	String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
            return iMaterialSpmsService.updateMaterialDeliverBoards(record, userId);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }
	
	 @SuppressWarnings({ "unused", "resource", "unchecked" })
	@RequestMapping("/importMaterialDeliveryExcel")
    @ApiOperation(value = "Excel导入物料板位数", notes = "请求参数示例：{ avatar: file}", httpMethod = "POST")
    @ResponseBody
    public ResponseResult importMaterialDeliveryExcel(@RequestParam(value = "avatar") MultipartFile avatar){
    	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);
                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<MaterialDeliveryBoards> safetyList = new ArrayList<MaterialDeliveryBoards>();
                	String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
                    for (int i = 2; i <= rowNum; i++) {//正式数据从第三行开始
                        row = sheet.getRow(i);
                        // 手工转化
                        if (row == null){
                            continue;
                        }
                        MaterialDeliveryBoards materialVO = new MaterialDeliveryBoards();
                        String cell0 = ExportExcel.getCellFormatValue(row.getCell(0));
                        materialVO.setMaterialNo(cell0);
                        String cell1 = ExportExcel.getCellFormatValue(row.getCell(1));
                        materialVO.setDeliveryNoteSap(cell1);
                        if (StringUtils.isBlank(cell0) && StringUtils.isBlank(cell1)) {
                        	return ResponseResult.error("物料号跟交货单号二选一填写");
                        }
                        if (StringUtils.isNotBlank(cell0) && StringUtils.isNotBlank(cell1)) {
                			return ResponseResult.error("物料号跟交货单号二选一填写");
                		}
                        String cell2 = ExportExcel.getCellFormatValue(row.getCell(2));
                        materialVO.setBoards(cell2);
                        String cell3 = ExportExcel.getCellFormatValue(row.getCell(3));
                        materialVO.setMaterialType(cell3);
                        if (StringUtils.isNotBlank(cell0)) {
                        	// 判断物料编码是否存在
                        	MaterialSap materialInfo = iMaterialSapService.getMaterialInfo(cell0);
                			if (materialInfo == null) {
                				return ResponseResult.error("第"+(i+1)+"行物料"+cell0+"在物料表中不存在，请检查输入的物料号是否正确！");
                			}
                			// 看物料号或者交货单号在物料/交货单仓租计费板位数表中是否存在，不存在新增、存在就更新
                			Map<String, Object> selectMaterialAndDelivery = iMaterialSpmsService.selectMaterialAndDelivery(cell0, null);
                			if (selectMaterialAndDelivery == null) {
                				materialVO.setCreateUser(userId);
                				materialVO.setCreateTime(new Date());
                				materialVO.setDeliveryNoteSap("");
                				iMaterialSpmsService.insertMaterialAndDelivery(materialVO);
                			} else {
                				materialVO.setUpdateUser(userId);
                				materialVO.setUpdateTime(new Date());
                				iMaterialSpmsService.updateMaterialAndDelivery(materialVO);
                			}
                        } else if (StringUtils.isNotBlank(cell1)) {
                        	SapDeliveryNote sapDnByDn = iSapDeliveryNoteService.getSapDnByDn(cell1);
                			if (sapDnByDn == null) {
                				return ResponseResult.error("第"+(i+1)+"行交货单号"+cell1+"在交货单表中不存在，请检查输入的交货单号是否正确！");
                			}
                			// 看物料号或者交货单号在物料/交货单仓租计费板位数表中是否存在，不存在新增、存在就更新
                			Map<String, Object> selectMaterialAndDelivery = iMaterialSpmsService.selectMaterialAndDelivery(null, cell1);
                			if (selectMaterialAndDelivery == null) {
                				materialVO.setCreateUser(userId);
                				materialVO.setCreateTime(new Date());
                				materialVO.setMaterialNo("");
                				iMaterialSpmsService.insertMaterialAndDelivery(materialVO);
                			} else {
                				materialVO.setUpdateUser(userId);
                				materialVO.setUpdateTime(new Date());
                				iMaterialSpmsService.updateMaterialAndDelivery(materialVO);
                			}
                        }
                    }
                }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){
                    }
                }
            }
            return ResponseResult.success().add("msg","S");
        }
    }
	 
	@RequestMapping("/exportMaterialDeliveryList")
    @ApiOperation(value = "物料板位数导出EXCEL", notes = "物料板位数导出EXCEL\n" +
    		"可选输入物料编号/交货单模糊查找：materialNo = 130011853；\n" +
            "{\n" +
            "materialNo = 130011853,\n" +
            "}\n", httpMethod = "POST")
	@RequiresPermissions("materialSpms-exportMaterialDeliveryList")
    public ResponseResult exportMaterialDeliveryList(@RequestBody MaterialDeliveryBoardsQueryVO dto){
        try {
            dto.setPageNo(1);
        	dto.setPageSize(Integer.MAX_VALUE);
            String filename = "materialAndDeliveryBoards" + System.currentTimeMillis()+".xlsx";
            // 1.附件缓存路径
            String excelPath = iFileOperationService.saveMaterialAndDeliveryBoardsExcel(iMaterialSpmsService.getMaterialDeliveryBoardsList(dto), filename);
            if (StringUtils.isEmpty(excelPath)) {
                return ResponseResult.error("附件创建失败");
            }
            // 2.上传附件至minIO文件服务器
            String fileUrl = iFileOperationService.fileUploader(filename, excelPath);
            if (fileUrl.isEmpty()){
                return ResponseResult.error("附件上传失败:" + excelPath + "--" + fileUrl);
            }
            // 3.返回附件地址，上传OA
            return ResponseResult.success().add("fileUrl",fileUrl);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

}
