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

import cn.hutool.core.bean.BeanUtil;
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.fasterxml.jackson.annotation.JsonFormat;
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.github.wxiaoqi.security.common.vo.PageDataVO;
import com.github.wxiaoqi.security.common.vo.PageParam;
import com.upyuns.platform.rs.gtdata.GdLoginVO;
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.dto.DataTempcacheDTO;
import com.upyuns.platform.rs.website.dto.GainDataDTO;
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 lombok.Data;
import lombok.extern.log4j.Log4j;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.io.OutputStream;
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")
@Slf4j
public class AdminDataTempcacheController 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
    @Override
    public ObjectRestResponse<PageDataVO<DataTempcache>> baseLogicPages(Map<String, Object> params) {
        PageDTO pageDTO = BeanUtil.mapToBean(params, PageDTO.class, true);
        PageDataVO<DataTempcache> pageDataVO = PageDataVO.pageInfo(pageDTO.initQuery(), () -> baseBiz.selectByWeekend(w -> {
            w.andEqualTo(DataTempcache::getIsDel, SYS_TRUE);
            w.andEqualTo(DataTempcache::getStatus, SYS_TRUE);
            if (StrUtil.isNotBlank(pageDTO.getName())) {
                w.andLike(DataTempcache::getName, "%"+ pageDTO.getName()+ "%");
            }
            if (null != pageDTO.getSource()) {
                w.andEqualTo(DataTempcache::getSource, pageDTO.getSource());
            }
            if (null != pageDTO.getStarttime()) {
                w.andGreaterThanOrEqualTo(DataTempcache::getCrtTime, pageDTO.getStarttime());
            }
            if (null != pageDTO.getEndtime()) {
                w.andLessThanOrEqualTo(DataTempcache::getCrtTime, pageDTO.getEndtime());
            }
            return w;
        }));
        return ObjectRestResponse.succ(pageDataVO);
    }

    @Data
    static public class PageDTO extends PageParam {
        private String name;
        private Integer source;
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        @JsonFormat(pattern = "yyyy-MM-dd",timezone="GMT+8")
        private Date starttime;
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        @JsonFormat(pattern = "yyyy-MM-dd",timezone="GMT+8")
        private Date endtime;
    }

    //BaseController.del

    @RequestMapping(value = "/app/unauth/dealImageimgUrl", method = RequestMethod.GET)
    @IgnoreUserToken
    public ObjectRestResponse dealImageimgUrl(DataTempcache dataTempcache) throws Exception  {
        //查询dataTempcache 的上传方式
        DataTempcache dataTempcacheDB = baseBiz.selectById(dataTempcache.getId());
        String resultUrl = "";
        if(DataTempcache.UPTYPE_GTDATA == dataTempcacheDB.getUptype()) {
            //判断是否存在本地路径和url
            if(StrUtil.isBlank(dataTempcacheDB.getFileurl())) {
//                Map<String, Object> result = gtDataRestClient.openLarge(dataTempcacheDB.getGtdataPath());
//                byte[] content = (byte[]) result.get("file");
//                getResponse().setContentLength(content.length);

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

                gtDataRestClient.openLarge(serverPath + "/" + dataTempcacheDB.getFilename(), dataTempcacheDB.getGtdataPath());
//                FileUtil.writeBytes(content, serverPath + "/" + dataTempcacheDB.getFilename());

                baseBiz.updateSelectiveById(new DataTempcache(){{
                    setId(dataTempcacheDB.getId());
                    setFilepath(serverPath + "/" + dataTempcacheDB.getFilename());
                    setFileurl(xx_url+ SystemConfig.XXMP_URL + realPath + "/" + dataTempcacheDB.getFilename());
                }});
                dataTempcacheDB.setFilepath(serverPath + "/" + dataTempcacheDB.getFilename());
                dataTempcacheDB.setFileurl(xx_url+ SystemConfig.XXMP_URL + realPath + "/" + dataTempcacheDB.getFilename());
            }
//            else if (DataTempcache.UPTYPE_URL == dataTempcacheDB.getUptype()) {
//
//            }
        }
        resultUrl = dataTempcacheDB.getFileurl();

        return ObjectRestResponse.succ(resultUrl);
    }

    @RequestMapping(value = "/getPageList",method = RequestMethod.GET)
    public ObjectRestResponse<List<GainData>> getPageList(DataTempcacheDTO dto) {
        PageDataVO pageDataVO = PageDataVO.pageInfo(dto.getPage(), dto.getLimit(), ()->baseBiz.pageList(dto));
        return ObjectRestResponse.succ(pageDataVO);
    }

    @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());
            }else if(DataTempcache.UPTYPE_UPLOAD == dataTempcache.getUptype()){
                dataTempcache.setFileurl(dataTempcache.getUpurl());
            }
        }


        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);
    }
}