package com.starry.admin.modules.weichat.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.common.oss.service.IOssFileService;
import com.starry.admin.modules.shop.service.IShopUiSettingService;
import com.starry.admin.modules.system.service.ISysAdministrativeAreaDictInfoService;
import com.starry.admin.modules.weichat.service.WxAccessTokenService;
import com.starry.admin.modules.weichat.utils.WxFileUtils;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.result.R;
import com.starry.common.utils.IdUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author admin
 * @since 2024/4/10 16:18
 **/
@Api(tags = "微信通用接口", description = "微信公共功能相关接口")
@Slf4j
@RestController
@RequestMapping("/wx/common/")
public class WxCommonController {

    @Resource
    private IOssFileService ossFileService;

    @Resource
    private ISysAdministrativeAreaDictInfoService areaDictInfoService;
    @Resource
    WxAccessTokenService wxAccessTokenService;
    @Resource
    private IShopUiSettingService shopUiSettingService;

    @ApiOperation(value = "获取行政区域树", notes = "获取省市区县的树形结构数据")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @GetMapping("area/tree")
    public R areaTree() {
        return R.ok(areaDictInfoService.selectTree("2"));
    }

    @ApiOperation(value = "获取店铺UI设置", notes = "获取当前店铺的UI配置信息")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @GetMapping("setting/info")
    public R selectShopUiSettingInfo() {
        return R.ok(shopUiSettingService.selectShopUiSettingInfo());
    }

    @ApiOperation(value = "上传文件", notes = "上传文件到OSS存储")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功，返回文件访问地址")})
    @PostMapping("file/upload")
    public R fileUpload(@ApiParam(value = "上传的文件", required = true) @RequestParam("file") MultipartFile file)
            throws IOException {
        String fileAddress = ossFileService.upload(file.getInputStream(), SecurityUtils.getTenantId(),
                file.getOriginalFilename());
        return R.ok(fileAddress);
    }

    @ApiOperation(value = "上传音频", notes = "通过微信媒体ID上传音频文件，自动转换为MP3格式")
    @ApiImplicitParam(name = "mediaId", value = "微信媒体ID", required = true, dataType = "String", paramType = "query")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功，返回文件访问地址"),
            @ApiResponse(code = 500, message = "上传失败，mediaId为空或文件不存在")})
    @GetMapping("audio/upload")
    public R audioUpload(@RequestParam("mediaId") String mediaId) throws IOException, WxErrorException {
        if (StrUtil.isBlankIfStr(mediaId)) {
            throw new CustomException("mediaId不能为空");
        }
        String accessToken = wxAccessTokenService.getAccessToken();
        // 下载录音文件，并转化为InputStream
        InputStream inputStream = WxFileUtils.getTemporaryMaterial(accessToken, mediaId);
        File tempFile = FileUtil.createTempFile("wx_" + SecurityUtils.getTenantId(), IdUtils.getUuid() + ".amr", null)
                .toFile();
        // 可以在这里对临时文件进行操作
        log.error("tempFile = {}", tempFile.getPath());
        try (FileOutputStream fileOutputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            // 读取InputStream并写入到FileOutputStream
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }
        }
        if (FileUtil.size(tempFile) <= 0) {
            throw new CustomException("音频文件上传失败,文件不存在");
        }
        // 将下载的微信素材文件，转化为MP3文件
        File targetFile = FileUtil.createTempFile("wx_" + SecurityUtils.getTenantId(), IdUtils.getUuid() + ".mp3", null)
                .toFile();
        log.error("targetFile = {}", targetFile.getPath());
        WxFileUtils.audioConvert2Mp3(tempFile, targetFile);
        // 将MP3文件上传到OSS
        String fileAddress = ossFileService.upload(Files.newInputStream(targetFile.toPath()),
                SecurityUtils.getTenantId(), IdUtils.getUuid() + ".mp3");
        // 删除临时文件
        FileUtil.del(tempFile);
        FileUtil.del(targetFile);
        return R.ok(fileAddress);
    }
}
