package com.ruoyi.interfaces.controller;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.interfaces.core.page.Page;
import com.ruoyi.interfaces.core.page.PageUtils;
import com.ruoyi.interfaces.domain.PtDataImp;
import com.ruoyi.interfaces.domain.PtDataImpField;
import com.ruoyi.interfaces.domain.SysCate;
import com.ruoyi.interfaces.mapper.PtDataImpMapper;
import com.ruoyi.interfaces.service.SysCateService;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/pt/data/imp")
public class PtDataImpController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(PtDataImpController.class);

    @Autowired
    private PtDataImpMapper ptDatImpMapper;

    @Autowired
    private SysCateService sysCateService;

    @ApiOperation("添加数据导入")
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public AjaxResult insert(PtDataImp p, String json) {
        p.setId(IdUtils.simpleUUID());
        int insert = ptDatImpMapper.insert(p);
        if (insert > 0) {
            //添加详情
            if (json != null && !"".equals(json)) {
                String[] strs = json.split(";");
                for (String str : strs) {
                    PtDataImpField ptDataImpField = JSONObject.parseObject(str, PtDataImpField.class);
                    ptDataImpField.setId(p.getId());
                    ptDataImpField.setFid(IdUtils.simpleUUID());
                    ptDatImpMapper.insertPtDatImpField(ptDataImpField);
                }
            }
            return AjaxResult.success(p.getId());
        }
        return AjaxResult.error();
    }

    @ApiOperation("查询数据导入")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public Page selectAll(int page, int rows, PtDataImp ptDataImp) {
        PageHelper.startPage(page, rows);
        List<PtDataImp> list = ptDatImpMapper.selectAll(ptDataImp);
        PageInfo<PtDataImp> pageInfo = new PageInfo<>(list);
        return PageUtils.convert(pageInfo);
    }

    @ApiOperation("修改数据导入")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public AjaxResult update(PtDataImp p, String json) {
        System.out.println(p);
        int update = ptDatImpMapper.update(p);
        System.out.println("update" + update);
        //修改详情
        PtDataImpField ptDataImpField2 = new PtDataImpField();
        ptDataImpField2.setId(p.getId());
        if (update > 0) {
            ptDatImpMapper.deletePtDataImpField(ptDataImpField2);
            if (json != null && !"".equals(json)) {
                String[] strs = json.split(";");
                for (String str : strs) {
                    PtDataImpField ptDataImpField = JSONObject.parseObject(str, PtDataImpField.class);
                    ptDataImpField.setId(p.getId());
                    ptDataImpField.setFid(IdUtils.simpleUUID());
                    ptDatImpMapper.insertPtDatImpField(ptDataImpField);
                }
            }
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @ApiOperation("删除数据导入")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public AjaxResult delete(String ids) {
        String[] strs = ids.split(",");
        int deletes = 0;
        for (String str : strs) {
            //查询是否存在子类
            PtDataImpField pt = new PtDataImpField();
            pt.setId(str);
            ptDatImpMapper.deletePtDataImpField(pt);
            deletes += ptDatImpMapper.delete(str);
        }
        if (deletes == strs.length) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @ApiOperation("删除操作")
    @RequestMapping(value = "/delete_imp_field")
    public AjaxResult deleteImpField(PtDataImpField pf) {
        int delete = ptDatImpMapper.deletePtDataImpField(pf);
        if (delete > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @ApiOperation("跳到数据导入修改页面")
    @RequestMapping(value = "/to_update", method = RequestMethod.GET)
    public ModelAndView toUpdatePtDataImpField(String id, String impType) {
        ModelAndView model = new ModelAndView();
        model.addObject("ptDataImp", ptDatImpMapper.findByOne(id));
        model.addObject("data", impExcelList);
        model.addObject("impType", impType);
        model.setViewName("mng/pt_data_imp_edit");
        return model;
    }

    @ApiOperation("根据数据导入查询导入字段")
    @RequestMapping(value = "/select_imp_field")
    public List<PtDataImpField> selectField(PtDataImpField p) {
        List<PtDataImpField> list = null;
        list = ptDatImpMapper.selectAllPtDatImpField(p);
        return list;
    }


    @ApiOperation("数据列表")
    @RequestMapping(value = "/cate_list", method = RequestMethod.GET)
    public List<SysCate> list(String tabName) {
        SysCate criteria = new SysCate();
        criteria.setCateTable(tabName);
        return sysCateService.findAllO(criteria);//.selectByCriteria(criteria);//查询
    }

    @ApiOperation("导出数据到本地")
    @RequestMapping(value = "/export_excel", method = RequestMethod.POST)
    public AjaxResult exportExcel(String id, String fileName) {
        PtDataImpField ptDataImpField = new PtDataImpField();
        ptDataImpField.setId(id);
        List<PtDataImpField> list = ptDatImpMapper.selectAllPtDatImpField(ptDataImpField);
        if (list.size() == 0) {
            //AjaxResult.error("模板无内容");
        }
        return AjaxResult.success(expExcel(list));

    }

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
    @Value("${sys.report.upload.path}")
    private String reportPath;

    public String expExcel(List<PtDataImpField> list) {
        String fileName = "数据导入模板" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String path = "E:\\excel文件\\" + fileName + ".xls";

        String tmpPath = sdf.format(new Date());
        String filePath = reportPath + tmpPath;
        //  清空临时文件夹
        OutputStream os = null;
        Workbook book = null;

        try {
            if (!new File(filePath).exists()) {
                new File(filePath).mkdirs();
            }
            String id = IdUtils.simpleUUID();
            // 输出流
            os = new FileOutputStream(filePath + "/" + id + ".xls");
            // 创建工作区(97-2003)
            book = new HSSFWorkbook();
            // 创建第一个sheet页
            Sheet sheet = book.createSheet(fileName);
            // 生成行数,对应的list集合长度
            for (int i = 0; i < 2; i++) {
                Row row = sheet.createRow(i);
                //给每一行的每一列赋值
                if (i == 0) {
                    for (int j = 0; j < list.size(); j++) {
                        row.createCell(j).setCellValue(list.get(j).getCode());
                    }
                }
                if (i == 1) {
                    for (int j = 0; j < list.size(); j++) {
                        row.createCell(j).setCellValue(list.get(j).getName());
                    }
                }
            }
            // 写文件
            book.write(os);
            /*http://127.0.0.1:8083/gxpt/report/2018/09/19/1042325997479800832.xlsx*/
            return tmpPath + "/" + id + ".xls";
        } catch (FileNotFoundException e) {
            return "";
        } catch (IOException e) {
            return "";
        } finally {
            // 关闭输出流
            try {
                os.close();
            } catch (IOException e) {
                logger.error(e.getLocalizedMessage(), e);
            }
        }

    }

    private static List<PtDataImpField> impExcelList = null;

    @ApiOperation("从本地导入数据到数据库")
    @RequestMapping(value = "/import_excel", method = RequestMethod.POST)
    public AjaxResult impExcel(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws IOException {
        String path = "E:\\excel文件";
        //  清空临时文件夹
//        FileUtils.deleteDir(new File(path));
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String uuid = IdUtils.simpleUUID();
        //1、判断目录。如果目录不存在，则创建目录
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //2、写入文件
        file.transferTo(new File(path + "/" + uuid + "." + suffix));
        List<PtDataImpField> impExcelList = impExcel(path + "/" + uuid + "." + suffix);
        return AjaxResult.success(impExcelList);
    }

    /**
     * 导入Excel
     *
     * @param
     */
    public List<PtDataImpField> impExcel(String inputStream) {
        List<PtDataImpField> list = new ArrayList<>();
        try {
            // 构造 Workbook 对象，execelFile 是传入文件路径(获得Excel工作区)
            Workbook book = null;
            try {
                // Excel 2007获取方法
                book = new XSSFWorkbook(new FileInputStream(inputStream));
            } catch (Exception ex) {
                // Excel 2003获取方法
                book = new HSSFWorkbook(new FileInputStream(inputStream));
            }

            // 读取表格的第一个sheet页
            Sheet sheet = book.getSheetAt(0);

            // 定义 row、cell
            Row row;
            String cell;
            // 总共有多少行,从0开始
            int totalRows = 1;

            // 循环输出表格中的内容,首先循环取出行,再根据行循环取出列
            for (int i = 0; i < totalRows; i++) {
                row = sheet.getRow(i);
                // 处理空行
                if (row == null) {
                    continue;
                }
                // 总共有多少列,从0开始
                int totalCells = row.getLastCellNum();
                for (int j = row.getFirstCellNum(); j < totalCells; j++) {
                    PtDataImpField ptDataImpField = new PtDataImpField();
                    // 获取单元格内容
                    //  cell = sheet.getRow(0).getCell(j).toString();
                    // cell = sheet.getRow(0).getCell(j).toString();
                    ptDataImpField.setCode(sheet.getRow(0).getCell(j).toString());
                    ptDataImpField.setName(sheet.getRow(1).getCell(j).toString());

                    ptDataImpField.setType("1");
                    ptDataImpField.setPosX(j + 1);
                    ptDataImpField.setSeq(j + 1);
                    ptDataImpField.setPosY(0);
                    ptDataImpField.setLength("0");
                    ptDataImpField.setId(list.size() + "");
                    list.add(ptDataImpField);
                }
            }
        } catch (FileNotFoundException e) {
            logger.error(e.getLocalizedMessage(), e);
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage(), e);
        }
        return list;
    }

    @ApiOperation("导入数据进入数据库")
    @RequestMapping(value = "/import_data", method = RequestMethod.POST)
    public AjaxResult impModel(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request, PtDataImp ptDataImp) throws IOException {
        String path = "E:\\excel文件";
        //  清空临时文件夹
//        FileUtils.deleteDir(new File(path));
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String uuid = IdUtils.simpleUUID();
        //1、判断目录。如果目录不存在，则创建目录
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //2、写入文件
        file.transferTo(new File(path + "/" + uuid + "." + suffix));
        return impModel(path + "/" + uuid + "." + suffix, ptDatImpMapper.findByOne(ptDataImp.getId()));
    }

    /**
     * 导入模板
     *
     * @param
     */
    public AjaxResult impModel(String inputStream, PtDataImp ptDataImp) {
        try {
            Workbook book = null;
            try {
                // Excel 2007获取方法
                book = new XSSFWorkbook(new FileInputStream(inputStream));
            } catch (Exception ex) {
                // Excel 2003获取方法
                book = new HSSFWorkbook(new FileInputStream(inputStream));
            }

            /*根据配置的行、列进行读取Excel*/
            //开始行
            int startRow = ptDataImp.getStartRow() - 1;
            //开始列
            int startCol = ptDataImp.getStartCol() - 1;
            //结束行
            int endRow = ptDataImp.getEndRow() - 1;
            //结束列
            int endCol = ptDataImp.getEndCol();

            // 读取表格的第一个sheet页
            Sheet sheet = book.getSheetAt(0);
            Row row;
            String cell;
            // 循环输出表格中的内容,首先循环取出行,再根据行循环取出列
//            for (int i = startRow; i <= endRow; i++) {
//                row = sheet.getRow(i);
//                if (row == null) {
//                    continue;
//                }
//                Test test = new Test();
//                for (int j = startCol; j < endCol; j++) {
//                    // 处理空列
//                    if (row.getCell(j) == null) {
//                        continue;
//                    }
//                    // 通过 row.getCell(j).toString() 获取单元格内容
//                    cell = row.getCell(j).toString();
//                    if (j == 0) {
//                        test.setId(cell);
//                    }
//                    if (j == 1) {
//                        test.setName(cell);
//                    }
//                    System.out.print(cell + "\t");
//                }
//                if (test.getId() != null || test.getName() != null) {
//                    ptDatImpMapper.insertTest(test);
//                }
//            }
        } catch (FileNotFoundException e) {
            return AjaxResult.error();
        } catch (IOException e) {
            return AjaxResult.error();
        }
        return AjaxResult.success();
    }

}
