package com.ruoyi.bar;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.BarLoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.PdfUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.domain.WyPlatformBillTemplate;
import com.ruoyi.system.service.impl.WyPlatformBillTemplateServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;

@Api(tags = "酒吧方酒单相关接口")
@RestController
@RequestMapping("/bar/bill")
public class BarBillController extends BarBaseController {

    @Resource
    private WyPlatformBillTemplateServiceImpl platformBillTemplateService;
    private static final Logger log = LoggerFactory.getLogger(BarBillController.class);

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询我的酒单模板列表
     */
    @ApiOperation("查询我的酒单模板列表")
    @GetMapping("/templateList")
    public AjaxResult templateList() {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        final WyPlatformBillTemplate wyPlatformBillTemplate = new WyPlatformBillTemplate();
        //专属模板
        wyPlatformBillTemplate.setBarId(loginUser.getBarId());
        final List<WyPlatformBillTemplate> wyPlatformBillTemplates = platformBillTemplateService.selectWyPlatformBillTemplateList(wyPlatformBillTemplate);
        //公共模板
        wyPlatformBillTemplate.setBarId(0L);
        final List<WyPlatformBillTemplate> publicTemplates = platformBillTemplateService.selectWyPlatformBillTemplateList(wyPlatformBillTemplate);
        //合并模板
        wyPlatformBillTemplates.addAll(publicTemplates);
        return AjaxResult.success(wyPlatformBillTemplates);
    }

    /**
     * 查询酒单模板详情
     */
    @ApiOperation("查询酒单模板详情")
    @GetMapping("/templateDetail")
    public AjaxResult templateDetail(@RequestParam("templateId") Long templateId) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        final WyPlatformBillTemplate template = platformBillTemplateService.selectWyPlatformBillTemplateById(templateId);
        if (template == null) {
            return AjaxResult.error("模板不存在");
        }
        if (!Objects.equals(template.getBarId(), loginUser.getBarId()) && template.getBarId() != 0) {
            return AjaxResult.error("无权限查看该模板");
        }
        return AjaxResult.success(template);
    }

    /**
     * 保存导出记录
     */
    @ApiOperation("保存导出记录")
    @PostMapping("/saveExportRecord")
    public AjaxResult saveExportRecord(@RequestParam("templateId") Long templateId, @RequestParam(value = "remark", required = false) String remark) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        final WyPlatformBillTemplate template = platformBillTemplateService.selectWyPlatformBillTemplateById(templateId);
        if (template == null) {
            return AjaxResult.error("模板不存在");
        }
        if (!Objects.equals(template.getBarId(), loginUser.getBarId()) && template.getBarId() != 0) {
            return AjaxResult.error("无权限使用该模板");
        }
        template.setRemark(remark);
        platformBillTemplateService.saveExportRecord(template);
        return AjaxResult.success("保存成功");
    }

    /**
     * 生成酒单pdf
     */
    @ApiOperation("生成酒单pdf")
    @PostMapping("/generatePdf")
    public AjaxResult saveExportRecord(MultipartFile file) {
        BarLoginUser loginUser = SecurityUtils.getBarLoginUser();
        validateBarAuth();
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String billPath = filePath + "/bill/bar_" + loginUser.getBarId();

            // 上传并返回新文件名称
            final String newFileName = DateUtils.dateTimeNow() + "_" + file.getOriginalFilename();
            FileUploadUtils.getAbsoluteFile(billPath,newFileName);
            file.transferTo(Paths.get(billPath + "/" + newFileName));
            // 生成pdf
            final String newPdfName = DateUtils.dateTimeNow() + "_" + FileUtils.getNameNotSuffix(file.getOriginalFilename()) + ".pdf";
            PdfUtils.addImageToPdf(billPath + "/"+ newFileName, billPath + "/"+ newPdfName);
            final String pathFileName = FileUploadUtils.getPathFileName(billPath, newPdfName);
            // 删除原文件
            FileUtils.deleteFile(billPath + "/" + newFileName);
            String url = serverConfig.getUrl() + pathFileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("pathFileName", pathFileName);
            ajax.put("newPdfName", newPdfName);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
