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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
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.vo.PageDataVO;
import com.upyuns.platform.rs.datacenter.entity.RscpImageDataTotal;
import com.upyuns.platform.rs.gtdata.GtDataRestClient;
import com.upyuns.platform.rs.gtdata.GtFileInfo;
import com.upyuns.platform.rs.website.biz.DataMenuBiz;
import com.upyuns.platform.rs.website.biz.GainDataBiz;
import com.upyuns.platform.rs.website.dto.GainDataDTO;
import com.upyuns.platform.rs.website.entity.DataMenu;
import com.upyuns.platform.rs.website.entity.GainData;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

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

@RestController
@RequestMapping("gainData/web")
public class GainDataController extends BaseController<GainDataBiz,GainData> {

    @Autowired
    DataMenuBiz dataMenuBiz;

    @Autowired
    GtDataRestClient gtDataRestClient;

    @ApiModelProperty("列表")
    @IgnoreUserToken
    @RequestMapping(value = "/app/unauth/mapAll",method = RequestMethod.GET)
    public ObjectRestResponse<List<GainData>> getPageList(GainDataDTO dto) {
        Example example = baseBiz.initExample(dto);

        PageDataVO pageDataVO = PageDataVO.pageInfo(dto.getPage(), dto.getLimit(), ()->baseBiz.selectByExample(example));
        return ObjectRestResponse.succ(pageDataVO);
    }

    @ApiModelProperty("统计")
    @IgnoreUserToken
    @RequestMapping(value = "/app/unauth/statistics",method = RequestMethod.GET)
    public ObjectRestResponse<List<GainData>> statistics(GainDataDTO dto) {
        Example example = baseBiz.initExample(dto);

        List<GainData> list = baseBiz.selectByExample(example);
        List<DataMenu> dataMenuList = dataMenuBiz.selectListAll();
        List<GainDataVO> voList = Convert.toList(GainDataVO.class, list);
        Map<Integer, DataMenu> dataMenuMap = dataMenuList.parallelStream().collect(Collectors.toMap(DataMenu::getId, Function.identity()));
        for(GainDataVO gainDataVO : voList) {
            if(null != gainDataVO.getMenuId()) {
                DataMenu topMenu = baseBiz.getTopMenu(dataMenuMap, dataMenuMap.get(gainDataVO.getMenuId()));
                if(null != topMenu) {
                    gainDataVO.setTopMenuId(topMenu.getId());
                    gainDataVO.setTopMenuName(topMenu.getTitle());
                }
            }
        }
        Map<String, Long> map = list.parallelStream().filter(o -> StrUtil.isNotBlank(o.getSupplier())).collect(Collectors.groupingBy(GainData::getSupplier, Collectors.counting()));
        Map<String, Long> map2 = voList.parallelStream().filter(o -> (null != o.getMenuId())).collect(Collectors.groupingBy(GainDataVO::getTopMenuName, Collectors.counting()));
        Map<String, Long> map3 = voList.parallelStream().filter(o -> (null != o.getMenuId())).collect(Collectors.groupingBy(GainDataVO::getTopMenuName, Collectors.counting()));
        Map<String, Long> map4 = voList.parallelStream().filter(o -> (null != o.getMenuId())).collect(Collectors.groupingBy(GainDataVO::getTopMenuName, Collectors.counting()));

//        Map<String, Map> returnMap = CollUtil.newHashMap();
//        returnMap.put("供应商统计", map);
//        returnMap.put("项目统计", map2);
//        returnMap.put("项目统计加工次数", map3);
//        returnMap.put("项目统计分发次数", map4);
        List<StatisticsInfo> datas = CollUtil.newArrayList(new StatisticsInfo(){{
            setName("供应商统计");
            setStatistics(map);
        }},new StatisticsInfo(){{
            setName("项目统计");
            setStatistics(map2);
        }},new StatisticsInfo(){{
            setName("项目统计加工次数");
            setStatistics(map3);
        }},new StatisticsInfo(){{
            setName("项目统计分发次数");
            setStatistics(map4);
        }});

        return ObjectRestResponse.succ(datas);
    }

    @Data
    static public class StatisticsInfo {
        String name;
        Map<String, Long> statistics;
    }

    @Data
    static public class GainDataVO extends GainData {
        Integer topMenuId;
        String topMenuName;
    }

    @ApiModelProperty("查询详情")
    @IgnoreUserToken
    @RequestMapping(value = "/app/unauth/getbyId",method = RequestMethod.GET)
    public ObjectRestResponse<List<GainData>> getbyId(GainDataDTO dto) {
        Example example = new Example(GainData.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("isDel", 0);
        criteria.andEqualTo("status",2);
        if (StringUtils.isNotBlank(dto.getId())){
            criteria.andEqualTo("id",dto.getId());
        }
        GainData result = baseBiz.selectById(dto.getId());
        return ObjectRestResponse.succ(result);
    }

    @ApiModelProperty("查询详情")
    @IgnoreUserToken
    @RequestMapping(value = "/app/unauth/dealGtdata",method = RequestMethod.GET)
    public ObjectRestResponse dealGtdata(GainData gainData) {
        List<GainData> gainData1 = baseBiz.selectAll(gainData);
        baseBiz.dealGtdata(gainData1);
        return ObjectRestResponse.succ();
    }


    @ApiModelProperty("处理历史图片")
    @IgnoreUserToken
    @RequestMapping(value = "/app/unauth/dealHisimg",method = RequestMethod.GET)
    public ObjectRestResponse dealHisimg(GainData gainData) throws IOException {
        gainData.setIsDel(SYS_FALSE);
        List<GainData> gainData1 = baseBiz.selectAll(gainData);
        for(GainData gainData2 : gainData1) {
            if(StrUtil.isNotBlank(gainData2.getPictureUrl())) {
                String path = gainData2.getPictureUrl().replaceAll("https://gdxm.upyuns.com/image","/sdbdata/www/gdweb_resources/image");
                path = path.replaceAll("https://zzrsmgmt.upyuns.com/image","/sdbdata/www/gdweb_resources/image");
                String path250 = path + "_250";
                if(!FileUtil.exist(path250)) {
                    //生成250
                    BufferedImage originalImage = ImageIO.read(new File(path));
                    int originalWidth = originalImage.getWidth();
                    int originalHeight = originalImage.getHeight();
                    double scaleFactor = 1.0;

                    if (originalWidth > originalHeight) {
                        scaleFactor = (double) 500 / originalWidth;
                    } else {
                        scaleFactor = (double) 500 / originalHeight;
                    }

                    int newWidth = (int) (originalWidth * scaleFactor);
                    int newHeight = (int) (originalHeight * scaleFactor);

                    BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
                    Graphics2D g = resizedImage.createGraphics();
                    g.drawImage(originalImage, 0, 0, newWidth, newHeight, null);
                    g.dispose();

                    // 保存压缩后的图片
                    String compressedFilePath = path250;
                    String lastFormat = path.substring(path.lastIndexOf("."));
                    ImageIO.write(resizedImage, lastFormat.substring(1, lastFormat.length()), new File(compressedFilePath));
                }
            }
        }
        return ObjectRestResponse.succ();
    }

    @ApiModelProperty("")
    @IgnoreUserToken
    @RequestMapping(value = "/app/unauth/gtDataList",method = RequestMethod.GET)
    public ObjectRestResponse gtDataList(String path) throws IOException {
        //gtdtat 获取数据
        Map<String, Object> responseMap = gtDataRestClient.list(path);
        List<GtFileInfo> gtFileInfos = Convert.toList(GtFileInfo.class, responseMap.get("files"));
        GtFileInfo gtFileInfo = gtFileInfos.get(0);
        String filename = gtFileInfo.getFilename();
        String filesize = gtFileInfo.getSize();
        return ObjectRestResponse.succ(responseMap);
    }

    public static void main(String[] args) {
        String url = "https://zzrsmgmt.upyuns.com/image/admin/2024-05-30/11.JPG";
        String url2 = url.replaceAll("https://zzrsmgmt.upyuns.com/image","/sdbdata/www/gdweb_resources/image");
        String lastFormat = url2.substring(url2.lastIndexOf("."));
        System.out.println(url2);
        System.out.println(lastFormat);
    }
}