package com.yida.data.user.controller.web;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.common.ResultMsgType;
import com.yida.data.common.core.entity.school.EduSchoolTips;
import com.yida.data.common.core.utils.FileUtil;
import com.yida.data.common.core.utils.QrCodeUtil;
import com.yida.data.user.service.EduSchoolTipsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * 学校智慧迎新web后台接口
 *
 * @author wjm
 * @date 2021/8/21
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/web/welcome")
@RefreshScope
@Api(tags = "学校智慧迎新后台接口")
public class WebEduSchoolWelcomeController {

    @Value("${welcome.H5Url}")
    private String welcomeH5Url;

    @Value("${febs.uploadUrl}")
    private String uploadUrl;

    private final EduSchoolTipsService eduSchoolTipsService;

    /***
     * @Author jianMingWang
     * @Description 根据学校id获取须知信息
     * @Date 15:26 2021/8/21
     * @Param [schoolId]
     * @return com.yida.data.common.core.common.ResultBean<com.yida.data.common.core.entity.school.EduSchoolTips>
     **/
    @ApiOperation("获取学校须知信息")
    @GetMapping("/getSchoolTip")
    public ResultBean<EduSchoolTips> getEduSchoolTips(
            @ApiParam(value = "学校id", required = true) @RequestParam Long schoolId) {
        try {
            return ResultBean.buildSuccess(eduSchoolTipsService.getOne(Wrappers.<EduSchoolTips>query().lambda().eq(EduSchoolTips::getSchoolId, schoolId)));
        } catch (Exception e) {
            log.error("获取学校须知信息失败: {}", e.getMessage(), e);
            return ResultBean.buildError(ResultMsgType.QUERY_FAIL.getValue());
        }
    }


    /***
     * @Author jianMingWang
     * @Description 保存或修改学校须知信息
     * @Date 15:25 2021/8/21
     * @Param [eduSchoolTips]
     * @return com.yida.data.common.core.common.ResultBean<com.yida.data.common.core.entity.school.EduSchoolTips>
     **/
    @ApiOperation("保存或修改学校须知信息")
    @PostMapping("/saveSchoolTips")
    public ResultBean<EduSchoolTips> saveSchoolTips(
            @ApiParam(value = "须知信息", required = true) @RequestBody EduSchoolTips eduSchoolTips) {
        try {
            // 判断是否需要生成二维码信息
            if (!Optional.ofNullable(eduSchoolTips.getId()).isPresent()) {
                // 保存智慧迎新H5页面地址
                String pageUrl = welcomeH5Url + "?schoolId=" + eduSchoolTips.getSchoolId();
                eduSchoolTips.setPageUrl(pageUrl);
                // 获取本地文件上传路径
                String dirPath = FileUtil.getLocalUploadAddress();
                // 生成文件名称
                String fileName = "welcomeQrCode" + eduSchoolTips.getSchoolId() + ".png";
                // 生成本地二维码
                String filePath = dirPath + fileName;
                QrCodeUtil.generateQrCodeImage(pageUrl, 200, 200, filePath);
                // 上传文件到媒资
                String qrCodeAddress = FileUtil.uploadFileToMediaServer(uploadUrl, filePath);
                eduSchoolTips.setQrCodeAddress(qrCodeAddress);
            }
            eduSchoolTipsService.saveOrUpdate(eduSchoolTips);
            return ResultBean.buildSuccess();
        } catch (Exception e) {
            log.error("保存或修改学校须知信息失败: {}", e.getMessage(), e);
            return ResultBean.buildError(ResultMsgType.SAVE_FAIL.getValue());
        }
    }

    /**
     * 下载在线图片并返回文件流
     *
     * @param imageUrl 在线图片地址
     * @param response 文件返回流
     * @author ZYJ
     * @date 2021/8/23 15:14
     */
    @ApiOperation("下载在线图片并返回文件流")
    @GetMapping("/downloadImage")
    public void downloadImage(
            @ApiParam(value = "图片外网访问地址", required = true) @RequestParam String imageUrl,
            HttpServletResponse response) throws Exception {
        // 下载图片到本地
        String imageFilePath = FileUtil.downloadToLocal(imageUrl);
        // 文件下载
        FileUtil.download(imageFilePath, "智慧迎新二维码.png", Boolean.TRUE, response);
    }
}
