package com.fs.common.controller;

import com.fs.common.config.FSConfig;
import com.fs.common.constant.Constants;
import com.fs.common.core.domain.AjaxResult;
import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.file.OssException;
import com.fs.common.param.SmsCodeParam;
import com.fs.common.service.ISmsService;
import com.fs.common.utils.StringUtils;
import com.fs.common.utils.file.FileUploadUtils;
import com.fs.common.utils.file.FileUtils;
import com.fs.common.vo.WangUploadVO;
import com.fs.core.config.ServerConfig;
import com.fs.course.service.IHuaweiObsService;
import com.fs.system.oss.CloudStorageService;
import com.fs.system.oss.OSSFactory;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.fs.course.service.impl.HuaweiObsServiceImpl.uploadProgress;

/**
 * 通用请求处理
 *

 */
@RestController
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ISmsService smsService;
    @Autowired
    private IHuaweiObsService huaweiObsService;
    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            if (!FileUtils.isValidFilename(fileName))
            {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = FSConfig.getDownloadPath() + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete)
            {
                FileUtils.deleteFile(filePath);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = FSConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }



    /**
     * 通用上传请求
     */
    @PostMapping("/common/uploadWang")
    public WangUploadVO uploadWang( HttpServletRequest request) throws Exception
    {
        WangUploadVO vo=new WangUploadVO();
        List<WangUploadVO.WangUploadItem> items=new ArrayList<>();
        vo.setData(items);
        try {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            Iterator<String> fileNames = multipartHttpServletRequest.getFileNames();
            while (fileNames.hasNext()) {
                MultipartFile file = multipartHttpServletRequest.getFile(fileNames.next());
                WangUploadVO.WangUploadItem wangUploadItem=new WangUploadVO.WangUploadItem();
                try
                {
                    String fileName = file.getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf("."));
                    CloudStorageService storage = OSSFactory.build();
                    String url = storage.uploadSuffix(file.getBytes(), suffix);
                    vo.setErrno(0);
                    wangUploadItem.setUrl(url);
                    items.add(wangUploadItem);
                }
                catch (Exception e)
                {
                    vo.setErrno(-1);
                }
            }
        } catch (Exception e) {

        }
        return vo;

    }
    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String name, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        // 本地资源路径
        String localPath = FSConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(name, Constants.RESOURCE_PREFIX);
        // 下载名称
        String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, downloadName));
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

    @ApiOperation("发送短信验证")
    @PostMapping(value="/common/sendSmsCode")
    public R sendSmsCode(@Validated @RequestBody SmsCodeParam smsCodeParam){
        String captcha = redisCache.getCacheObject(smsCodeParam.getMobile());
        if(StringUtils.isNotEmpty(captcha)){
            return R.error("验证码已发送");
        }
        int code = (int) (Math.random() * (9999 - 1000 + 1)) + 1000;// 产生1000-9999的随机数
        return smsService.sendTSms(smsCodeParam.getMobile(),String.valueOf(code));
    }

    @PostMapping("/common/uploadOSS")
    public R uploadOSS(@RequestParam("file") MultipartFile file) throws Exception
    {
//        String deviceId = "4eea1292408044beb49c02d3197871b0";
//        qwMaterialService.insertQwMaterial(file,deviceId);
//        return R.ok();
        if (file.isEmpty())
        {
            throw new OssException("上传文件不能为空");
        }
        // 上传文件
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        CloudStorageService storage = OSSFactory.build();
        String url = storage.uploadSuffix(file.getBytes(), suffix);
        return R.ok().put("url",url);
    }

    @PostMapping("common/uploadHuaWeiObs")
    public R uploadHuaWeiObs(@RequestPart("file") MultipartFile file) throws IOException
    {
        if (file.isEmpty())
        {
            throw new OssException("上传文件不能为空");
        }
        // 将MultipartFile转换为File对象
        File convFile = new File(System.getProperty("java.io.tmpdir") + "/" + file.getOriginalFilename());
        file.transferTo(convFile);
        String fileKey = UUID.randomUUID().toString(); // 用于标识上传进度
        uploadProgress.put(fileKey, 0.0);
        new Thread(() -> {
            try {
                huaweiObsService.uploadPartFile(convFile, fileKey);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        return R.ok().put("data", fileKey);
//        String url = huaweiObsService.uploadPartFile(convFile);
//        return R.ok().put("url", url);
    }
}
