package com.ruoyi.web.controller.backstage;


import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.SourcePriceVo;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.app.baidu.GsonUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
//import org.springframework.security.access.prepost.RequiresRoles;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

import static com.ruoyi.common.core.domain.AjaxResult.error;
import static com.ruoyi.common.core.domain.AjaxResult.success;


// 产品管理后台
@RestController
@RequestMapping("/system/source")
public class SysSourceController extends BaseController {

    @Autowired
    private ISysSourceService sysSourceService;

    @Autowired
    private ISysCityService sysCityService;

    @Autowired
    private ISysScenicService sysScenicService;

    @Autowired
    private IDailySysService dailySysService;

    @Autowired
    private IUserInfoService userInfoService;

    @Autowired
    private IUserWorkService userWorkService;


    // 设置各景区默认价格和背景图片
    @Autowired
    private ISysScenicDefaultService sysScenicDefaultService;


    // 设置资源位默认价格和背景图片
    @Autowired
    private ISysSourceDefaultService sysSourceDefaultService;


    // 状态
    /*
    *
    1)0 闲置
    2)1 已购 未展示
    3)2 已购 在展示中
    * */

    // 获取系统资源位列表, 附带搜索功能
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/getAllSource")
    public TableDataInfo getAllSource(SysSource sysSource) {

//        System.out.println("搜索条件: "+sysSource.getCity()+sysSource.getScenic()+sysSource.getcX()+sysSource.getcY());

        startPage();

        List<SourceListDto> sysSourceList = sysSourceService.getSysSourceList(sysSource);

        for(SourceListDto sourceListDto : sysSourceList){

            sourceListDto.setNumber(sourceListDto.getPart()+String.format("%02d", sourceListDto.getcX())+String.format("%02d", sourceListDto.getcY()));
            LocalDate startTime = sourceListDto.getStartTime();
            LocalDate endTime = sourceListDto.getEndTime();
            LocalDate now = LocalDate.now();

            if (sourceListDto.getWorkId() != 0L)
            {
                sourceListDto.setTime(sourceListDto.getStartTime() + "~" + sourceListDto.getEndTime());
                Long daysBetween = ChronoUnit.DAYS.between(startTime, endTime);
                // 展示天数
                sourceListDto.setpDay(daysBetween);
                // 剩余天数
                Long rDay = ChronoUnit.DAYS.between(startTime, now);
                sourceListDto.setrDay(Math.max(rDay, 0L));
            }

//            sourceListDto.setTime(sourceListDto.getStartTime() + "~" + sourceListDto.getEndTime());
//            // 价格
//            Map<String, String> price = GsonUtils.fromJson(sourceListDto.getPrice(), HashedMap.class);
//
//            sourceListDto.setPriceJson(price);


            // 新版价格
            sourceListDto.setPriceList(GsonUtils.fromJson(sourceListDto.getPrice(), List.class));



            // 这里根据天数判断价格?? 还是直接返回每天的价格算了

//            System.out.println(price);
        }


        return getDataTable(sysSourceList);
    }

    // 获取城市数, 景区数, 资源位数, 展示中的资源位个数, 互动次数, 分享次数.
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/getStSource")
    public AjaxResult getStSource() {

        LoginUser loginUser = SecurityUtils.getLoginUser();
//        System.out.println("登录用户id: "+loginUser.getPermissions()+loginUser.getUser().getUserName());

        AjaxResult stSource = AjaxResult.success();

        // 城市数
        stSource.put("cityCount", sysCityService.selectSysCityList(new SysCity()).size());

        // 景区数
        stSource.put("scenicCount", sysScenicService.selectSysScenicList(new SysScenic()).size());

        // 资源位数
        stSource.put("sourceCount", sysSourceService.selectSysSourceList(new SysSource()).size());


        // 展示中的资源位
        SysSource sysSource = new SysSource();
        sysSource.setSourceStatus("2");
        stSource.put("sourceShowCount", sysSourceService.selectSysSourceList(sysSource).size());

        // 互动次数 分享次数
        // 前一天时间
        LocalDate date = LocalDate.now().minusDays(1);

        System.out.println("产品管理--资源位--前一天时间"+date);


//         ----------------------------------真实数据---------------------------------------

        DailySys dailySys = dailySysService.selectDailySysByDate(date);

        stSource.put("interactions", dailySys.gettInteractions());
        stSource.put("shares", dailySys.gettShares());
//        ---------------------------------真实数据end-------------------------------------

//        //--------------------------------- 测试数据----------------------------------------
//        stSource.put("interactions", 123231L);
//        stSource.put("shares", 54321L);
//        //----------------------------测试数据end------------------------

        return stSource;
    }

    // 根据天数获取资源位利用情况, 还要加城市.现在只有济南,先不写了.
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/getSourceUseCount/{day}")
    public AjaxResult getSourceUseCount(@PathVariable int day) {



        // 前一天时间
        LocalDate now = LocalDate.now();

        LocalDate startDate = now.minusDays(day+1);
        LocalDate endDate = now.minusDays(1);

        //------------------------------------实际返回数据----------------------------------------------
        List<SourceUseCountDto> seUserWorkCount = dailySysService.getSourceUserCount(startDate, endDate);
        // 还要计数资源位数量--未使用资源位数量=资源位总数-以使用数量.
        int sourceCount = sysSourceService.selectSysSourceList(new SysSource()).size();
        for(SourceUseCountDto sourceUseCountDto : seUserWorkCount){
            sourceUseCountDto.setUnUseCount(sourceCount-sourceUseCountDto.getUseCount());
        }


        //------------------------------------实际返回数据结束----------------------------------------------

//        //---------------------------------编造数据-----------------------------------------------------
//        List<SourceUseCountDto>  seUserWorkCount = new ArrayList<>();
//        for(int i=0;i<day;i++){
//            SourceUseCountDto sourceUseCountDto = new SourceUseCountDto();
//            sourceUseCountDto.setDate(startDate.plusDays(i+1));
//
//            Random random = new Random();
//            long minValue = 1000L;
//            long maxValue = 99999L;
//            long range = maxValue - minValue + 1;
//            long userCount = minValue + (long) (random.nextDouble() * range);
//            long unUserCount = minValue + (long) (random.nextDouble() * range);
//
//            sourceUseCountDto.setUnUseCount(unUserCount);
//            sourceUseCountDto.setUseCount(userCount);
//            seUserWorkCount.add(sourceUseCountDto);
//        }
//
//        //-----------------------------------编造数据end----------------------------------------------------



        return success(seUserWorkCount);
    }

    // 根据天数获取资源位利用情况, 还要加城市----------------后期要修改
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @PostMapping("/getSourceUseCount")
    public AjaxResult getSourceUseCount(@RequestParam String city, @RequestParam int day) {



        // 前一天时间
        LocalDate now = LocalDate.now();

        LocalDate startDate = now.minusDays(day+1);
        LocalDate endDate = now.minusDays(1);

        //------------------------------------实际返回数据----------------------------------------------
        List<SourceUseCountDto> seUserWorkCount = dailySysService.getSourceUserCount(startDate, endDate);

        // 还要计数资源位数量--未使用资源位数量=资源位总数-已使用数量.
        Long sourceCount = sysSourceService.getSourceCountByCity(city);
        for(SourceUseCountDto sourceUseCountDto : seUserWorkCount){
            sourceUseCountDto.setUnUseCount(sourceCount-sourceUseCountDto.getUseCount());
        }

        //------------------------------------实际返回数据结束----------------------------------------------

//        //---------------------------------编造数据-----------------------------------------------------
//        List<SourceUseCountDto>  seUserWorkCount = new ArrayList<>();
//        for(int i=0;i<day;i++){
//            SourceUseCountDto sourceUseCountDto = new SourceUseCountDto();
//            sourceUseCountDto.setDate(startDate.plusDays(i+1));
//
//            Random random = new Random();
//            long minValue = 1000L;
//            long maxValue = 99999L;
//            long range = maxValue - minValue + 1;
//            long userCount = minValue + (long) (random.nextDouble() * range);
//            long unUserCount = minValue + (long) (random.nextDouble() * range);
//
//            sourceUseCountDto.setUnUseCount(unUserCount);
//            sourceUseCountDto.setUseCount(userCount);
//            seUserWorkCount.add(sourceUseCountDto);
//        }
//
//        //-----------------------------------编造数据end----------------------------------------------------



        return success(seUserWorkCount);
    }



    // 热门作者榜单--以user_info中的 receive_rockets 为基准排序, 返回前6 然后再查他们的作品数
    // 作品数 ----暂定都查询--连带着草稿都查询
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/getHotAuthor")
    public AjaxResult getHotAuthor() {

        List<HotAuthorDto> hotAuthorDtoList = new ArrayList<>();

        // 获取前6名
        List<HotAuthorDto> userInfoList = userInfoService.getHotAuthor();

        for(HotAuthorDto userInfo : userInfoList){

            HotAuthorDto hotAuthorDto = new HotAuthorDto();

            hotAuthorDto.setUserId(userInfo.getUserId());
            hotAuthorDto.setNickName(userInfo.getNickName());
            hotAuthorDto.setReceiveRockets(userInfo.getReceiveRockets());

            Long userWorkCount = userWorkService.getUserWorkCountByUserId(userInfo.getUserId());
            // 作品数这里还要去查每个人的作品??--先不做
            hotAuthorDto.setWorkCount(userWorkCount);
            hotAuthorDtoList.add(hotAuthorDto);

        }

        return success(hotAuthorDtoList);
    }

    //资源位榜单--以 sys_source 中的 b_bought 为基准排序, 返回前10
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/getHotSource")
    public AjaxResult getHotSource() {

//        List<HotSourceDto> hotSourceDtoList = new ArrayList<>();

        // 获取前6名
        List<HotSourceDto> sysSourceList = sysSourceService.getHotSource();

        for(HotSourceDto sysSource : sysSourceList){

            sysSource.setNumber(sysSource.getPart()+sysSource.getScale()+String.format("%02d%02d", sysSource.getcX(), sysSource.getcY()));
        }
        return success(sysSourceList);
    }

    //查看资源位详情
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @Log(title = "产品管理--查看资源位详情", businessType = BusinessType.GET)
    @GetMapping("/getSource/{sourceId}")
    public AjaxResult getSource(@PathVariable Long sourceId) {
        SysSource sysSource = new SysSource();
        sysSource.setSourceId(sourceId);

        List<SourceListDto> sysSourceList = sysSourceService.getSysSourceList(sysSource);

        SourceListDto sourceListDto = sysSourceList.get(0);

        LocalDate startTime = sourceListDto.getStartTime();
        LocalDate endTime = sourceListDto.getEndTime();

        System.out.println(startTime+" "+endTime);

        sourceListDto.setTime(sourceListDto.getStartTime() + "~" + sourceListDto.getEndTime());

        long daysBetween = 0L;

        if(startTime!=null && endTime!=null){

            daysBetween = ChronoUnit.DAYS.between(startTime, endTime);

        }





        // 展示天数
        sourceListDto.setpDay(daysBetween);

        // 剩余天数, 这里先置为0
        sourceListDto.setrDay(0L);

        // 价格
//        Map<String, String> price = GsonUtils.fromJson(sourceListDto.getPrice(), HashedMap.class);

        // 编号
        sourceListDto.setNumber(sourceListDto.getPart()+"区"+sourceListDto.getScale()+sourceListDto.getCoordinate());

        sourceListDto.setPriceList(GsonUtils.fromJson(sourceListDto.getPrice(), List.class));

//        sourceListDto.setPriceJson(price);


        return success(sysSourceList);
    }


    // 设置--价格

    // 查询分区价格和图片
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/getPartPriceAndWork")
    public AjaxResult getPartPrice(SysScenic scenic) {

        List<SetPriceAndWorkDto> scenicDefaultList = sysScenicDefaultService.getPartPrice(scenic);


        for(SetPriceAndWorkDto scenicDefault : scenicDefaultList){
//            scenicDefault.setPriceJson(GsonUtils.fromJson(scenicDefault.getPrice(), List.class));

//            List<String> priceList = Arrays.asList(scenicDefault.getPrice().split(","));
//            for(String price : priceList){
//
//            }
//            System.out.println(priceList);

            // 将String 转换成数组
//            scenicDefault.setPriceList(Arrays.asList(scenicDefault.getPrice().split(",")));


//            //---------------------------------特别重要= 将json字符串转换成list-----------------------------------------
//            List<Map<String, SetSourcePriceDto>> list = GsonUtils.fromJson(scenicDefault.getPrice(), List.class);
//            for(Map<String, SetSourcePriceDto> map : list){
//                for(String key : map.keySet()){
//                    System.out.println(key);
//                }
//                System.out.println("map end");
//            }
//
//            System.out.println("list"+ list);
//
//            //---------------------------------特别重要end----------------------------------------------------------------------


            scenicDefault.setPriceList(GsonUtils.fromJson(scenicDefault.getPrice(), List.class));


        }

        return success(scenicDefaultList);


    }

//     修改默认价格和图片--------默认价格修改
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @Transactional
    @Log(title = "产品管理--修改资源位默认价格", businessType = BusinessType.UPDATE)
    @PostMapping("/changeSourcePriceAndWork")
    public AjaxResult changeSourcePrice(@RequestBody SetSourceDto setSourceDto) {

        List<SetSourcePriceDto> priceList = setSourceDto.getPriceList();

        for(SetSourcePriceDto price : priceList){

//            System.out.println("价格前端数据: " + price.getCity()+price.getScenic()+price.getPart());

            // 根据景区和分区查看默认价格--直接插 sys_scenic_default的id 还是 直接把他查出来啊?

            SysScenicDefault sysScenicDefault = sysScenicDefaultService.getScenicDefaultByScenicAndPart(price.getScenic(), price.getPart());

//            System.out.println("默认设置id: " + sysScenicDefault.getId());


            //----------------------------------------------测试----------------------------------------
//            List<SourcePriceVo> priceList1 = price.getPriceList();
//
//            for (SourcePriceVo sourcePriceVo : priceList1) {
//                System.out.println("价格: " + sourcePriceVo.getPrice() + " 天数: " + sourcePriceVo.getDays());
//            }
//
//            System.out.println("价格: " + priceList1.toString());
            //----------------------------------------------测试end---------------------------------------

            sysScenicDefault.setPrice(price.getPriceList().toString());

            System.out.println("查询数据: "+ sysScenicDefault.getPrice());

            // 更新数据库--价格信息
            sysScenicDefaultService.updateSysScenicDefault(sysScenicDefault);

            // 更新sys_source_default中的价格
            sysSourceDefaultService.updateDefaultSourcePrice(sysScenicDefault.getScenicId(), sysScenicDefault.getPart(), price.getPriceList().toString());

            //----------------------------------- 修改所有对应资源位的默认价格--source_status=0------------------------------------------
//            SysSource sysSource = new SysSource();
//            sysSource.setPart(price.getPart());
//            sysSource.setScenic(price.getScenic());
//            sysSource.setCity(price.getCity());
//            sysSource.setSourceStatus("0");
//            sysSource.setPrice(price.getPriceList().toString());


            sysSourceService.updateDefaultSourcePrice(price.getCity(), price.getScenic(), price.getPart(), price.getPriceList().toString());

            // function
            //---------------------------------修改所有对应资源位的默认价格end-------------------------------------------------

        }


        return success("修改成功");



    }


    // 下拉框返回城市和景区列表
//    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @GetMapping("/getCityAndScenic")
    public AjaxResult getCityAndScenic() {

        AjaxResult ajax = new AjaxResult();

        List<SysCity> sysCityList = sysCityService.selectSysCityList(new SysCity());

        List<SysScenic> sysScenicList = sysScenicService.selectSysScenicList(new SysScenic());

        ajax.put("cityList", sysCityList);
        ajax.put("scenicList", sysScenicList);

        return ajax;


    }

    // 上传默认资源位图片--并更新sys_scenic_default默认的图片
    // 修改默认被购买的资源位的默认图片---未完成
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @Transactional
    @Log(title = "产品管理--修改资源位默认图片", businessType = BusinessType.UPDATE)
    @PostMapping("/changeSourceImage")
    public AjaxResult changeSourceImage(@RequestParam("sourceImage") MultipartFile sourceImage,
                                        @RequestParam("city") String city,
                                        @RequestParam("scenic") String scenic,
                                        @RequestParam("part") String part) {

        //------------------------------------------------新版文件上传-------------------------------------------------
        String sourceImagePath = "";
        try{
            sourceImagePath = FileUploadUtils.upload(RuoYiConfig.getProfile()+"/default_source", sourceImage);
        }
        catch (Exception e){
            return error("资源位图片上传失败");
        }
        SysScenicDefault sysScenicDefault = sysScenicDefaultService.getScenicDefaultByScenicAndPart(scenic, part);
        System.out.println("图片路径: " + sourceImagePath);

        // 更改作品默认地址
        sysScenicDefault.setWorkAddress(sourceImagePath);

        // 更新数据库--图片地址
        sysScenicDefaultService.updateSysScenicDefault(sysScenicDefault);

        //-----------------------------修改默认被购买的资源位的默认图片----------------------------------------------

        // 更新资源位默认图片---source_status=0, 没购买的改.
        SysSource sysSource = new SysSource();
        sysSource.setCity(city);
        sysSource.setScenic(scenic);
        sysSource.setPart(part);
        sysSource.setWorkAddress(sourceImagePath);

        // 根据city,scenic,part修改默认图片.
        sysSourceService.updateSysSourceByCP(sysSource);



        //------------------------修改没有被购买的资源位的默认图片end---------------------------------------------------------

        return success();// 可以返回文件的相对路径或URL给前端


//        // ------------------------------------------旧版文件上传----------------------------------------
//        //获取本地图像保存路径
//        String localPath = RuoYiConfig.getProfile();
//
//        if (sourceImage.isEmpty()) {
//            return error("文件为空");
//        }
//        // 验证文件类型（可选，这里只允许jpg,jpeg和png格式）
//        String fileType = sourceImage.getContentType().split("/")[1].toLowerCase();
//        if (!"jpg".equals(fileType) && !"jpeg".equals(fileType) && !"png".equals(fileType)) {
//            return error("只支持jpg和png格式的图片");
//        }
//        String filePath = localPath + "/default_source";
//        try {
//
//            System.out.println("city: "+ city + " scenic: " + scenic + " part: " + part);
//
////            String fileName = IdUtils.fastUUID();
//            String fileName = city+scenic+part;
//
//            // 默认一个景区一个部分只会存在一个默认图片-----------新上传的的会覆盖旧的图片.
//            String uploadFilePath = filePath+"/"+fileName+"_source_default.jpg";
//
//            // 保存文件到服务器
//            sourceImage.transferTo(new File(filePath, fileName+"_source_default.jpg"));
////            boolean flag = sysUserService.updateUserAvatar(userName,filePath+"/"+userName+"_avatar.jpg");
//
//            SysScenicDefault sysScenicDefault = sysScenicDefaultService.getScenicDefaultByScenicAndPart(scenic, part);
//
//            // 更改作品默认地址
//            sysScenicDefault.setWorkAddress(uploadFilePath);
//
//            // 更新数据库--图片地址
//            sysScenicDefaultService.updateSysScenicDefault(sysScenicDefault);
//
//            //-----------------------------修改默认被购买的资源位的默认图片----------------------------------------------
//
//            // 更新资源位默认图片---source_status=0
//            SysSource sysSource = new SysSource();
//            sysSource.setCity(city);
//            sysSource.setScenic(scenic);
//            sysSource.setPart(part);
//            sysSource.setWorkAddress(uploadFilePath);
//
//            // 根据city,scenic,part修改默认图片.
//            sysSourceService.updateSysSourceByCP(sysSource);
//
//
//
//            //------------------------修改没有被购买的资源位的默认图片end---------------------------------------------------------
//
//            return success();// 可以返回文件的相对路径或URL给前端
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            return error("文件上传失败");
//        }
//        //-------------------------------------------------旧版文件上传--------------------------------------------------


    }

    // 产品管理--设置--获取资源位分布坐标, 便于修改单个资源位图片
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @PostMapping("/getAllSourceCoordinate")
    public AjaxResult getAllSourceCoordinate(@RequestBody SysSource sysSource) {

        System.out.println("搜索条件: "+sysSource.getCity()+sysSource.getScenic());

        //------------------------------------------------资源位预览图------------------------------------------
//        SysScenic sysScenic = new SysScenic();
//        sysScenic.setScenic(sysSource.getScenic());
//        sysScenic.setCity(sysSource.getCity());
//        SysScenic sysScenic_1 = sysScenicService.selectSysScenicList(sysScenic).get(0);
//        String preview = sysScenic_1.getPreview();
        //------------------------------------------------资源位预览图end---------------------------------------


        int horizontalCount = 0;
        int verticalCount = 0;

        List<SysSource> sysSourceList = sysSourceService.selectSysSourceList(sysSource);

        // 这里写的也太迂回了吧, 就这样吧
//        ShowSysSourceDto showSysSource = new ShowSysSourceDto();
        List<ShowSysSourceListDto> showSysSourceList = new ArrayList<>();

        System.out.println("sysSourceList: "+sysSourceList.size());
        for(SysSource sysSource1 : sysSourceList){
//            // 没必要解析price数据
//            sysSource1.setPriceList(GsonUtils.fromJson(sysSource1.getPrice(), List.class));
            ShowSysSourceListDto showSysSourceListDto = new ShowSysSourceListDto();
            showSysSourceListDto.setSourceId(sysSource1.getSourceId());
            showSysSourceListDto.setPart(sysSource1.getPart());
            showSysSourceListDto.setcX(sysSource1.getcX());
            showSysSourceListDto.setcY(sysSource1.getcY());
            showSysSourceListDto.setSourceStatus(sysSource1.getSourceStatus());
            showSysSourceListDto.setWorkAddress(sysSource1.getWorkAddress());


            horizontalCount = Math.max(sysSource1.getcX(), horizontalCount);
            verticalCount = Math.max(sysSource1.getcY(), verticalCount);

            showSysSourceList.add(showSysSourceListDto);

        }

        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("horizontalCount", horizontalCount+1);
        ajaxResult.put("verticalCount", verticalCount+1);
        ajaxResult.put("sourceList", showSysSourceList);

        return ajaxResult;

    }

    // 产品管理--设置--修改指定资源位的当前背景,
    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @Log(title = "产品管理--修改指定资源位默认图片", businessType = BusinessType.UPDATE)
    @PostMapping("/changeSingleSourceImage")
    public AjaxResult changeSingleSourceImage(@RequestParam("sourceImage") MultipartFile sourceImage,
                                                @RequestParam("sourceId") Long sourceId) {

        if (sourceImage.isEmpty()) {
                return error("文件为空");
            }
            //------------------------------------------------新版文件上传-------------------------------------------------
            String sourceImagePath = "";
            try{
                sourceImagePath = FileUploadUtils.upload(RuoYiConfig.getProfile()+"/single_source", sourceImage);
            }
            catch (Exception e){
                return error("头像文件上传失败");
            }
            //----------------------------------------------新版文件上传end-----------------------------------------------

            try {

                // 修改资源位的图片, 先都能修改吧
                SysSource sysSource = sysSourceService.selectSysSourceBySourceId(sourceId);
                sysSource.setWorkAddress(sourceImagePath);
                int flag = sysSourceService.updateSysSource(sysSource);
                if (flag > 0){
                    AjaxResult ajax = success();
                    ajax.put("workAddress", sourceImagePath);
                    return ajax;// 可以返回文件的相对路径或URL给前端
                }
                else{
                    return error("修改头像失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
                return error("文件上传失败");
            }



    }
    // 产品管理--设置--批量修改指定资源位图片

    @PreAuthorize("@ss.hasPermi('system:goods:list')")
    @Transactional
    @PostMapping("/changeMultiSourceImage")
    public AjaxResult changeMultiSourceImage(@RequestParam("sourceImage") MultipartFile sourceImage,
                                             @RequestParam("sourceStrList") String sourceStrList) {


        // 一个文件不能多次存储
        if (sourceImage.isEmpty()) {
            return error("文件为空");
        }
        //------------------------------------------------新版文件上传-------------------------------------------------
        String sourceImagePath = "";
        try{
            sourceImagePath = FileUploadUtils.upload(RuoYiConfig.getProfile()+"/single_source", sourceImage);
        }
        catch (Exception e){
            return error("头像文件上传失败");
        }
        //----------------------------------------------新版文件上传end-----------------------------------------------
        // System.out.println("sourceImagePath: "+sourceImagePath);

        List<Double> sourceIdList = GsonUtils.fromJson(sourceStrList, List.class);



        for (Double sourceDId : sourceIdList) {
            Long sourceId = sourceDId.longValue();
            System.out.println("sourceId: "+sourceId);
            // 修改资源位的图片, 先都能修改吧
            SysSource sysSource = sysSourceService.selectSysSourceBySourceId(sourceId);
            sysSource.setWorkAddress(sourceImagePath);
            sysSourceService.updateSysSource(sysSource);


            // sys_source_default修改资源位默认图片
            sysSourceDefaultService.updateSysSourceDefaultWorkBySourceId(sourceId, sourceImagePath);

        }
        AjaxResult ajax = success();
        ajax.put("workAddress", sourceImagePath);
        return ajax;// 可以返回文件的相对路径或URL给前端

    }


    // 设置--默认图片
}
