package com.upyuns.platform.rs.website.controller.web;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.github.wxiaoqi.security.common.rest.BaseController;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.upyuns.platform.rs.gtdata.GtDataRestClient;
import com.upyuns.platform.rs.gtdata.GtFileInfo;
import com.upyuns.platform.rs.website.biz.DataTempcacheBiz;
import com.upyuns.platform.rs.website.entity.DataTempcache;
import com.upyuns.platform.rs.website.entity.FileData;
import com.upyuns.platform.rs.website.entity.GainData;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;

@RestController
@RequestMapping("dataTempcache/web")
public class DataTempcacheController extends BaseController<DataTempcacheBiz,DataTempcache> {

    @Autowired
    GtDataRestClient gtDataRestClient;

    @Value("${universal.tempcachePath}")
    private String tempcachePath ;

    @Value("${universal.baseUploadPath}")
    private String baseUploadPath ;

    @Value("${universal.url}")
    private String xx_url ;

    @ApiModelProperty("添加修改文件")
    @RequestMapping(value = "/app/unauth/saveDataTempcache",method = RequestMethod.POST)
    @IgnoreUserToken
    public ObjectRestResponse<FileData> saveDataTempcache(@RequestBody DataTempcache dataTempcache) {

        if(null != dataTempcache.getUptype()) {
            if(DataTempcache.UPTYPE_GTDATA == dataTempcache.getUptype()) {
//            //gtdtat 获取数据
                Map<String, Object> responseMap = gtDataRestClient.list(dataTempcache.getGtdataPath());
                if(null != responseMap && null != responseMap.get("HttpStatusCode") && null != responseMap.get("files") && 200 == (Integer) responseMap.get("HttpStatusCode")) {
                    List<GtFileInfo> gtFileInfos = Convert.toList(GtFileInfo.class, responseMap.get("files"));
                    GtFileInfo gtFileInfo = gtFileInfos.get(0);
                    String filename = gtFileInfo.getFilename();
                    String filesize = gtFileInfo.getSize();

                    String filetype = filename.substring(filename.lastIndexOf("."));
                    long fileSize = Long.valueOf(filesize);
                    //  double fileSizeInKB = (double) fileSize / 1024; // 转换为 KB
                    double fileSizeInMB = (double) fileSize / (1024 * 1024); // 转换为 MB
                    double roundedFileSizeInMB = Math.round(fileSizeInMB * 100.0) / 100.0; // 保留两位小数
                    String fileSizeString = String.format("%.2f MB", roundedFileSizeInMB);

                    dataTempcache.setHasGtdata(SYS_TRUE);
                    dataTempcache.setFilename(filename);
                    dataTempcache.setFiletype(filetype);
                    dataTempcache.setFilesize(fileSizeString);
                }else {
                    return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "分布式路径不对");
                }
            }else if(DataTempcache.UPTYPE_URL == dataTempcache.getUptype()) {

                //提前插入
                if(null == dataTempcache.getId()) {
                    baseBiz.insertSelective(dataTempcache);
                }

                String realPath = tempcachePath+"/"+dataTempcache.getId();
                String serverPath = baseUploadPath + realPath;
                //创建目录
                if(!FileUtil.exist(serverPath)) {
                    FileUtil.mkdir(serverPath);
                }

                String fileName = StrUtil.subAfter(dataTempcache.getUpurl(), "/", true);
                //然后获取这个文件名的后缀
                String suffix = StrUtil.subAfter(fileName, ".", true);

                if(StrUtil.isBlank(dataTempcache.getFilename())) {
                    dataTempcache.setFilename(fileName);
                }

                if(StrUtil.isBlank(dataTempcache.getFiletype())) {
                    dataTempcache.setFiletype("." + suffix);
                }

                //下载文件
                Long size = HttpUtil.downloadFile(dataTempcache.getUpurl(), FileUtil.file(serverPath + "/" + dataTempcache.getFilename()));
                double fileSizeInMB = (double) size / (1024 * 1024); // 转换为 MB
                double roundedFileSizeInMB = Math.round(fileSizeInMB * 100.0) / 100.0; // 保留两位小数
                String fileSizeString = String.format("%.2f MB", roundedFileSizeInMB);
                dataTempcache.setFilesize(fileSizeString);
                dataTempcache.setFilepath(serverPath + "/" + dataTempcache.getFilename());
                dataTempcache.setFileurl(xx_url+ SystemConfig.XXMP_URL + realPath + "/" + dataTempcache.getFilename());
            }
        }


        if (dataTempcache.getId()!=null){
            baseBiz.updateSelectiveById(dataTempcache);
        }else {
            dataTempcache.setIsDel(0);
            baseBiz.insertSelective(dataTempcache);
        }

        return ObjectRestResponse.succ();
    }

    public static void main(String[] args) {
        String url = "http://example.com/path/to/file.jpg";
        // 假设URL的最后一个部分是文件名，我们可以先获取这个部分
        String fileName = StrUtil.subAfter(url, "/", true);
        System.out.println("URL路径的文件后缀是：" + fileName);
        // 然后获取这个文件名的后缀
        String suffix = StrUtil.subAfter(fileName, ".", true);
        System.out.println("URL路径的文件后缀是：" + suffix);
    }
}