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 cn.hutool.json.JSONUtil;
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.Query;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.util.process.SystemConfig;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.upyuns.platform.rs.gtdata.GtDataRestClient;
import com.upyuns.platform.rs.gtdata.GtFileInfo;
import com.upyuns.platform.rs.universal.utils.DateUtil;
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 io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

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

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

@RestController
@RequestMapping("dataTempcache/web")
@Slf4j
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 ;

    //BaseController.baseLogicPages
    //BaseController.del



    @RequestMapping(value = "/app/unauth/dealGtdataDir", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse dealGtdataPath(String gtdataPaths)  {
        if(StrUtil.isBlank(gtdataPaths)) {
            return ObjectRestResponse.createFailedResult(ResultCode.FAILED_CODE, "分布式路径不对");
        }

        String[] gtdataPathArray = gtdataPaths.split(",");

        //创建临时目录
        String gtdataDirPath = "/rscloudmart"+ tempcachePath + "/" + (new Date()).getTime();
        gtDataRestClient.mkdirs(gtdataDirPath);


        //循环判断复制数据
        for(String gtdataPath : gtdataPathArray) {
            Integer indexNum  = StrUtil.lastIndexOfIgnoreCase(gtdataPath, "/");
            //带/的filename
            String fileName = gtdataPath.substring(indexNum, gtdataPath.length());
            String targetPath = gtdataDirPath + fileName;
            gtDataRestClient.copy(gtdataPath, targetPath);
        }

        return ObjectRestResponse.succ(gtdataDirPath);
    }

    @RequestMapping(value = "/app/unauth/dealGtdataPath", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse dealGtdataPath(DataTempcache dataTempcache)  {
        //查询dataTempcache 的上传方式
        DataTempcache dataTempcacheDB = baseBiz.selectById(dataTempcache.getId());
        String resultPath = "";

        //判断是否存在处理GTDATA
        if(null == dataTempcacheDB.getGtdataPath() || DataTempcache.HASGTDATA_FIN != dataTempcacheDB.getHasGtdata())  {
            if(StrUtil.isBlank(dataTempcacheDB.getGtdataPath())) {
                //生成gtdataPath
                //根据id创建gtdata目录
                String gtdataPath = "/rscloudmart"+ tempcachePath + "/" + dataTempcacheDB.getId();
                gtDataRestClient.mkdirs(gtdataPath);

                //上传文件
                String fileGtdataPath = gtdataPath + "/" + dataTempcacheDB.getFilename();

                String filepath = dataTempcacheDB.getFilepath();
//                if(StrUtil.isBlank(filepath)) {
//                    //下载文件
//                }

                if(!gtDataRestClient.isExist(fileGtdataPath).get("exist").toString().equals("true")){
                    Map<String, Object> responseMap = gtDataRestClient.createLarge(filepath, fileGtdataPath);
                    if (responseMap == null || 200 != (Integer) responseMap.get("HttpStatusCode")) {
                        log.error(JSONUtil.toJsonStr(responseMap), responseMap);
                    }
                }

                baseBiz.updateSelectiveById(new DataTempcache() {{
                    setId(dataTempcache.getId());
                    setGtdataPath(fileGtdataPath);
                    setHasGtdata(HASGTDATA_FIN);
                }});
                dataTempcacheDB.setGtdataPath(fileGtdataPath);
            }
        }
        resultPath = dataTempcacheDB.getGtdataPath();

        return ObjectRestResponse.succ(resultPath);
    }

    @ApiOperation("查询分页-ObjectRestResponse")
    @RequestMapping(value = "/app/unauth/logicPages",method = RequestMethod.GET)
    @IgnoreUserToken
    @ResponseBody
    public ObjectRestResponse<PageDataVO<DataTempcache>> unauthBaseLogicPages(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);
        return ObjectRestResponse.succ(baseBiz.selectByQueryLogicPage(query));
    }

    @ApiModelProperty("添加修改文件")
    @RequestMapping(value = "/app/unauth/saveDataTempcache",method = RequestMethod.POST)
    @IgnoreUserToken
    public ObjectRestResponse<FileData> saveDataTempcache(@RequestBody DataTempcache dataTempcache) {
        if (dataTempcache.getId()!=null){
            baseBiz.updateSelectiveById(dataTempcache);
        }else {
            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());
                }
            }
            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);
    }
}