package com.sunda.spmsweb.ordercontroller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.MaterialSap;
import com.sunda.spmsorder.entity.ShoppingScenario;
import com.sunda.spmsorder.entity.ShoppingScenarioDtl;
import com.sunda.spmsorder.service.IFileOperationService;
import com.sunda.spmsorder.service.IMaterialSapService;
import com.sunda.spmsorder.service.IShoppingScenarioService;
import com.sunda.spmsoversea.dto.SafetyInventorySearchDTO;
import com.sunda.spmsoversea.entity.SafetyInventory;
import com.sunda.spmsoversea.service.ISafetyInventoryService;
import com.sunda.spmsuser.entity.SpmsUser;
import com.sunda.spmsuser.service.ISpmsUserService;
import com.sunda.spmsweb.util.ExportExcel;
import com.sunda.spmsweb.util.JWTUtil;

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.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
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;

/**
 * <p>
 * 请购场景表表头 前端控制器
 * </p>
 *
 * @author Wayne
 * @since 2021-03-01
 */
@RestController
@RequestMapping("/shoppingScenario")
@Api(tags = "请购场景接口", description = "请购场景接口")
public class ShoppingScenarioController {

    @Autowired
    IShoppingScenarioService iShoppingScenarioService;
    
    @Autowired
    IFileOperationService iFileOperationService;
    
    @Autowired
    IMaterialSapService iMaterialSapService;
    
    @Autowired
    ISafetyInventoryService iSafetyInventoryService;

    @Autowired
    ISpmsUserService iSpmsUserService;

    @RequestMapping("/getOrderScenario")
    @ApiOperation(value = "获取工厂请购场景（表头 分页）",notes = "获取指定条件下工厂请购场景分页信息。werks 工厂代码必输，[\"GF01\", \"GF02\"]；isDelete：0有效，1已删除；isDelete传空则忽略；",
            httpMethod = "POST")
    public ResponseResult getOrderScenario(@RequestParam(defaultValue = "1") int pageNo ,
                                               @RequestParam(defaultValue = "20") int pageSize,
                                           @RequestBody String[] werks, String isDelete) {
        try{
            return ResponseResult.success().add("shoppingScenarioList", iShoppingScenarioService.getScenarioList(pageNo, pageSize, werks, isDelete));
        } catch (Exception e){
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/queryOrderScenario")
    @ApiOperation(value = "获取工厂请购场景（表头 分页）",notes = "获取指定条件下工厂请购场景分页信息。werks 工厂代码必输，isDelete：0有效，1已删除；isDelete传空则忽略；" +
    "{ \n"+
    "  \"authorName\": \"张坤鹏\", \n"+
    "  \"spmsId\": \"GF03-001\", \n"+
    "  \"isDelete\": \"0\", \n"+
    "  \"pageNo\": 1, \n"+
    "  \"pageSize\": 20, \n"+
    "  \"scenarioName\": \"模板名称\", \n"+
    "  \"workshopCode\": \"车间编号\", \n"+
    "  \"machineDesc\": \"设备名称\", \n"+
    "  \"userId\": \"999904\", \n"+
    "  \"werks\": \"GF03\"\n"+
    "} \n",
            httpMethod = "POST")
    @RequiresPermissions("shoppingScenario-queryOrderScenario")
    public ResponseResult queryOrderScenario(@RequestBody JSONObject queryObj) {
        try{
            return ResponseResult.success().add("shoppingScenarioList", iShoppingScenarioService.queryScenarioList(queryObj));
        } catch (Exception e){
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/getOrderScenarioDtl")
    @ApiOperation(value = "获取工厂请购场景（行项目 不分页）",notes = "获取指定条件下工厂请购场景详情信息。传入请购场景表头 uuid = 9463644cb2a941c881e88c76d12b62fw。",
            httpMethod = "POST")
    @RequiresPermissions("shoppingScenario-getOrderScenarioDtl")
    public ResponseResult getOrderScenarioDtl(String uuid) {
        try{
            return ResponseResult.success().add("shoppingScenarioDtl", iShoppingScenarioService.getScenarioDtlList(uuid));
        } catch (Exception e){
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }


    @RequestMapping("/exportOrderScenarioDtl")
    @ApiOperation(value = "导出工厂请购场景（行项目 不分页）",notes = "获取指定条件下工厂请购场景详情信息。传入请购场景表头 uuid = 9463644cb2a941c881e88c76d12b62fw。",
            httpMethod = "GET")
    //@RequiresPermissions("overseaRequisition-createOverseaRequisitionReport")
    public ResponseResult exportOrderScenarioDtl(String uuid){
        try {
            ShoppingScenario head = iShoppingScenarioService.getOne(new QueryWrapper<ShoppingScenario>().eq("UUID", uuid));
            SpmsUser user = iSpmsUserService.getByUserId(head.getCreateUserid());
            head.setCreateUserid(user.getLastName());
            List<Map<String, Object>> data = iShoppingScenarioService.getScenarioDtlList(uuid);
            String filename = "order_scenario_" + System.currentTimeMillis()+".xlsx";
            // 1.附件缓存路径
            String excelPath = iFileOperationService.saveShoppingScenarioExcel(head,data, filename);
            if (excelPath.isEmpty()){
                return ResponseResult.error("附件创建失败");
            }
            System.out.println("附件缓存地址：" + excelPath);
            // 2.上传附件至minIO文件服务器
            String fileUrl = iFileOperationService.fileUploader(filename, excelPath);
            if (fileUrl.isEmpty()){
                return ResponseResult.error("附件上传失败:" + excelPath + "--" + fileUrl);
            }
            System.out.println("附件上传地址:" + fileUrl);
            // 3.返回附件地址，上传OA
            return ResponseResult.success()
                    .add("fileUrl",fileUrl);
        }catch (Exception e){
            e.printStackTrace();
            return ResponseResult.error("请求数据失败").add("error", e.getMessage());
        }
    }

    @RequestMapping("/createScenario")
    @ApiOperation(value = "创建工厂请购场景及行项目",notes = "创建工厂请购场景及行项目，传入json字符串参考：\n" +
            "场景编号规则：工厂代码 werks + 序列号，如 GF01-1001\n" +
            "{\n" +
            "\t\"shoppingScenario\": {\n" +
            "\t\t\"scenarioDesc\": \"GF01xx电机维修场景描述\",\n" +
            "\t\t\"machineDesc\": \"设备描述\",\n" +
            "\t\t\"createUserid\": \"20001\",\n" +
            "\t\t\"werks\": \"GF01\",\n" +
            "\t\t\"machineNo\": \"machine no\",\n" +
            "\t\t\"scenarioName\": \"GF01xx电机维修场景\",\n" +
            "\t\t\"remarks\": null\n" +
            "\t},\n" +
            "\t\"shoppingScenarioDtl\": [{\n" +
            "\t\t\t\"ssdRowId\": 1,\n" +
            "\t\t\t\"quantity\": 5,\n" +
            "\t\t\t\"longContractCode\": null,\n" +
            "\t\t\t\"materialNo\": \"130014340\",\n" +
            "\t\t\t\"brand\": null,\n" +
            "\t\t\t\"equipmentParts\": \"设备部位\",\n" +
            "\t\t\t\"centralizedProcurement\": \"集中采购\",\n" +
            "\t\t\t\"strategicGoods\": \"战略物资\"" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"ssdRowId\": 2,\n" +
            "\t\t\t\"quantity\": 6,\n" +
            "\t\t\t\"longContractCode\": null,\n" +
            "\t\t\t\"materialNo\": \"130011913\",\n" +
            "\t\t\t\"brand\": null,\n" +
            "\t\t\t\"equipmentParts\": \"设备部位1\",\n" +
            "\t\t\t\"centralizedProcurement\": \"集中采购1\",\n" +
            "\t\t\t\"strategicGoods\": \"战略物资1\"" +
            "\t\t}\n" +
            "\t]\n" +
            "}",
            httpMethod = "POST")
    @RequiresPermissions("shoppingScenario-createScenario")
    public ResponseResult createScenario(@RequestBody JSONObject jsonObject) {
        try{
            return iShoppingScenarioService.createScenario(jsonObject);
        } catch (Exception e){
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateScenario")
    @ApiOperation(value = "更新工厂请购场景表头及行",notes = "更新工厂请购场景，uuid 作为唯一主键不可修改，werks、scenarioId不可修改，传入json字符串参考：\n" +
            "{\n" +
            "\t\"shoppingScenario\": {\n" +
            "\t\"uuid\": \"429ecfbda9ba43e8a03b90945300f568\",\n" +
            "\t\"scenarioName\": \"GF01xx电机维修场景\",\n" +
            "\t\"scenarioDesc\": \"GF01xx电机维修场景描述\",\n" +
            "\t\"machineNo\": \"machine no\",\n" +
            "\t\"machineDesc\": \"设备描述\",\n" +
            "\t\"remarks\": null,\n" +
            "\t\"isDelete\": \"0\",\n" +
            "\t\"updateUser\": \"20001\"\n" +
            "\t},\n" +
            "\t\"shoppingScenarioDtl\": [{\n" +
            "\t\t\t\"ssdRowId\": 1,\n" +
            "\t\t\t\"quantity\": 5,\n" +
            "\t\t\t\"longContractCode\": null,\n" +
            "\t\t\t\"materialNo\": \"130014340\",\n" +
            "\t\t\t\"brand\": null,\n" +
            "\t\t\t\"equipmentParts\": \"设备部位\",\n" +
            "\t\t\t\"centralizedProcurement\": \"集中采购\",\n" +
            "\t\t\t\"strategicGoods\": \"战略物资\"" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"ssdRowId\": 2,\n" +
            "\t\t\t\"quantity\": 6,\n" +
            "\t\t\t\"longContractCode\": null,\n" +
            "\t\t\t\"materialNo\": \"130011913\",\n" +
            "\t\t\t\"brand\": null,\n" +
            "\t\t\t\"equipmentParts\": \"设备部位1\",\n" +
            "\t\t\t\"centralizedProcurement\": \"集中采购1\",\n" +
            "\t\t\t\"strategicGoods\": \"战略物资1\"" +
            "\t\t}\n" +
            "\t]\n" +
            "}" ,
            httpMethod = "POST")
    public ResponseResult updateScenario(@RequestBody JSONObject jsonObject) {
        try{
            return iShoppingScenarioService.updateScenario(jsonObject);
        } catch (Exception e){
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }

    @RequestMapping("/updateScenarioDtl")
    @ApiOperation(value = "更新工厂请购场景明细",notes = "更新工厂请购场景明细，uuid 作为唯一主键不可修改，传入json字符串参考：\n" +
            "{\n" +
            "\t\"uuid\": \"9463644cb2a941c881e88c76d12b62fw\",\n" +
            "\t\"shoppingScenarioDtl\": [{\n" +
            "\t\t\t\"ssdRowId\": 1,\n" +
            "\t\t\t\"quantity\": 5,\n" +
            "\t\t\t\"longContractCode\": null,\n" +
            "\t\t\t\"materialNo\": \"130014340\",\n" +
            "\t\t\t\"brand\": null\n" +
            "\t\t},\n" +
            "\t\t{\n" +
            "\t\t\t\"ssdRowId\": 2,\n" +
            "\t\t\t\"quantity\": 6,\n" +
            "\t\t\t\"longContractCode\": null,\n" +
            "\t\t\t\"materialNo\": \"130011913\",\n" +
            "\t\t\t\"brand\": null\n" +
            "\t\t}]\n" +
            "}" ,
            httpMethod = "POST")
    @RequiresPermissions("shoppingScenario-updateScenarioDtl")
    public ResponseResult updateScenarioDtl(@RequestBody JSONObject jsonObject) {
        try{
            return iShoppingScenarioService.updateScenarioDtl(jsonObject);
        } catch (Exception e){
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }


    @RequestMapping("/deleteScenarios")
    @ApiOperation(value = "删除多个请购场景",notes = "删除多个请购场景示例参数：[\"239ecfbda9ba43e8a03b90945300f568\", \"429ecfbda9ba43e8a03b90945300f568\"]",
            httpMethod = "POST")
    @RequiresPermissions("shoppingScenario-deleteScenarios")
    public ResponseResult deleteScenarios(@RequestBody String[] scenarioUuid) {
        try{
            return iShoppingScenarioService.deleteScenarios(scenarioUuid);
        } catch (Exception e){
            return ResponseResult.error("请求异常请重试:" + e);
        }
    }
    
    @SuppressWarnings({ "unchecked", "rawtypes", "resource" })
	@RequestMapping("/importScenarioDtlExcel")
    @ApiOperation(value = "Excel导入常用清单行", notes = "请求参数示例：{ avatar: file}", httpMethod = "POST")
    @ResponseBody
    public ResponseResult importSafetyInventoryExcel(@RequestParam(value = "avatar") MultipartFile avatar){
    	List<Map<String, Object>> safetyList = new ArrayList<Map<String, Object>>();
    	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);
                // 2.上传附件至minIO文件服务器
                //String fileUrl = iFileOperationService.fileUploader(fileName, filePath);
                //return ResponseResult.success().add("imageUrl",fileUrl);
                temp = new File(filePath);
                is = new FileInputStream(temp);
                Workbook wb;
                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 {
                	int ssdRowId = 1;
                    for (int i = 2; i <= rowNum; i++) {//正式数据从第三行开始
                        row = sheet.getRow(i);
                        // 手工转化
                        if (row == null){
                            continue;
                        }
                        Map<String, Object> map=new HashMap<>();
                        String cell0 = ExportExcel.getCellFormatValue(row.getCell(0));
                        if (StringUtils.isEmpty(cell0)) {
                        	return ResponseResult.error("第"+(i+1)+"行“工厂代码”不能为空！");
                        }
                        String cell1 = ExportExcel.getCellFormatValue(row.getCell(1));
                        if(StringUtils.isNotEmpty(cell1)){
                        	map.put("equipmentParts", cell1);//设备部位
                        }else{
                            return ResponseResult.error("第"+(i+1)+"行“设备部位”不能为空！");
                        }
                        String cell2 = ExportExcel.getCellFormatValue(row.getCell(2));
                        if(StringUtils.isNotEmpty(cell2)){
                        	map.put("materialNo", cell2);//物料编码
                        }else{
                        	return ResponseResult.error("第"+(i+1)+"行“物料编码”不能为空！");
                        }
                        // 判断物料编码是否存在
                        ResponseResult materialSapXM = iMaterialSapService.getMaterialSapXM(cell2);
                        Map<String, Object> materialMap = materialSapXM.getData();
                        if (MapUtils.isEmpty(materialMap)) {
                        	return ResponseResult.error("第"+(i+1)+"行“物料编码”不存在！");
                        }
                        List<MaterialSap> materialList = (List<MaterialSap>) materialMap.get("materialList");
                        if (CollectionUtils.isEmpty(materialList)) {
                        	return ResponseResult.error("第"+(i+1)+"行“物料编码”不存在！");
                        }
//                        String cell5 = ExportExcel.getCellFormatValue(row.getCell(5));
//                    	map.put("basicUnit", materialList.get(0).getBasicUnit());// 基本单位
                        // 根据工厂+物料编码查询安全库存表信息
                        SafetyInventorySearchDTO dto = new SafetyInventorySearchDTO();
                        dto.setWerks(cell0);
                        dto.setMaterialNo(cell2);
                        dto.setCurrent(1);
                        dto.setSize(Integer.MAX_VALUE);
                        IPage inventoryPage = iSafetyInventoryService.getSafetyInventoryPage(dto);
                        List<Map<String, Object>> inventoryList = inventoryPage.getRecords();
                        if (CollectionUtils.isNotEmpty(inventoryList)) {
                        	map.put("safetyQtyBasicUnit", inventoryList.get(0).get("safetyQtyBasicUnit"));// 安全库存
                        	map.put("safetyInventoryYear", inventoryList.get(0).get("safetyInventoryYear"));//安全库存年限
                        	map.put("standardConsumptionLastYear", inventoryList.get(0).get("standardConsumptionLastYear"));//上年度使用量
                        	
                        	map.put("inventoryQuantity", 0);//库存数量
                        	map.put("wayQuantity", 0);//在途库存
                        	map.put("supplementQuantity", 0);//补充数量:数量+库存数量+在途库存-安全库存数量
                        	
                        	// 根据安全库存的ABC分类判断是易损件C、常用件B还是战略物资A
                        	if (StringUtils.isNotEmpty(inventoryList.get(0).get("classify").toString())) {
                        		// 三个字段合并成一个字段显示 2022-11-22 xzp update
                        		map.put("strategicGoods", inventoryList.get(0).get("classify").toString());
//                        		if ("A".equals(inventoryList.get(0).get("classify").toString())) {
//                        			map.put("strategicGoods", "A");
//                        		} else if ("B".equals(inventoryList.get(0).get("classify").toString())) {
//                        			map.put("commonParts", "B");
//                        		} else if ("C".equals(inventoryList.get(0).get("classify").toString())) {
//                        			map.put("wearingParts", "C");
//                        		}
                        	}
                        } else {
                        	map.put("safetyQtyBasicUnit", 0);// 安全库存
                        	map.put("safetyInventoryYear", 0);//安全库存年限
                        	map.put("standardConsumptionLastYear", 0);//上年度使用量
                        	map.put("inventoryQuantity", 0);//库存数量
                        	map.put("wayQuantity", 0);//在途库存
                        	map.put("supplementQuantity", 0);//补充数量:数量+库存数量+在途库存-安全库存数量
                        }
                        
                        String cell3 = ExportExcel.getCellFormatValue(row.getCell(3));
                        map.put("materialZhDesc", cell3);// 物料描述
//                        String cell4 = ExportExcel.getCellFormatValue(row.getCell(4));
//                        if(StringUtils.isNotEmpty(cell4)){
//                        	map.put("quantity", cell4);//数量
//                        }else{
//                        	return ResponseResult.error("第"+(i+1)+"行“数量”不能为空！");
//                        }
                        String cell4 = ExportExcel.getCellFormatValue(row.getCell(4));
                        map.put("centralizedProcurement", cell4);// 集中采购
                    	String cell6 = ExportExcel.getCellFormatValue(row.getCell(5));
                    	map.put("rowComment", cell6);//备注
                        // 行号
                    	map.put("ssdRowId", ssdRowId+"0");
                        safetyList.add(map);
                        ++ssdRowId;
                    }
                }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("shoppingScenarioDtl", safetyList).add("msg","S");
        }
    }
}
