package com.tykj.dev.device.excel.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.excel.utils.ExcelStyleUtil;
import com.tykj.dev.device.excel.utils.ExcelUtil;
import com.tykj.dev.device.library.repository.DeviceLibraryDao;
import com.tykj.dev.device.library.service.DeviceLibraryService;
import com.tykj.dev.device.library.subject.domin.DeviceLibrary;
import com.tykj.dev.device.library.subject.vo.DeviceExcel;
import com.tykj.dev.misc.utils.MapperUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
 * @author zjm
 */
@RestController
@RequestMapping(value = "/excel")
@AutoDocument
@Api(tags = "excel", value = "excel")
public class ExeclController {

    @Autowired
    DeviceLibraryDao deviceLibraryDao;

    @Autowired
    DeviceLibraryService deviceLibraryService;

    /**
     * 保存报废草稿
     */
    @GetMapping(value ="/test")
    @ApiOperation(value = "下载培训excel", notes = "下载培训excel")
    public ResponseEntity saveDeviceDestroyBill(HttpServletRequest request, HttpServletResponse response){
        List<DeviceExcel> excelList=deviceLibraryDao.findAll().stream()
                .filter(deviceLibrary -> deviceLibrary.getLifeStatus()==12&& "浙江省委机要局".equals(deviceLibrary.getOwnUnit()))
                .map(DeviceLibrary::parseExcel)
                .sorted(Comparator.comparing(DeviceExcel::getSeqNumber,Comparator.nullsLast(String::compareTo)).thenComparing(DeviceExcel::getName))
                .collect(Collectors.toList());
//        Map<String,List<DeviceExcel>> map = excelList.stream().collect(groupingBy(DeviceExcel::getSeqNumber));
//        List<DeviceExcel> deviceExcels= new ArrayList<>();
//        for (String s : map.keySet()){
//            List<DeviceExcel> deviceExcelList= map.get(s);
//            if (deviceExcelList.size()>1){
//                deviceExcels.addAll(deviceExcelList);
//            }
//            else {
//                DeviceExcel deviceExcel = deviceExcelList.get(0);
//                if (deviceExcel.getSeqNumber().length()<=5||deviceExcel.getSeqNumber().equals(deviceExcel.getProdNumber())){
//                    deviceExcels.add(deviceExcel);
//                }
//            }
//        }
//        deviceExcels = deviceExcels.stream()
//                .sorted(Comparator.comparing(DeviceExcel::getSeqNumber,Comparator.nullsLast(String::compareTo)).thenComparing(DeviceExcel::getName))
//                .collect(Collectors.toList());

        ExportParams exportParams = new ExportParams("xxx","xxx", ExcelType.XSSF);
        exportParams.setStyle(ExcelStyleUtil.class);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, DeviceExcel.class, excelList);
        ExcelUtil.downloadExcel(request, response, workbook, "xxx");
//        List<TrainUserExcel> tableInfoVos = new ArrayList<>();
//        for (int i=0;i<6;i++){
//            TrainUserExcel trainUserExcel=new TrainUserExcel();
//            trainUserExcel.setIdCard("123123123131");
//            trainUserExcel.setMobel("15171636570");
//            trainUserExcel.setName("占金明");
//            trainUserExcel.setSex("男");
//            trainUserExcel.setNumber(i);
//            tableInfoVos.add(trainUserExcel);
//        }
//        ExportParams exportParams = new ExportParams("xxx","xxx", ExcelType.XSSF);
//        exportParams.setStyle(ExcelStyleUtil.class);
//        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, TrainUserExcel.class, tableInfoVos);
//        ExcelUtil.downloadExcel(request, response, workbook, "xxx");
        return ResponseEntity.ok("ok");
    }



    @PostMapping(value ="/test1")
    @ApiOperation(value = "导入excel", notes = "下载培训excel")
    public ResponseEntity importExcel(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        // 开启Excel校验
//      params.setNeedVerfiy(true);
//      params.setVerifyHandler(excelVerifyHandle);

        Workbook workbook = WorkbookFactory.create(file.getInputStream());
        Sheet sheet = workbook.getSheet(workbook.getSheetName(0));
        //获取第一行
//        Row titlerow = sheet.getRow(0);
//        String tableName = titlerow.getCell(0).getStringCellValue();

        ExcelImportResult<DeviceExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), DeviceExcel.class,
                params);
        List<DeviceExcel> deviceExcels= result.getList();
        Map<Integer,DeviceLibrary> deviceLibraryMap = deviceLibraryService.getAllDeviceMap();
        for (DeviceExcel d:deviceExcels){
            DeviceLibrary deviceLibrary = deviceLibraryMap.get(d.getId());
            MapperUtils.copyNoNullProperties(d,deviceLibrary);
            deviceLibraryService.update(deviceLibrary);
        }
        return ResponseEntity.ok(deviceExcels.size());
    }

}
