package com.ruoyi.interfaces.controller;

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.PageUtils;
import com.ruoyi.interfaces.domain.PtReport;
import com.ruoyi.interfaces.domain.PtReportFile;
import com.ruoyi.interfaces.domain.SysCate;
import com.ruoyi.interfaces.mapper.PtReportDAO;
import com.ruoyi.interfaces.mapper.PtReportFileMapper;
import com.ruoyi.interfaces.mapper.SqlMapper;
import com.ruoyi.interfaces.service.SysCateService;
import io.swagger.annotations.ApiOperation;
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.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/pt/report")
public class PtReportController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(PtReportController.class);

    @Value("${sys.report.upload.path}")
    private String reportPath;

    @Autowired
    private PtReportDAO BDAO;

    @Autowired
    private SysCateService sysCateService;
    @Autowired
    private PtReportFileMapper PFMapper;

    @ApiOperation("添加报表服务")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult insertBaoBiaoFuWu(PtReport bao) {
        bao.setCode(IdUtils.simpleUUID());
        bao.setPubTime(new Date());
        bao.setPubUser("");
        int success = BDAO.insert(bao);
        if (success > 0) {
            AjaxResult b = AjaxResult.success();
            return b;
        }
        return AjaxResult.error();
    }

    @ApiOperation("数据列表")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public com.ruoyi.interfaces.core.page.Page getList(@RequestParam(required = false, defaultValue = "1") int page,
                                                       @RequestParam(required = false, defaultValue = "100") int rows, PtReport ptReport) {
        PageHelper.startPage(page, rows);
        PageHelper.orderBy("PUB_TIME desc");
        List<PtReport> list = BDAO.selectAll(ptReport);//dao.(criteria);//查询
        // 取分页信息
        PageInfo<PtReport> pageInfo = new PageInfo<PtReport>(list);
        return PageUtils.convert(pageInfo);
    }

    @ApiOperation("去编辑页面")
    @RequestMapping(value = "/to_edit", method = RequestMethod.GET)
    public ModelAndView toEdit(String code) {
        ModelAndView model = new ModelAndView();
        PtReport pt = new PtReport();
        pt.setCode(code);
        model.addObject("ptReport", BDAO.selectAll(pt).get(0));
        //查询是否存在文件
        model.addObject("ptPeportFile", PFMapper.selectCodeFile(code));
        model.setViewName("mng/pt_report_edit");
        return model;
    }

    @ApiOperation("修改报表服务")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult updateptReoprt(PtReport bao) {
        bao.setPubTime(new Date());
        bao.setPubUser("");
        int update = BDAO.update(bao);
        if (update > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @ApiOperation("批量删除")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @Transactional
    public AjaxResult deletePtReport(String codes) {
        String[] strs = codes.split(",");
        int deletes = 0;
        for (String str : strs) {
            //删除之前先查附件，有附件也删除,防止出现子记录
            PtReportFile pf = PFMapper.selectCodeFile(str);
            if (pf != null) {
                int deleteFile = PFMapper.deleteByPrimaryKey(pf.getFileId());
            }
            int delete = BDAO.delete(str);
            deletes += delete;
        }
        if (deletes == strs.length) {
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }


    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

    @ApiOperation("文件导入")
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request, PtReport bao) {

        //第一步：写入文件
        String fileName = file.getOriginalFilename();
        //如果不是空的，就新增文件
        if (fileName != null && !"".equals(fileName)) {
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String uuid = IdUtils.simpleUUID();
            try {
                String tmpPath = sdf.format(new Date());
                String filePath = reportPath + tmpPath;
                //1、判断目录。如果目录不存在，则创建目录
                File dir = new File(filePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //2、写入文件
                file.transferTo(new File(filePath + "/" + uuid + "." + suffix));

                //第二步：解析文件，返回值为List<T>

                PtReportFile ptReportFile = new PtReportFile();
                //第三步：写入数据库
                bao.setCode(IdUtils.simpleUUID());
                bao.setPubTime(new Date());
                bao.setPubUser("");
                int success = BDAO.insert(bao);
                if (success > 0) {
                    ptReportFile.setFileId(IdUtils.simpleUUID());
                    ptReportFile.setFileTime(new Date());
                    ptReportFile.setFileType(suffix);
                    ptReportFile.setFilePath(filePath + "/" + uuid + "." + suffix);
                    ptReportFile.setFileSavename(uuid);
                    ptReportFile.setFileViewname(fileName);
                    ptReportFile.setRelId("1");
                    ptReportFile.setCode(bao.getCode());
                    int insert = PFMapper.insert(ptReportFile);
                    if (insert > 0) {
                        return AjaxResult.success();
                    }
                    return AjaxResult.error();
                }
            } catch (Exception e) {
                //在此处调用
                logger.error(e.getLocalizedMessage(), e);
                return AjaxResult.error();
            }
        } else {
            bao.setCode(IdUtils.simpleUUID());
            bao.setPubTime(new Date());
            bao.setPubUser("");
            int success = BDAO.insert(bao);
            if (success > 0) {
                return AjaxResult.success();
            }
            return AjaxResult.error();
        }
        return AjaxResult.error();
    }

    @ApiOperation("文件导入")
    @RequestMapping(value = "/edit_import", method = RequestMethod.POST)
    public AjaxResult editImport(@RequestParam("file") MultipartFile file, HttpServletRequest request, PtReport bao, String fileId, String fileViewName) {

        //第一步：写入文件
        String fileName = file.getOriginalFilename();
        //如果不是空的，就新增文件
        if (fileName != null && !"".equals(fileName)) {
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String uuid = IdUtils.simpleUUID();
            try {
                String tmpPath = sdf.format(new Date());
                String filePath = reportPath + tmpPath;
                //1、判断目录。如果目录不存在，则创建目录
                File dir = new File(filePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //2、写入文件
                file.transferTo(new File(filePath + "/" + uuid + "." + suffix));

                //第二步：解析文件，返回值为List<T>

                PtReportFile ptReportFile = new PtReportFile();
                //第三步：写入数据库
                bao.setPubTime(new Date());
                bao.setPubUser("");
                int update = BDAO.update(bao);
                if (update > 0) {
                    ptReportFile.setFileId(fileId);
                    ptReportFile.setFileTime(new Date());
                    ptReportFile.setFileType(suffix);
                    ptReportFile.setFilePath(filePath + "/" + uuid + "." + suffix);
                    ptReportFile.setFileSavename(uuid);
                    ptReportFile.setFileViewname(fileName);
                    ptReportFile.setRelId("1");
                    ptReportFile.setCode(bao.getCode());
                    ptReportFile.setFileTime(new Date());
                    int update2 = PFMapper.updateByPrimaryKey(ptReportFile);
                    if (update2 > 0) {
                        return AjaxResult.success();
                    }
                    return AjaxResult.error();
                }
                return AjaxResult.error();
            } catch (Exception e) {
                //在此处调用
                logger.error(e.getLocalizedMessage(), e);
                return AjaxResult.error();
            }
        } else {
            //第三步：写入数据库
            bao.setPubTime(new Date());
            bao.setPubUser("");
            int update = BDAO.update(bao);
            if (update > 0) {
                return AjaxResult.success();
            }
            return AjaxResult.error();
        }
    }

    @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);//查询
    }

    @Autowired
    private SqlMapper sqlMapper;

    /**
     * 图形格式拼接
     *
     * @param
     * @return
     */
    @GetMapping("/to_pt_report_pre")
    public ModelAndView toPtReportPre(String code) {
        ModelAndView modelAndView = new ModelAndView();
        PtReport ptReport = new PtReport();
        ptReport.setCode(code);
        PtReport p = BDAO.selectAll(ptReport).get(0);
        List list = null, list2 = null;
        if ("混合".equals(p.getStyle())) {
            list = sqlMapper.selectAll(p.getSql());
            list2 = sqlMapper.selectAll(p.getListSql());
        } else if ("图表".equals(p.getStyle())) {
            list = sqlMapper.selectAll(p.getSql());
        } else {
            list2 = sqlMapper.selectAll(p.getListSql());
        }
        modelAndView.addObject("list", list);
        modelAndView.addObject("list2", list2);
        modelAndView.addObject("ptReport", p);
        modelAndView.setViewName("mng/pt_report_pre");
        return modelAndView;
    }
}
