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.extension.plugins.pagination.Page;
import com.sunda.spmscommon.ResponseResult;
import com.sunda.spmsorder.entity.MaterialPriceImport;
import com.sunda.spmsorder.entity.MaterialSap;
import com.sunda.spmsorder.mapper.MaterialSapMapper;
import com.sunda.spmsorder.service.IFileOperationService;
import com.sunda.spmsorder.service.IMaterialPriceImportService;
import com.sunda.spmsorder.vo.MaterialPriceImportVO;
import com.sunda.spmsuser.service.ISpmsUserWhsService;
import com.sunda.spmsweb.util.JWTUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.SecurityUtils;
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
 * @since 2024-04-27
 */
@RestController
@Slf4j
@RequestMapping("/material-price-import")
public class MaterialPriceImportController {

    @Autowired
    IMaterialPriceImportService materialPriceImportService;

    @Autowired
    IFileOperationService iFileOperationService;
    @Autowired
    ISpmsUserWhsService iSpmsUserWhsService;

    @Autowired
    MaterialSapMapper materialSapMapper;

    @RequestMapping("/getMaterialPriceList")
    @ApiOperation(value = "获取全部物料价格信息",notes = "获取全部物料价格信息 \n" +
            "{\n" +
            "\t\"materialNumber\": \"213213123\",\n" +
            "\t\"werks\": [\"CN01\"]\n" +
            "}", httpMethod = "POST")
    public ResponseResult getMaterialPriceList(@RequestBody MaterialPriceImportVO record){
        try {
            if(record.getFactory()==null ) {
                throw new Exception("工厂代码不能为空！");
            }
            return materialPriceImportService.getMaterialPriceList(record);
        }catch (Exception e){
            log.error("获取物料价格出错:"+e.getMessage());
            return ResponseResult.error("获取物料价格出错");
        }
    }



//
//    @RequestMapping("/insertMaterialPrice")
//    @ApiOperation(value = "新建物料价格",notes = "新建物料价格", httpMethod = "POST")
//    public ResponseResult insertMaterialPrice(@RequestBody MaterialPriceImport materialPriceImport){
//        return materialPriceImportService.insertMaterialPrice(materialPriceImport);
//    }



    @RequestMapping("/uploadMaterialPrice")
    @ApiOperation(value = "上传物料价格Excel文件导入", notes = "请求参数示例：{ avatar: file}", httpMethod = "POST")
    @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 {
                String userId = JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                // 另存文件名
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                Calendar calendar = Calendar.getInstance();
                String fileName = df.format(calendar.getTime()) + avatar.getOriginalFilename();
                // 1.附件缓存路径
                String filePath = iFileOperationService.saveMaterialApplicationPic(avatar, fileName);
                log.info("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 <= 2) {
                    return ResponseResult.error("请检查文件内容是否为空！");
                }
                try {
                    List<MaterialPriceImport> prices = new ArrayList<MaterialPriceImport>();
                    for (int i = 3; i <= rowNum; i++) {//正式数据从第四行开始
                        row = sheet.getRow(i);
                        // 手工转化
                        if (row == null){
                            continue;
                        }
                        MaterialPriceImport materialPriceImport=new MaterialPriceImport();
                        if(row.getCell(0)!=null){
                            row.getCell(0).setCellType(CellType.STRING);
                            materialPriceImport.setFactory(row.getCell(0).getRichStringCellValue().getString());//工厂代码
                        }else{
                            return ResponseResult.error("第"+i+"行“工厂代码”不能为空！");
                        }
                        if(row.getCell(1)!=null){
                            row.getCell(1).setCellType(CellType.STRING);
                            materialPriceImport.setMaterialNo(row.getCell(1).getRichStringCellValue().getString());//物料编码
                        }else{
                            return ResponseResult.error("第"+i+"行“物料编码”不能为空！");
                        }
//                        if(row.getCell(2)!=null){
//                            row.getCell(2).setCellType(CellType.STRING);
//                            materialPriceImport.setMaterialNo(row.getCell(2).getRichStringCellValue().getString());//物料描述
//                        }else{
//                            return ResponseResult.error("第"+i+"行“物料描述”不能为空！");
//                        }
                        if(row.getCell(3)!=null){
                            row.getCell(3).setCellType(CellType.STRING);
                            materialPriceImport.setPrice(row.getCell(3).getRichStringCellValue().getString());//物料单价
                        }else{
                            return ResponseResult.error("第"+i+"行“物料单价”不能为空！");
                        }
                        if(row.getCell(4)!=null){
                            row.getCell(4).setCellType(CellType.STRING);
                            materialPriceImport.setCurrency(row.getCell(4).getRichStringCellValue().getString());//币种
                        }else{
                            return ResponseResult.error("第"+i+"行“货币”不能为空！");
                        }
                        if(row.getCell(5)!=null){
                            row.getCell(5).setCellType(CellType.STRING);
                            Date startDate = sdf.parse(row.getCell(5).getRichStringCellValue().getString());
                            materialPriceImport.setStartDate(startDate);//有效起始日期
                        }else{
                            return ResponseResult.error("第"+i+"行“有效起始日期”不能为空！");
                        }
                        if(row.getCell(6)!=null){
                            row.getCell(6).setCellType(CellType.STRING);
                            Date endDate = sdf.parse(row.getCell(6).getRichStringCellValue().getString());
                            materialPriceImport.setEndDate(endDate);//有效截止日期
                        }else{
                            return ResponseResult.error("第"+i+"行“有效截止日期”不能为空！");
                        }
                        prices.add(materialPriceImport);
                        List<Map<String, Object>> userWhsList = iSpmsUserWhsService.getUserWhsList(userId);
                        boolean factoryExist = false;
                        for (Map<String, Object> userWhs:userWhsList){
                            if(materialPriceImport.getFactory().equals(userWhs.get("werks"))){
                                factoryExist = true;//存在对应的工厂
                            }
                        }
                        if(!factoryExist){
                            return ResponseResult.error("第"+i+"行“工厂不存在”请检查！");
                        }
                        MaterialSap materialSap=materialSapMapper.selectOne(new QueryWrapper<MaterialSap>().eq("MATERIAL_NO", materialPriceImport.getMaterialNo()));
                        if(materialSap!=null){
                            if("X".equals(materialSap.getOnMall()) && !"X".equals(materialSap.getIsDelete())
                                && !materialSap.getMaterialStatus().contains("Z1")
                                    && !materialSap.getMaterialStatus().contains("Z3")
                                        && !materialSap.getMaterialStatus().contains("Z5")){
                                //物料是上架的，并且未删除的
                            }else{
                                return ResponseResult.error("第"+i+"行“物料编码不存在”请检查！");
                            }
                        }else{
                            return ResponseResult.error("第"+i+"行“物料编码不存在”请检查！");
                        }

                        int res = materialPriceImportService.insertMaterialPrice(materialPriceImport,userId);
//                        if(100==res.getCode()){
//                            return ResponseResult.error(res.getMsg());
//                        }
                    }
                }catch (Exception e) {
                    return ResponseResult.error(e.getMessage());
                }
            }catch (Exception e) {
                log.error("导入物料价格出错:"+e.getMessage());
                return ResponseResult.error(e.getMessage());
            } finally {
                if (temp != null) {
                    boolean newFile = temp.delete();
                    if(!newFile){
                        //log.error(temp+"删除失败");
                    }
                }
            }

            return ResponseResult.success().add("msg","S");
        }
    }

}
