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.Page;
import com.ruoyi.interfaces.core.page.PageUtils;
import com.ruoyi.interfaces.domain.PtChart;
import com.ruoyi.interfaces.domain.PtChartFile;
import com.ruoyi.interfaces.domain.SysCate;
import com.ruoyi.interfaces.mapper.PtChartFileMapper;
import com.ruoyi.interfaces.mapper.PtChartMapper;
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.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 java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

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

    @Autowired
    private PtChartMapper mapMapper;

    @Autowired
    private PtChartFileMapper ptChartFileMapper;

    @Autowired
    private SysCateService sysCateService;

    @Value("${sys.chart.upload.path}")
    private String uploadFilePath;


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

    @ApiOperation("添加数据")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult add(@RequestParam(name = "file", required = false) MultipartFile file, @RequestParam(name = "image", required = false) MultipartFile image, PtChart map) {

        if (image != null) {
            //第一步：写入文件
            String imageName = image.getOriginalFilename();
            String suffix = imageName.substring(imageName.lastIndexOf(".") + 1);
            String uuid = IdUtils.simpleUUID();
            try {
                String tmpPath = sdf.format(new Date());
                String filePath = tmpPath + "/" + uuid + "." + suffix;
                //1、判断目录。如果目录不存在，则创建目录
                File dir = new File(uploadFilePath + filePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //2、写入文件
                image.transferTo(new File(uploadFilePath + filePath));
                map.setThumb(imageName);// 缩略图名称
                map.setUrl(filePath);// 缩略图地址
            } catch (Exception e) {
                //在此处调用
                logger.error(e.getLocalizedMessage(), e);
                return AjaxResult.error();
            }
        }

        String code = IdUtils.simpleUUID();
        map.setCode(code);
        map.setPubUser("测试ID");
        map.setPubTime(new Date());
        System.out.println(map);
        int ret = mapMapper.insert(map);

        if (file != null) {
            //第一步：写入文件
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String uuid = IdUtils.simpleUUID();
            try {
                String tmpPath = sdf.format(new Date());
                String filePath = uploadFilePath + "/" + tmpPath + "/" + uuid + "." + suffix;
                //1、判断目录。如果目录不存在，则创建目录
                File dir = new File(filePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //2、写入文件
                file.transferTo(new File(filePath));
                // 3、写入数据库
                PtChartFile ptChartFile = new PtChartFile();
                ptChartFile.setFileId(IdUtils.simpleUUID());
                ptChartFile.setCode(code);
                ptChartFile.setRelId(code);
                ptChartFile.setFileType(suffix);
                ptChartFile.setFilePath(filePath);
                ptChartFile.setFileSavename(uuid);
                ptChartFile.setFileViewname(fileName);
                ptChartFile.setFileTime(new Date());
                ptChartFileMapper.insert(ptChartFile);
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e);
                return AjaxResult.error();
            }
        }
        return AjaxResult.success();
    }

    @ApiOperation("根据主键获取数据")
    @RequestMapping(value = "/get")
    public ModelAndView get(@RequestParam(required = true) String key) {
        ModelAndView mav = new ModelAndView();
        PtChart ptChart = mapMapper.selectByPrimaryKey(key);
        if (ptChart != null) {
            mav.addObject("ptChart", ptChart);
        }
        PtChartFile ptChartFile = ptChartFileMapper.selectByCode(key);
        if (ptChartFile != null) {
            mav.addObject("fileViewname", ptChartFile.getFileViewname());
            mav.addObject("fileId", ptChartFile.getFileId());
        }
        mav.setViewName("mng/pt_chart_edit");
        return mav;

    }

    @ApiOperation("数据列表")
    @RequestMapping(value = "/list")
    public Page getList(@RequestParam(required = false, defaultValue = "1") int page,
                        @RequestParam(required = false, defaultValue = "100") int rows
            , PtChart ptChart) {
        System.out.println(ptChart);
        PageHelper.startPage(page, rows);
        PageHelper.orderBy("PUB_TIME desc");
        List<PtChart> list = mapMapper.selectAll(ptChart);
        PageInfo<PtChart> pageInfo = new PageInfo<PtChart>(list);
        return PageUtils.convert(pageInfo);
    }

    @ApiOperation("根据主键更新数据")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public AjaxResult update(@RequestParam(name = "file", required = false) MultipartFile file, @RequestParam(name = "smallImage", required = false) MultipartFile smallImage, PtChart map, String fileId) {
        // 上传缩略图
        if (smallImage != null) {
            //第一步：写入文件
            String imageName = smallImage.getOriginalFilename();
            String suffix = imageName.substring(imageName.lastIndexOf(".") + 1);
            String uuid = IdUtils.simpleUUID();
            try {
                String tmpPath = sdf.format(new Date());
                String filePath = tmpPath + "/" + uuid + "." + suffix;
                //1、判断目录。如果目录不存在，则创建目录
                File dir = new File(uploadFilePath + filePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //2、写入文件
                smallImage.transferTo(new File(uploadFilePath + filePath));
                map.setThumb(imageName);// 缩略图名称
                map.setUrl(filePath);// 缩略图地址
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e);
                return AjaxResult.error();
            }
        }
        // 修改主表
        map.setPubTime(new Date());
        int ret = mapMapper.updateByPrimaryKey(map);
        // 上传文件
        if (file != null) {
            //第一步：写入文件
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String uuid = IdUtils.simpleUUID();
            try {
                String tmpPath = sdf.format(new Date());
                String filePath = uploadFilePath + tmpPath + "/" + uuid + "." + suffix;
                //1、判断目录。如果目录不存在，则创建目录
                File dir = new File(filePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                //2、写入文件
                file.transferTo(new File(filePath));
                // 3、写入数据库
                PtChartFile ptChartFile = new PtChartFile();
                ptChartFile.setFileId(fileId);
                ptChartFile.setFileType(suffix);
                ptChartFile.setFilePath(filePath);
                ptChartFile.setFileSavename(uuid);
                ptChartFile.setFileViewname(fileName);
                ptChartFile.setFileTime(new Date());
                if (fileId == null || "".equals(fileId)) {
                    ptChartFile.setFileId(IdUtils.simpleUUID());
                    ptChartFile.setCode(map.getCode());
                    ptChartFile.setRelId(map.getCode());
                    ptChartFileMapper.insert(ptChartFile);
                } else {
                    ptChartFileMapper.updateByPrimaryKeySelective(ptChartFile);
                }
            } catch (Exception e) {
                logger.error(e.getLocalizedMessage(), e);
                return AjaxResult.error();
            }
        }
        return AjaxResult.success();


    }

    @ApiOperation("根据主键删除数据")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public AjaxResult delete(@RequestParam(required = true) String id) {
        int ret0 = ptChartFileMapper.deleteByCode(id);
        int ret = mapMapper.deleteByPrimaryKey(id);
        return AjaxResult.success();
    }

    @ApiOperation("去查看图表视图页面")
    @RequestMapping("/to_select_chart")
    public ModelAndView toSelectChart(String code) {
        ModelAndView modelAndView = new ModelAndView();
        PtChart ptChart = mapMapper.findById(code);
        //ptChart.setChartMess(JSON.toJSONString(eChartList3()));
        //ptChart.setCateSeries(JSON.toJSONString(echartList().getSeries()));
        modelAndView.addObject("ptChart", ptChart);
        modelAndView.setViewName("mng/pt_chart_preview");
        return modelAndView;
    }

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

}
