package com.ruoyi.web.controller.app;


import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaDisableException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.utils.*;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.system.domain.*;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.AppLoginBody;
import com.ruoyi.common.core.domain.model.AppRegisterUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysRegisterService;
//import com.ruoyi.system.domain.UserWork;
import com.ruoyi.system.domain.dto.*;
import com.ruoyi.system.domain.vo.OrderCacheVo;
import com.ruoyi.system.domain.vo.SourcePriceVo;
import com.ruoyi.system.domain.vo.UserMessageVo;
import com.ruoyi.system.service.*;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.web.controller.app.baidu.GsonUtils;
import com.ruoyi.web.controller.app.baidu.OcrIdCardBAI;
//import com.ruoyi.web.controller.app.pay.PayService;
import com.ruoyi.web.controller.app.juhe.JuheAuthentication;
import com.ruoyi.web.controller.backstage.BackstageController;
import javafx.scene.chart.StackedAreaChart;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/app/system")
public class AppSystemController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(BackstageController.class);

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IUserInfoService userInfoService;


    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IUserWorkService userWorkService;

    @Autowired
    private IWorkReviewService workReviewService;

    @Autowired
    private ISysSourceService sysSourceService;

    @Autowired
    private ISysOrderService sysOrderService;

    @Autowired
    private IAppVersionService appVersionService;

//    @Autowired
//    private PayService payService;

    @Autowired
    private ISysUserFollowService userFollowService;

    @Autowired
    private ISysUserNotificationService userNotificationService;

    @Autowired
    private ISysUserLikeService  userLikeService;

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private ISysUserLikeService sysUserLikeService;


    @Autowired
    private ISysScenicService sysScenicService;

    @Autowired
    private IDailySourceService dailySourceService;




    /**
     * 账号密码登录
     *
     * @param loginBody
     * @return
     */
    @PostMapping("/loginPassword")
    public AjaxResult loginPassword(@RequestBody AppLoginBody loginBody)  {
        AjaxResult ajax = success();
        // 生成令牌
        String token = loginService.appLoginPassword(loginBody.getUsername(), loginBody.getPassword());

        Long userId = sysUserService.selectUserByUserName(loginBody.getUsername()).getUserId();
        ajax.put(Constants.TOKEN, token);
        ajax.put("userId",userId);
        return ajax;
    }


    /**
     * 验证码登录
     * @param loginBody
     * @return
     */
    @PostMapping("/loginSms")
    public AjaxResult loginMessage(@RequestBody AppLoginBody loginBody) {
        AjaxResult ajax = success();
        // 生成令牌
        String token = loginService.appLoginMessage(loginBody.getUsername(), loginBody.getCode(),loginBody.getPhone());
        Long userId = sysUserService.selectUserByUserName(loginBody.getUsername()).getUserId();
        ajax.put(Constants.TOKEN, token);
        ajax.put("userId",userId);
        return ajax;
    }
    /*
    * 跟新密码时的验证码对比
    * */
    @PostMapping("/verifyUpdatePasswordSms")
    public AjaxResult verifyUpdatePasswordSms(@RequestBody PhoneSMSDto phoneSMSDto) {

        String username = SecurityUtils.getUsername();
        String code = phoneSMSDto.getCode();
        appvalidateCaptcha(username, code, username);

        return success();

    }

    /**
     * 注册
     * @param user
     * @return
     */

    @PostMapping("/register")
    public AjaxResult register(@RequestBody AppRegisterUser user){
        String msg = registerService.AppRegister(user);
        return StringUtils.isEmpty(msg) ? success() : error(msg);
    }


    //更新密码根据旧密码来更新密码
    @PutMapping("/updatePassword")
    public AjaxResult updatePassword(@RequestBody UpdatePwdDto updatepwdDto){
        String oldPassword = updatepwdDto.getOldPassword();
        String newPassword = updatepwdDto.getNewPassword();
        String phone = updatepwdDto.getPhone();

        String username = SecurityUtils.getUsername();

        if(!username.equals(phone)){
            return error("用户不存在");
        }

        SysUser sysUser = sysUserService.selectUserByUserName(phone);

        String truePassword = sysUser.getPassword();

        if (!SecurityUtils.matchesPassword(oldPassword, truePassword))
        {
            return error("旧密码错误");
        }
        if (sysUserService.resetUserPwd(phone, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            return success();
        }

        return error("修改密码异常，请联系管理员");

    }
    //更新密码
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(@RequestBody UpdatePwdDto updatepwdDto)
    {
//        String oldPassword = updatepwdDto.getOldPassword();
        String newPassword = updatepwdDto.getNewPassword();
        String phone = updatepwdDto.getPhone();
        String code = updatepwdDto.getCode();

        String username = SecurityUtils.getUsername();

        System.out.println(username);
        System.out.println(phone);

        if (!username.equals(phone)){
            return error("手机号错误");
        }

        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + phone;
        String captcha = redisCache.getCacheObject(verifyKey);
//            System.out.println(captcha);

        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            return error("验证码过期");
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
//                throw new CaptchaException();
            return error("验证码错误");
        }


        SysUser sysUser = sysUserService.selectUserByUserName(phone);
        if (sysUser == null)
        {
            return error("用户不存在");
        }
        String userName = sysUser.getUserName();
        String password = sysUser.getPassword();
//        if (!SecurityUtils.matchesPassword(oldPassword, password))
//        {
//            return error("修改密码失败，旧密码错误");
//        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        if (sysUserService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 删除缓存中的验证码
            redisCache.deleteObject(verifyKey);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    @PutMapping("/forgetPassword")
    public AjaxResult forgetPassword(@RequestBody UpdatePwdDto updatepwdDto)
    {
        String newPassword = updatepwdDto.getNewPassword();
        String phone = updatepwdDto.getPhone();
        String code = updatepwdDto.getCode();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + phone;
        String captcha = redisCache.getCacheObject(verifyKey);

        System.out.println("验证码是: "+captcha);
        System.out.println("code: "+code);

        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            return error("验证码过期");
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(phone, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            return error("验证码错误");
        }


        SysUser sysUser = sysUserService.selectUserByUserName(phone);
        if (sysUser == null)
        {
            return error("用户不存在");
        }
        String userName = sysUser.getUserName();
        String password = sysUser.getPassword();
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return error("新密码不能与旧密码相同");
        }
        if (sysUserService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 删除缓存中的验证码
            redisCache.deleteObject(verifyKey);
            return success();
        }
        return error("修改密码异常，请联系管理员");
    }

    //----------更新用户头像-------------------------
    @PutMapping("/uploadAvatar")
    public AjaxResult uploadAvatar(@RequestParam("user_name") String userName,
                                   @RequestParam("avatarImage") MultipartFile avatarImage)
    {

        //头像图片
        if (avatarImage.isEmpty()) {
            return error("文件为空");
        }
        //------------------------------------------------新版文件上传-------------------------------------------------
        String fileName = "";
        try{
             fileName = FileUploadUtils.upload(RuoYiConfig.getProfile()+"/avatar", avatarImage);
        }
        catch (Exception e){
            return error("头像文件上传失败");
        }
        LoginUser loginUser = getLoginUser();
        boolean flag = sysUserService.updateUserAvatar(loginUser.getUsername(), fileName);
        if (flag){
            AjaxResult ajax = success();
            ajax.put("上传头像地址", fileName);
            return ajax;// 可以返回文件的相对路径或URL给前端
        }
        else{
            return error("修改头像失败");
        }

        //-----------------------------------------------新版文件上传end-----------------------------------------------

    }
    //-----------------------------实名认证---------------------------------
    @Transactional
    @PostMapping("/realNameAuthentication")
    public AjaxResult realNameAuthentication(
            @RequestParam("realNameAuthenticationDto") String realNameAuthenticationDtoString
//            ,@RequestParam("realNameAuthenticationDto")
                                            ,@RequestParam("cardFront") MultipartFile cardFront
                                            ,@RequestParam("cardBack") MultipartFile cardBack)
    {
        //将String转换为对象，假设前端校验了用户名，身份证号
        RealNameAuthenticationDto realNameAuthenticationDto = GsonUtils.fromJson(realNameAuthenticationDtoString, RealNameAuthenticationDto.class);

        //获取用户输入和真实姓名和身份证号
        String pRealName = realNameAuthenticationDto.getReal_name();
        String pIdCard = realNameAuthenticationDto.getId_card();
//        String userName = realNameAuthenticationDto.getUser_name();

        String username = SecurityUtils.getUsername();


        // 正式时这里会有登录认证，所以不存在未注册用户
        //-----------------------先判断是否实名认证过-------没必要--------------------



        if (cardFront.isEmpty() || cardBack.isEmpty()) {
            return error("文件为空");
        }
//        //---------------------------------------------------新版文件上传--------------------------------------------------
//        String cardFrontPath = "";
//        String cardBackPath = "";
//        try{
//            cardFrontPath = FileUploadUtils.upload(RuoYiConfig.getIdCardPath()+"/avatar", cardFront);
//            cardBackPath = FileUploadUtils.upload(RuoYiConfig.getIdCardPath()+"/avatar", cardBack);
//        }
//        catch (Exception e){
//            return error("身份证图片文件上传失败");
//        }
//        //---------------------------------------------------新版文件上传end--------------------------------------------------

        //--------------------------------------------------------旧版文件上传-------------------------------------------------------------
        // 验证文件类型（可选，这里只允许jpg,jpeg和png格式）
        String fileType1 = cardFront.getContentType().split("/")[1].toLowerCase();
        if (!"jpg".equals(fileType1) && !"jpeg".equals(fileType1) && !"png".equals(fileType1)) {
            return error("只支持jpg和png格式的图片");
        }

        String fileType2 = cardBack.getContentType().split("/")[1].toLowerCase();
        if (!"jpg".equals(fileType2) && !"jpeg".equals(fileType2) && !"png".equals(fileType2)) {
            return error("只支持jpg和png格式的图片");
        }



//        String filePath = localPath + "/id_card";

        String localPathId = RuoYiConfig.getIdCardPath();
        String filePath = localPathId;


        try {
            // 保存文件到服务器
            cardFront.transferTo(new File(filePath, username+"_card_front.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
            return error("身份证人像照上传失败");
        }
        try {
            // 保存文件到服务器
            cardBack.transferTo(new File(filePath, username+"_card_back.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
            return error("身份证人像照上传失败");
        }
        //-------------------------------------------------------------旧版文件上传end-------------------------------------------------------------

        //验证上传身份证
        OcrIdCardBAI ocrIdCardBAI= new OcrIdCardBAI();
        // 先不做复杂验证了，就只判断姓名和身份证号是否一致---------获取人像面------------------------------
        String result = ocrIdCardBAI.idcard(filePath+"/"+username+"_card_front.jpg", "front", "true", "true", "true", "false");
        BaiduIdCard baiduIdCard = GsonUtils.fromJson(result, BaiduIdCard.class);

        String qRealName = baiduIdCard.getWords_result().get("姓名").getWords();
        String qIdCard = baiduIdCard.getWords_result().get("公民身份号码").getWords();
        String qSex = baiduIdCard.getWords_result().get("性别").getWords();
        String birth = baiduIdCard.getWords_result().get("出生").getWords();
//        //-----------------------------------------------end人像面-----------------------------------------------
        String resultBack = ocrIdCardBAI.idcard(filePath+"/"+username+"_card_back.jpg", "back", "true", "true", "true", "false");
        BaiduCardBack baiduCardBack = GsonUtils.fromJson(resultBack, BaiduCardBack.class);
        String expiryDate = baiduCardBack.getWords_result().get("失效日期").getWords();

        // 删除上传图片

        Path path_front = Paths.get(filePath+"/"+username+"_card_front.jpg");
        Path path_back = Paths.get(filePath+"/"+username+"_card_back.jpg");

        try {
            Files.delete(path_front);
            Files.delete(path_back);

            System.out.println("删除成功");
        } catch (IOException e) {
            System.err.println("删除失败：" + e.getMessage());
        }


        if(!pRealName.equals(qRealName) || !pIdCard.equals(qIdCard)){
            return error("实名认证信息不一致");
        }
        else{
//            Long userId = sysUserService.selectUserByUserName(username).getUserId();

            Long userId = getUserId();

            System.out.println("userId:"+userId);
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(userId);
            userInfo.setAuthenticationStatus("1");
            userInfo.setRealName(pRealName);
            userInfo.setIdCard(pIdCard);
            if (qSex.equals("男")){
                userInfo.setSex("0");
            }
            else{
                userInfo.setSex("1");
            }
            userInfo.setCardFront(filePath+"/"+username+"_card_front.jpg");
            userInfo.setCardBack(filePath+"/"+username+"_card_back.jpg");
            long currentTimeMillis = System.currentTimeMillis();
            // 利用毫秒值构造Date对象
            Date currentDate = new Date(currentTimeMillis);
            userInfo.setUpdateTime(currentDate);
            userInfo.setBirth(birth);

            // 这里先默认是0 居民身份证
            userInfo.setIdType("0");

            int back = userInfoService.updateUserInfo(userInfo);
            if(back==0){
                return error("实名认证失败");
            }
            else{
                System.out.println("实名认证成功");
                return success("实名认证成功");
            }

        }

    }

    //---------------------------聚合数据三网认证-------------------------------------------------
    @Transactional
    @PostMapping("/juheAuthentication")
    public AjaxResult juheAuthentication(@RequestBody JuheAuthenticationDto juheAuthenticationDto) throws Exception {

        String realname = juheAuthenticationDto.getRealname();
        String idcard = juheAuthenticationDto.getIdcard();
        String mobile = juheAuthenticationDto.getMobile();
        String code = juheAuthenticationDto.getCode();

        String username = SecurityUtils.getUsername();

        // 验证短信验证码
        appvalidateCaptchaJuhe(username, code, mobile);

        Long userId = getUserId();
        UserInfo userInfo = userInfoService.selectUserInfoByUserId(userId);
        if(userInfo == null){
            return error("用户不存在");
        }

        if(userInfo.getAuthenticationStatus().equals("1")){
            return error("用户已实名认证");
        }

        // 调用聚合数据三网认证
        if(!JuheAuthentication.authentication(realname, idcard, mobile)){
            return error("认证信息不符");
        }

        // 更新数据库
        userInfo.setAuthenticationStatus("1");
        userInfo.setRealName(realname);
        userInfo.setIdCard(idcard);
        userInfoService.updateUserInfo(userInfo);

        // 删除缓存
        // 缓存的验证码和试错次数
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + mobile;
        String countKey = CacheConstants.CAPTCHA_CODE_KEY_COUNT + mobile;
        redisCache.deleteObject(verifyKey);
        redisCache.deleteObject(countKey);

        return success("实名认证成功");
    }



    // 获取用户个人信息
    @GetMapping("/getUserInfo/{phone}")
    public AjaxResult getUserInfo(@PathVariable String phone)
    {

        //----------------------------------------旧版-----------------------------------
//        String username = SecurityUtils.getUsername();
//        if (!username.equals(phone))
//        {
//            return error("token和用户名不符");
//        }
//
//        SysUser sysUser = sysUserService.selectUserByUserName(phone);
//
//        if(sysUser==null){
//            return error("用户不存在");

//        UserInfo userInfo = userInfoService.selectUserInfoByUserId(sysUserService.selectUserByUserName(phone).getUserId());//
        //------------------------------旧版 end---------------------------------------------------

        //----------------------------新版-----------------------------------------------------
        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);



        UserInfo userInfo = userInfoService.selectUserInfoByUserId(userId);

        //-----------------------------------新版end----------------------------------------------

        String nickName = sysUser.getNickName();
        String signature = userInfo.getSignature();
        String authenticationStatus = userInfo.getAuthenticationStatus();
        String avatar = sysUser.getAvatar();
        String background = userInfo.getBackGround();
        AjaxResult ajax = success();
        ajax.put("nickName",nickName);
        ajax.put("signature",signature);
        ajax.put("avatar",avatar);
        ajax.put("background", background);
        ajax.put("authenticationStatus", authenticationStatus);

        //------------------------- 20241227--添加--获取关注数(我关注的人数),欢迎度(关注我的人数), 喜爱(我的作品总的点赞数)



        // 喜爱
        ajax.put("popularity", userInfo.getReceiveRockets());

        // 关注,我关注的人数------暂定从 sys_user_follow表里获取-----------为了效率应该单开一个字段存储-----后续可以优化
        // 可以直接从 user_info中获取
        ajax.put("following", userFollowService.getFollowingCount(userId));

        // 欢迎度, 多少人关注了我
        ajax.put("followed", userFollowService.getFollowedCount(userId));

        return ajax;
    }

    // 设置--更新个人信息
    @Transactional
    @PostMapping("/updateNickSign")
    public AjaxResult updateUserInfo(@RequestParam("updateNickSignDto") String updateNickSignDt, @RequestParam("avatar") MultipartFile avatarImage)
    {
        UpdateNickSignDto updateNickSignDto = GsonUtils.fromJson(updateNickSignDt, UpdateNickSignDto.class);
        String nickName = updateNickSignDto.getNickname();
        String signature = updateNickSignDto.getSignature();

        String username = SecurityUtils.getUsername();

        System.out.println("头像图片是否为空: "+avatarImage.isEmpty());

        // 和以前一样就不用修改了
        // 新的昵称不为空
        if(!StringUtils.isEmpty(nickName)){
            SysUser sysUser = sysUserService.selectUserByUserName(username);
            if (!nickName.equals(sysUser.getNickName())){
                boolean f1 = sysUserService.updateNickName(username,nickName);
                if(!f1){
                    return error("更新昵称失败");
                }
            }

        }
        // 新签名

        UserInfo userInfo = userInfoService.selectUserInfoByUserId(getUserId());
        if(!signature.equals(userInfo.getSignature())) {
            boolean f2 = userInfoService.updateSignature(username, signature);
            if (!f2) {
                return error("更新签名失败");
            }
        }


        if (!avatarImage.isEmpty()){
            //-----------------------------------------新版文件上传------------------------------------------------------
            String avatarFilePath = "";
            try {
                // 保存文件到配置的路径
                avatarFilePath = FileUploadUtils.upload(RuoYiConfig.getProfile()+"/avatar", avatarImage);
            } catch (Exception e) {
                return error("更新头像文件失败");
            }
            boolean flag = sysUserService.updateUserAvatar(username,avatarFilePath);
            if (flag){
                AjaxResult ajax = success();
                ajax.put("上传头像地址", avatarFilePath);
                return ajax;// 可以返回文件的相对路径或URL给前端
            }
            else{
                return error("修改头像失败");
            }
            //-----------------------------------------新版文件上传---------------------------------------------------
        }
        else{
            return success("更新昵称和介绍成功");
        }





//        //--------------------------------------旧版文件上传--------------------------------------------------------
//
//        String localPath = RuoYiConfig.getProfile();
//
//
//
//        //头像图片---可以为空
//        if (!avatarImage.isEmpty()) {
//            //        String mimeType = avatarImage.getContentType();
////        System.out.println(mimeType);
//            // 验证文件类型（可选，这里只允许jpg,jpeg和png格式）
//            String fileType = avatarImage.getContentType().split("/")[1].toLowerCase();
////        System.out.println(avatarImage.getContentType());
//            System.out.println(fileType);
//            if (!"jpg".equals(fileType) && !"jpeg".equals(fileType) && !"png".equals(fileType)) {
//                return error("只支持jpg、jpeg和png格式的图片");
//            }
//            String filePath = localPath + "/avatar";
//            try {
//                // 保存文件到服务器
//                avatarImage.transferTo(new File(filePath, username+"_avatar.jpg"));
//                boolean flag = sysUserService.updateUserAvatar(username,filePath+"/"+username+"_avatar.jpg");
//                if (flag){
//                    AjaxResult ajax = success();
//                    ajax.put("上传头像地址", filePath+"/"+username+"_avatar.jpg");
//                    return ajax;// 可以返回文件的相对路径或URL给前端
//                }
//                else{
//                    return error("修改头像失败");
//                }
//
//            } catch (IOException e) {
//                e.printStackTrace();
//                return error("头像文件上传失败");
//            }
//
//        }
//
//        return success("修改信息成功");
//        //-------------------------------------------------旧版文件上传end----------------------------------------------------------------

    }
//    @PostMapping("/createWork")
//    public AjaxResult createWork(@RequestParam("userWorkDto") String userWorkDto
//            ,@RequestParam("userWorkFile") MultipartFile userWorkFile)
//    {
//        Long userId = SecurityUtils.getUserId();
//
//        UserWork userWork = GsonUtils.fromJson(userWorkDto, UserWork.class);
////        String workName = userWork.getWorkName();
//        System.out.println(userWork);
//        return AjaxResult.success();
//    }

    @GetMapping("/logOut")
    public AjaxResult logOut()
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String uuid = loginUser.getToken();
//        System.out.println(loginUser.getUsername());
        if (StringUtils.isNotEmpty(uuid)){
            tokenService.delLoginUser(uuid);
            return success("注销用户");
        }
        return error("注销失败，请联系管理员");

    }

    @PostMapping("/changeBackground")
    public AjaxResult changeBackground(@RequestParam("username") String userName,
                                       @RequestParam("background") MultipartFile background)
    {

        String username = SecurityUtils.getUsername();



        if (background.isEmpty()) {
            return error("文件为空");
        }
        //-----------------------------------------新版文件上传------------------------------------------------------
        String backgroundFilePath = "";
        try {
            // 保存文件到配置的路径
            backgroundFilePath = FileUploadUtils.upload(RuoYiConfig.getProfile()+"/background", background);
        } catch (Exception e) {
            return error("更新头像文件失败");
        }
        boolean flag = userInfoService.updateBackground(username, backgroundFilePath);
        if (flag){
            AjaxResult ajax = success();
            ajax.put("上背景图片地址", backgroundFilePath);
            return ajax;
        }
        else{
            return error("修改头像失败");
        }
        //-----------------------------------------新版文件上传---------------------------------------------------
//        //-------------------------------------------旧版文件上传---------------------------------------------------
//        String localPath = RuoYiConfig.getProfile();
//        // 验证文件类型（可选，这里只允许jpg,jpeg和png格式）
//        String fileType = background.getContentType().split("/")[1].toLowerCase();
//        if (!"jpg".equals(fileType) && !"jpeg".equals(fileType) && !"png".equals(fileType)) {
//            return error("只支持jpg、jpeg和png格式的图片");
//        }
//        String filePath = localPath + "/background";
//        try {
//            // 保存文件到服务器
//            background.transferTo(new File(filePath, username+"_background.jpg"));
//            boolean flag = userInfoService.updateBackground(username, filePath+"/"+username+"_background.jpg");
//            if(flag){
//                AjaxResult ajax = success();
//                ajax.put("上背景图片地址", filePath+"/"+username+"_background.jpg");
//                return ajax;// 可以返回文件的相对路径或URL给前端
//            }
//            else{
//                return error("更新背景图片失败");
//            }
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            return error("文件上传失败");
//        }
//        //-------------------------------------旧版文件上传end------------------------------------------------------
    }

    // 用户创建作品
    @PostMapping("createUserWork")
    public AjaxResult createUserWork(@RequestParam("workDto") String userWorkDtoString,
                                 @RequestParam("work") MultipartFile workImage)
    {

        UserWorkDto userWorkdto = GsonUtils.fromJson(userWorkDtoString, UserWorkDto.class);
        String username = SecurityUtils.getUsername();

        String workName = userWorkdto.getWorkName();
        String workType = userWorkdto.getWorkStatus();
        String workDetail = userWorkdto.getDetail();

        Long userId = SecurityUtils.getUserId();

        UserWork userWork = new UserWork();

        userWork.setUserId(userId);
        userWork.setWorkName(workName);
        userWork.setWorkStatus(workType);
        userWork.setDetail(workDetail);
        userWork.setCoordinate("0000");


        if (workImage.isEmpty()) {
            return error("文件为空");
        }
        //-----------------------------------------新版文件上传------------------------------------------------------
        String workImageFilePath = "";
        try {
            // 保存文件到配置的路径
            workImageFilePath = FileUploadUtils.upload(RuoYiConfig.getProfile()+"/work", workImage);
            userWork.setWorkAddress(workImageFilePath);
            boolean flag = userWorkService.insertUserWork(userWork) > 0;
            if(flag){

                return success("保存作品成功");// 可以返回文件的相对路径或URL给前端
            }
            else{
                return error("保存作品失败");
            }
        } catch (Exception e) {
            return error("上传作品文件失败");
        }
        //------------------------------------新版文件上传end-------------------------------------------------------

//        //-----------------------------------------------------旧版文件上传------------------------------------------------------
//        String localPath = RuoYiConfig.getProfile();
//        // 验证文件类型（可选，这里只允许jpg,jpeg和png格式）
//        String fileType = workImage.getContentType().split("/")[1].toLowerCase();
//        if (!"jpg".equals(fileType) && !"jpeg".equals(fileType) && !"png".equals(fileType) && !"mp4".equals(fileType)) {
//            return error("只支持jpg、jpeg和png格式的图片和mp4格式的视频");
//        }
//        String uuid = IdUtils.simpleUUID();
//
//        String filePath = localPath + "/work";
//        try {
//            // 保存文件到服务器
//            workImage.transferTo(new File(filePath, username+uuid+"."+fileType));
//            userWork.setWorkAddress(filePath+"/"+username+uuid+"."+fileType);
//            boolean flag = userWorkService.insertUserWork(userWork) > 0;
//
//            if(flag){
//
//                return success("保存作品成功");// 可以返回文件的相对路径或URL给前端
//            }
//            else{
//                return error("保存作品失败");
//            }
//
//        } catch (IOException e) {
//            e.printStackTrace();
//            return error("作品文件上传失败");
//        }
//        //----------------------------------------- 旧版文件上传end------------------------------------------------------------------

    }

//    @GetMapping("getMessage")
//    public AjaxResult getMessage(){
//        Long user_id = SecurityUtils.getUserId();
//
//        return AjaxResult.success();
//    }


//    //
//    // 多表修改要保证修改的数据的一致性
//    @Transactional
//    @PostMapping("/publishUserWork")
//    public AjaxResult publishUserWork(@RequestBody List<PublishUserWorkDto> publishUserWorkDtoList)
//    {
//        Long userId = SecurityUtils.getUserId();
//
//        List<Long> orderIdList = new ArrayList<>();
//
//        boolean flag = false;
//
//        // 总价格 以分为单位
//        Long totalPrice = 0L;
//
//
//        for(PublishUserWorkDto publishUserWorkDto:publishUserWorkDtoList){
//            Long workId = publishUserWorkDto.getWorkId();
//            Long sourceId = publishUserWorkDto.getSourceId();
//            String type = publishUserWorkDto.getType();
//
//            LocalDate startTime = publishUserWorkDto.getStartTime();
//            LocalDate endTime;
//
//            if(type.equals("one")){
//                endTime = startTime.plusDays(1);
//            }
//            else if(type.equals("seven")){
//                endTime = startTime.plusDays(7);
//            }
//            else if(type.equals("fifteen")){
//                endTime = startTime.plusDays(15);
//            }
//            else if(type.equals("thirty")){
//                endTime = startTime.plusDays(30);
//            }
//            else{
//                return error("非法操作, 已记录ip");
//            }
//
//
//            System.out.println("startTime: "+startTime+" endTime: "+endTime);
//
//            // 查看 work 是否属于这个人
//            UserWork userWork = userWorkService.selectUserWorkByWorkId(workId);
//
//            if(userWork == null || !userWork.getUserId().equals(userId)){
//                return error("用户与作品不符, 已记录ip");
//            }
//
//            // 检查时间是否合法, 从订单中查询当前资源位的订单时间, 每个资源位一年最多有 366条数据
//            int back = sysOrderService.isTimeLegal(startTime, endTime, sourceId);
//            if(back != 0){
//                return error("时间不合法");
//            }
//
//
//            // 查询 资源位信息
//            SysSource source = sysSourceService.selectSysSourceBySourceId(sourceId);
//
//            // 获得资源位价格
//            SourcePriceDto price = GsonUtils.fromJson(source.getPrice(), SourcePriceDto.class);
//
//            totalPrice = totalPrice + Long.parseLong(price.getOne());
//
//            //插入订单数据
//
//            SysOrder sysOrder = new SysOrder();
//
//            sysOrder.setUserId(userId);
//            sysOrder.setSourceId(sourceId);
//            sysOrder.setCreateTime(DateUtils.getNowDate());
//            sysOrder.setStartTime(startTime);
//            sysOrder.setEndTime(endTime);
//
//            int back1 = sysOrderService.insertSysOrder(sysOrder);
//
//            if (back1 == 0){
//                return error("插入订单数据失败");
//            }
//            // 这怎么返回 order_id 啊??
//            List<SysOrder> sysOrders = sysOrderService.selectSysOrderList(sysOrder);
//            orderIdList.add(sysOrders.get(0).getOrderId());
//
//
//        }
//        if (flag){
//            return error("非法操作, 已记录ip");
//        }
//
//        System.out.println(orderIdList);
//
//        // 旧版本接口
////        boolean back = payService.genOrder(orderIdList, totalPrice, userId);
//        boolean back = true;
//
//        if(back){
//            return success("支付成功");
//        }
//        else{
//
//            //生成失败的话---------------删除订单数据------不要占空间了.
//            for(Long orderId:orderIdList){
//                sysOrderService.deleteSysOrderByOrderId(orderId);
//            }
//
//            return error("支付失败");
//        }
//
//        // 生成订单--调用生成订单函数
//
//
////        return success(totalPrice);
//
//
//        //-------------------------------------------old--------------------------------------------------------
////        // 这里也不需要判断 作品所有者id和当前用户id是否一致.默认就是一致
////        Long userId = SecurityUtils.getUserId();
////        boolean flag = true;
////
////        for(PublishUserWorkDto publishUserWorkDto:publishUserWorkDtoList){
////            Long workId = publishUserWorkDto.getWorkId();
////            Long sourceId = publishUserWorkDto.getSourceId();
////            float price = publishUserWorkDto.getPrice();
////            Long orderId = publishUserWorkDto.getOrderId();
//////            System.out.println(workId);
////
////            //首先根据workId查询作品, 默认一个作品对应一个资源位
////            UserWork userWork = userWorkService.selectUserWorkByWorkId(workId);
////            //根据sourceId查询资源位信息
////            SysSource source = sysSourceService.selectSysSourceBySourceId(sourceId);
////
////            if(userWork == null || source == null){
////                flag = false;
////                break;
////            }
//////            System.out.println(source.getSourceId());
////
////            //设定作品信息
////            userWork.setPostTime(new Date());
////            userWork.setSourceId(sourceId);
////            userWork.setPrice(price);
////            userWork.setCity(source.getCity());
////            userWork.setScenic(source.getScenic());
////            userWork.setPart(source.getPart());
//////            userWork.setScale(source.getScale());
////            userWork.setCoordinate(source.getCoordinate());
////            // 已发表未审核
////            userWork.setWorkStatus("2");
////
////            int back1 = userWorkService.updateUserWork(userWork);
////            if(back1 > 0){
////
////                System.out.println("更新作品信息成功");
////                // 更新资源位信息, 订单那里要判断资源位有没有被购买........
////                source.setWorkAddress(userWork.getWorkAddress());
////                // 已购
////                source.setSourceStatus("2");
////                source.setbBought(source.getbBought()+1);
////                source.setOrderId(orderId);
////                // 设置开始时间与结束时间, 应该根据订单时间来确定
////                source.setStartTime(new Date());
////                source.setEndTime(new Date());
////                int back2 = sysSourceService.updateSysSource(source);
////                if(back2 == 0){
////                    System.out.println("更新资源位信息失败");
////                    flag = false;
////                    break;
////                }
////
////            }
////            else{
////                System.out.println("更新作品信息失败");
////                flag = false;
////                break;
////            }
////        }
////        if(flag){
////            return AjaxResult.success("发布作品成功");
////        }
////        else{
////            return AjaxResult.error("发布作品失败");
////        }
////-------------------------------------old---------------------------------------------------
//
//    }

    // 发布用户作品-------新版
    // 由于APP前端不支持预订时间-----startTime一定是从明天开始
    // 20250313更新---- 订单时间从明天12点开始. 修改LocalDate 为LocalDateTime
    // 20250401更新---- 已通过审核的作品发布时直接通过审核?
    @Transactional
    @PostMapping("/publishUserWorkNew")
    public AjaxResult publishUserWorkNew(@RequestBody List<PublishUserWorkDto> publishUserWorkDtoList)
    {
        // 获取用户id
        Long userId = SecurityUtils.getUserId();

        // 检查用户是否被禁止发布
        SysUser sysUser = sysUserService.selectUserById(userId);
        if(sysUser.getStatus().equals("2")){
            return error("您已被禁止发布");
        }

        // 检查用户是否实名认证
        UserInfo userInfo = userInfoService.selectUserInfoByUserId(userId);
        if(userInfo.getAuthenticationStatus().equals("0")){
            return error("您还未实名认证");
        }

        // 订单总价
        Double tPrice = 0.0;

        // 订单信息缓存
        List<OrderCacheVo> orderCacheVoList = new ArrayList<>();

        LocalDate tomorrow = LocalDate.now().plusDays(1);



        // 获取订单数据
        for(PublishUserWorkDto publishUserWorkDto:publishUserWorkDtoList){

            Long sourceId = publishUserWorkDto.getSourceId();

            System.out.println("发布选中的资源位id: "+ sourceId);
            Long workId = publishUserWorkDto.getWorkId();

            Long day = publishUserWorkDto.getDay();

//            //-----------------------------测试注释内容-------------------------------------
//            // 查看 work 是否属于这个人
//            UserWork userWork = userWorkService.selectUserWorkByWorkId(workId);
//            if(userWork == null || userWork.getUserId() != userId){
//                return error("用户与作品不符, 已记录ip");
//            }
//            //----------------------------测试注释内容---------------------------------------


//            LocalDate startTime = publishUserWorkDto.getStartTime();

            LocalDate startTime = tomorrow;

            if(!startTime.isEqual(tomorrow)){

                LOGGER.error("非法时间, 已记录ip"+ IpUtils.getIpAddr());
                return error("非法时间, 已记录ip");
            }

            // 新的开始时间
            LocalDateTime startTime_t = startTime.atStartOfDay();
            LocalDateTime startTimeNew = startTime_t.plusHours(12);


            LocalDate endTime = startTime;
            LocalDateTime endTimeNew = startTimeNew;

            // 根据资源位查看价格和时间
            SysSource sysSource = sysSourceService.selectSysSourceBySourceId(sourceId);

            // 获取资源位状态, 若只能从明天开始购买, 通过资源位的状态也能判断是否可以购买, 所以后面的时间判断对现在没有必要,
            String sourceStatus = sysSource.getSourceStatus();

            // 资源位状态!=0的位置都不可以购买
            if(!sourceStatus.equals("0")){
                return error("该资源位不能被购买, 请不要输入非法参数");
            }

            // 解析价格数据------这里不知道为什么默认是Double类型的??
            List<Map<String, Double>> list = GsonUtils.fromJson(sysSource.getPrice(), List.class);

            // 价格匹配标志量
            boolean flag = true;

            for(Map<String, Double> map : list){

                Double days = map.get("days");
                if(days==day.doubleValue()){
                    System.out.println("就是这个天: "+ day);
                    flag = false;
                    // 每个订单单价
                    tPrice = map.get("price");
                    // 结束时间
                    endTime = startTime.plusDays(days.intValue());
                    // 新的结束时间
                    endTimeNew = startTimeNew.plusDays(days.intValue());

                    break;
                }
            }
            if(flag){
                return error("输入天数数据错误");
            }

            // 检查时间是否合法, 从订单中查询当前资源位的订单时间, 每个资源位一年最多有 366条数据
            // 要不直接查资源位的起止时间??-------并不能这样做-----一个资源位可以购买多个时间段---一个数据根本存不下.
            // 所以只能通过订单的时间来查询时间是否合法.--这里默认一个订单只有一个时间(即使一个订单对应多个资源位)
            // 后续可能有必要, 现在必要性不大
            int back = sysOrderService.isTimeLegal(startTime, endTime, sourceId);

            // 这里也要检查redis缓存中的时间是否合法 --sourceId + startTime + endTime 这三元组就行.
            if(back > 0){
                return error("购买时间不合法:" + startTime + "至" + endTime);
            }

            //-----------------------------------------方案1通过redis缓存确保订单不会冲突-------------------------------------
            // 缓存中查看订单是否合法
            // 1. 查看缓存中是否存在键值----------键为order_{source_id}, 值为  [startTime, endTime]
            if(redisCache.hasKey("order_"+sourceId)){// 有缓存key

                List<List<String>> value = redisCache.getCacheObject("order_"+sourceId);

                System.out.println("缓存中存在键值: order_"+sourceId+":"+value);

                for(List<String> tList : value){

                    // 字符串型的 日期
                    String sStartTime = tList.get(0);
                    String sEndTime = tList.get(1);

                    // 日期格式化
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                    // 获取起止时间
                    LocalDate tStartTime = LocalDate.parse(sStartTime, formatter);
                    LocalDate tEndTime = LocalDate.parse(sEndTime, formatter);

                    // 判断时间是否合法
                    if(endTime.isAfter(tStartTime) && startTime.isBefore(tEndTime)){
                        return error("购买时间不合法:" + startTime + "至" + endTime);
                    }

                }

                List<String> tList = new ArrayList<>();
                // 20250313修改时间
                tList.add(startTime.toString());
                tList.add(endTime.toString());
                value.add(tList);

                // 写入缓存--更新缓存时间
                redisCache.setCacheObject("order_"+sourceId, value, 5, TimeUnit.MINUTES);

            }
            else{ // 无缓存key, 通过了订单的时间校验就能直接生成订单了, 先写入缓存, 5分钟有效期----订单支付有效期也为5分钟


                // 缓存中默认都是字符串, 使用时需要转换
                List<List<String>> value = new ArrayList<>();
                List<String> tList = new ArrayList<>();
                tList.add(startTime.toString());
                tList.add(endTime.toString());
                value.add(tList);

                // 写入缓存
                redisCache.setCacheObject("order_"+sourceId, value, 5, TimeUnit.MINUTES);

            }

            OrderCacheVo orderCacheVo = new OrderCacheVo();
            orderCacheVo.setEndTime(endTimeNew);
            orderCacheVo.setMoney(tPrice.longValue());
            orderCacheVo.setSourceId(sourceId);
            orderCacheVo.setStartTime(startTimeNew);
            orderCacheVo.setUserId(userId);
            orderCacheVo.setWorkId(workId);
            orderCacheVo.setWay("微信支付");

            orderCacheVoList.add(orderCacheVo);


            //-------------------------------------------------方案1 end----------------------------------------------------------


        }

        //------------------------------------------------------订单相关---------------------------------------------------------

        // 直接在这生成订单就行了
        // 订单号自己生成,用来标识这一次支付.
        // 生成时间戳部分
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timestamp = now.format(formatter);

        // 生成5位随机数（包含前导零）
        Random random = new Random();
        String randomSuffix = String.format("%05d", random.nextInt(100000));

        // 组合订单号
        String mchOrderNo = timestamp + randomSuffix;

//        System.out.println("mchOrderNo: " + mchOrderNo);
//        String mchOrderNo = "M" + UUID.randomUUID().toString().replaceAll("-", "");
//
//        // 缓存订单和用户关系, 为了回调函数中写入订单数据库
//        System.out.println("mchOrderNo: " + mchOrderNo);

        //------------------------------------------------------订单相关----------------------------------------------------------

        // 将订单信息写入缓存--超时时间稍微比订单时间长1分钟吧
        redisCache.setCacheObject(mchOrderNo, orderCacheVoList, 6, TimeUnit.MINUTES);

        System.out.println("总价格："+ tPrice);

        return AjaxResult.success(mchOrderNo);
    }

    // 关闭订单接口.根据订单号删除订单.
    @PostMapping("/closeOrder")
    public AjaxResult closeOrder(@RequestParam("mchOrderNo") String mchOrderNo) {
        System.out.println("关闭订单接口: "+ mchOrderNo);
        if(!redisCache.hasKey(mchOrderNo)){
            return error("订单不存在");
        }

        Long userId = getUserId();

        // 获取缓存中的订单信息
        List<OrderCacheVo> list = redisCache.getCacheObject(mchOrderNo);
//        System.out.println("用户id: "+ userId);
//        System.out.println("订单信息Id: "+ list.get(0).getUserId());
        if(list.size() == 0){
            return error("订单数据错误");
        }
        else if(!Objects.equals(list.get(0).getUserId(), userId)){

            return error("非法操作");
        }

        // 删除缓存中的订单数据
        for(OrderCacheVo orderCacheVo : list){
            // 删除缓存中资源位信息
            redisCache.deleteObject("order_"+orderCacheVo.getSourceId());
        }

        // 删除订单缓存数据
        redisCache.deleteObject(mchOrderNo);

        return success();
    }


    // 获取订单列表
    @GetMapping("/getOrderList")
    public TableDataInfo getOrderList(SysOrder sysOrder) {

        // 查询当前用户的订单
        sysOrder.setUserId(getUserId());


        List<OrderListDto> orderListDtoList = sysOrderService.getOrderListDto(sysOrder);

        // 根据 order_info_id 查看订单所有的资源位
        for(OrderListDto orderListDto: orderListDtoList){

            String orderInfoId = orderListDto.getOrderInfoId();

            List<OrderInfoDto> orderInfoList = orderInfoService.getOrderInfoDtoList(orderInfoId);

            for (OrderInfoDto orderInfoDto: orderInfoList){
                orderInfoDto.setNickName(orderListDto.getNickName());
                orderInfoDto.setPhoneNumber(orderListDto.getPhonenumber());
                orderInfoDto.setSource(orderInfoDto.getCity()+orderInfoDto.getScenic()+orderInfoDto.getPart()+orderInfoDto.getCoordinate());
                orderInfoDto.setAvatar(orderListDto.getAvatar());
                orderInfoDto.setWay(orderListDto.getWay());
                orderInfoDto.setOrderId(orderListDto.getOrderId());
            }


            //------------------------------------------设置订单剩余时间---------------------------------------------------------------------
            LocalDateTime now = orderListDto.getStartTime();
            Duration duration = Duration.between(now, orderListDto.getEndTime());


            // 分解单位（同上）
            long days = duration.toDays();
            long hours = duration.toHours() % 24;
            long minutes = duration.toMinutes() % 60;
            long seconds = duration.getSeconds() % 60;

            String s = "剩余";
            if (days > 0){
                s = s + days + "天";
            }
            if (hours > 0){
                s = s + hours + "小时";
            }
            if (minutes > 0){
                s = s + minutes + "分";
            }
            if  (seconds > 0){
                s = s + seconds + "秒";
            }

            if (s.equals("剩余")){
                s = "订单已结束展示";
            }


            orderListDto.setRemainTimeString(s);
            //----------------------------------------------------------------设置订单剩余时间end--------------------------------------------------------------

            orderListDto.setOrderInfoList(orderInfoList);


        }

        return getDataTable(orderListDtoList);
    }

    // 查看个人作品---所有不是草稿的作品
    @GetMapping("/getUserPublishWorkList")
    public TableDataInfo getUserPublishWorkList() {


        // 获取所有 work_status != "0" 的作品
        startPage();
        List<UserWork> userWorkList = userWorkService.selectUserPublishWorkList(getUserId());
        return getDataTable(userWorkList);

    }

    // 查看个人作品---草稿作品
    @GetMapping("/getUserDraftWorkList")
    public TableDataInfo getUserDraftWorkList() {

        UserWork userWork = new UserWork();

        userWork.setWorkStatus("0");
        userWork.setUserId(getUserId());

        // 获取所有 work_status = "0" 的作品
        startPage();
        List<UserWork> userWorkList = userWorkService.selectUserWorkList(userWork);

        return getDataTable(userWorkList);

    }

    // 查看个人作品详情
    @GetMapping("/getUserWork/{workId}")
    public AjaxResult getUserWork(@PathVariable("workId") Long workId) {

        UserWork userWork = userWorkService.selectUserWorkByWorkId(workId);

        if(!userWork.getUserId().equals(getUserId())){
            return error("非法操作, 请不要查看不是自己的作品");
        }


        return AjaxResult.success(userWork);

    }

    // 编辑作品---对于草稿作品来说草稿就是草稿. 对于已发布作品, 修改完状态可以变为草稿,未发表, 已发表未审核. 审过的也要改成未审核.
    @PutMapping("/editUserWork")
    public AjaxResult editUserWork(@RequestParam("workDto") String userWorkDtoString,
                                   @RequestParam("work") MultipartFile workImage) {

            UserWorkDto userWorkdto = GsonUtils.fromJson(userWorkDtoString, UserWorkDto.class);
            String username = SecurityUtils.getUsername();

            String workName = userWorkdto.getWorkName();
            String workType = userWorkdto.getWorkStatus();
            String workDetail = userWorkdto.getDetail();

            if(workType.equals("3") || workType.equals("4")){
                return error("非法操作");
            }

            Long userId = getUserId();

            // 根据work_id 查询作品.
            UserWork userWork = userWorkService.selectUserWorkByWorkId(userWorkdto.getWorkId());

            if(!userWork.getUserId().equals(userId)){
                return error("非法操作");
            }

            userWork.setWorkName(workName);
            userWork.setWorkStatus(workType);
            userWork.setDetail(workDetail);
            userWork.setCoordinate("0000");


            if (!workImage.isEmpty()) {
                //-----------------------------------------新版文件上传------------------------------------------------------
                String workImageFilePath = "";
                try {
                    // 保存文件到配置的路径
                    workImageFilePath = FileUploadUtils.upload(RuoYiConfig.getProfile()+"/work", workImage);
                    userWork.setWorkAddress(workImageFilePath);

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

                }
                //------------------------------------新版文件上传end-------------------------------------------------------
            }
            boolean flag = userWorkService.updateUserWork(userWork) > 0;
            if(flag){

                return success("编辑作品成功");
            }
            else{
                return error("编辑作品失败");
            }

        //----------------------------------------------------------- 旧版编辑用户作品-------------------------------------------------------------------
//        Long workId = userWork.getWorkId();
//
//        System.out.println(" 保存作品状态: "+ userWork.getWorkStatus());
//
//
//        UserWork userWork1 = userWorkService.selectUserWorkByWorkId(workId);
//
//        // 避免一些非法操作,
//        if(!userWork1.getUserId().equals(getUserId())){
//            return error("非法操作, 请不要编辑不是自己的作品");
//        }
//
//        // 清空审核记录
//        userWork.setAuditOpinion("");
////        userWork.setAuditStatus(userWork.);
//        userWorkService.updateUserWork(userWork);
//
//        // 编辑作品后,这个作品就需要重新审核, 所以有关他的审核记录要删掉
//        WorkReview workReview = new WorkReview();
//        workReview.setWorkId(workId);
//        workReview.setDeleteFlag("1");
//
//        // 根据workId 修改删除flag
//        workReviewService.setWorkReviewDeleteFlag(workReview);
//
//        System.out.println("更新审核数据");
//
//        return success();

        //---------------------------------------------------------旧版编辑用户作品end-------------------------------------------------------------------

    }

    // 我的发布---查看详情--返回资源位位置,剩余天数, 用户头像, 用户id
    @GetMapping("/getUserPublishWorkDetail/{workId}")
    public AjaxResult getUserPublishWorkDetail(@PathVariable("workId") Long workId) {

        UserPublishWorkDetailDto userPublishWorkDetail = userWorkService.getUserPublishWorkDetail(workId);

        //----------------------------------查看该作品所属的资源位----------------------------------------------
        List<UserPublishWorkSourceListDto> sourceList = sysSourceService.getUserPublishWorkSourceList(workId);

        for(UserPublishWorkSourceListDto userPublishWorkSourceListDto: sourceList){
            userPublishWorkSourceListDto.setSource(userPublishWorkSourceListDto.getCity()+userPublishWorkSourceListDto.getScenic()+userPublishWorkSourceListDto.getPart()+userPublishWorkSourceListDto.getCoordinate());

            //--------------------------------------测试时直接注释掉-------------------------------------------------
            LocalDate now = LocalDate.now();
            long daysBetween = ChronoUnit.DAYS.between(now, userPublishWorkSourceListDto.getEndTime());
            userPublishWorkSourceListDto.setrDays(Math.max(daysBetween, 0L));
            //--------------------------------------测试时直接注释掉end-----------------------------------------------
//            userPublishWorkSourceListDto.setrDays(0L);
        }
        //-----------------------------------查看该作品所属资源位end---------------------------------------------

        //----------------------------------查看是否点赞该作品--------------------------------------------------
        SysUserLike sysUserLike = new SysUserLike();
        sysUserLike.setUserId(getUserId());
        sysUserLike.setTargetId(userPublishWorkDetail.getWorkId());
        sysUserLike.setTargetType("1");
        sysUserLike.setStatus("0");
        List<SysUserLike> sysUserLikeList = sysUserLikeService.selectSysUserLikeList(sysUserLike);
        if(sysUserLikeList.size() > 0){
            // 已点赞
            userPublishWorkDetail.setIsAddLike("1");
        }else{
            userPublishWorkDetail.setIsAddLike("0");
        }
        //----------------------------------查看是否点赞该作品end-----------------------------------------------

        //----------------------------------查看是否关注该用户-----------------------------------------------
        SysUserFollow userFollow = new SysUserFollow();
        userFollow.setUserId(getUserId());
        userFollow.setFollowedUserId(userPublishWorkDetail.getUserId());
        userFollow.setStatus("0");
        List<SysUserFollow> userFollowList = userFollowService.selectSysUserFollowList(userFollow);
        if(userFollowList.size() > 0){
            // 以关注
            userPublishWorkDetail.setIsFollow("1");
        }else{
            userPublishWorkDetail.setIsFollow("0");
        }
        //----------------------------------查看是否关注该用户end-----------------------------------------------





        userPublishWorkDetail.setSourceList(sourceList);

        return success(userPublishWorkDetail);

    }

    //我的--实名认证--返回实名认证信息
    @GetMapping("/getUserAuthenticationInfo")
    public AjaxResult getUserAuthenticationInfo() {

        UserAuthenticationInfoDto userAuthenticationInfo = userInfoService.getUserAuthenticationInfo(getUserId());

        return success(userAuthenticationInfo);

    }

    // 根据作品id删除用户作品
    @DeleteMapping("/deleteUserWork/{workId}")
    public AjaxResult deleteUserWork(@PathVariable("workId") Long workId) {

        UserWork userWork = userWorkService.selectUserWorkByWorkId(workId);

        System.out.println("getUserId: "+getUserId());
        System.out.println("userWork.getUserId(): "+userWork.getUserId());

        if(!userWork.getUserId().equals(getUserId())){
            return error("非法操作, 请不要删除不是自己的作品");
        }

        // 删除作品
        userWorkService.deleteUserWorkByWorkId(workId);

        // 删除作品对应的审核记录
        WorkReview workReview = new WorkReview();
        workReview.setWorkId(workId);
        workReview.setDeleteFlag("1");

        // 根据workId 修改删除flag
        workReviewService.setWorkReviewDeleteFlag(workReview);

        return success();
    }

    // 我的--查看自己发布的作品
    @GetMapping("/getUserPublishWork")
    public AjaxResult getUserPublishWork() {

        Long userId = getUserId();

        List<GetUserPublishWorkDto> userPublishWorkDtoList = userWorkService.getUserPublishWork(userId);
        for(GetUserPublishWorkDto getUserPublishWorkDto: userPublishWorkDtoList){
            SysUserLike sysUserLike = new SysUserLike();
            sysUserLike.setUserId(userId);
            sysUserLike.setTargetId(getUserPublishWorkDto.getWorkId());
            sysUserLike.setTargetType("1");
            sysUserLike.setStatus("0");
            List<SysUserLike> sysUserLikeList = sysUserLikeService.selectSysUserLikeList(sysUserLike);
            if(sysUserLikeList.size() > 0){
                // 已点赞
                getUserPublishWorkDto.setIsAddLike("1");
            }else{
                getUserPublishWorkDto.setIsAddLike("0");
            }
        }



        return success(userPublishWorkDtoList);




//        //---------------------------------------------旧版-----------------------------------------------------------
//
//        // 所有审核通过的作品
//        UserWork userWork = new UserWork();
//        userWork.setWorkStatus("3");
//        userWork.setUserId(getUserId());
//        List<UserWork> userWorkList = userWorkService.selectUserWorkList(userWork);
//
//        // 查看自己作品自己是否点赞过
//        for(UserWork userWork1: userWorkList){
//            //----------------------------------查看是否点赞该作品--------------------------------------------------
//            SysUserLike sysUserLike = new SysUserLike();
//            sysUserLike.setUserId(getUserId());
//            sysUserLike.setTargetId(userWork1.getWorkId());
//            sysUserLike.setTargetType("1");
//            sysUserLike.setStatus("0");
//            List<SysUserLike> sysUserLikeList = sysUserLikeService.selectSysUserLikeList(sysUserLike);
//            if(sysUserLikeList.size() > 0){
//                // 已点赞
//                userWork1.setIsAddLike("1");
//            }else{
//                userWork1.setIsAddLike("0");
//            }
//            //----------------------------------查看是否点赞该作品end-----------------------------------------------
//        }
//
//        return AjaxResult.success(userWorkList);
//
//        //------------------------------------------------------旧版end-------------------------------------------------------

    }




    // 发布--获取系统资源位列表, 附带搜索功能
    @PostMapping("/getAllSource")
    public AjaxResult getAllSource(@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();


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

            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);
        ajaxResult.put("preview", preview);

        return ajaxResult;

    }

    //发布--根据sourceId获取价格信息
    @GetMapping("/getPriceList/{sourceId}")
    public AjaxResult getPriceList(@PathVariable("sourceId") Long sourceId) {

        SysSource sysSource = sysSourceService.selectSysSourceBySourceId(sourceId);

        // 解析价格数据
        List<Map<String, SetSourcePriceDto>> priceList = GsonUtils.fromJson(sysSource.getPrice(), List.class);

        return AjaxResult.success(priceList);

    }


    // 我的--查看我关注了那些人
    @GetMapping("/getFollowerList")
    public TableDataInfo getFollowerList() {

        Long userId = getUserId();

        startPage();
        List<FollowerListDto> followerList = userFollowService.getFollowerList(userId);
        return getDataTable(followerList);


    }

    // 我的--粉丝--查看那些人关注了我
    @GetMapping("/getFollowedList")
    public TableDataInfo getFollowedList() {

        Long userId = getUserId();

        startPage();
        List<FollowerListDto> followedList = userFollowService.getFollowedList(userId);
        return getDataTable(followedList);

    }

    // 我的--关注--取消关注
    @Transactional
    @GetMapping("/deleteFollower/{followedUserId}")
    public AjaxResult deleteFollower(@PathVariable("followedUserId") Long followedUserId)
    {

        Long userId = getUserId();
        System.out.println("userId: "+userId+" followedUserId: "+followedUserId);


        // 删除关注数据
        userFollowService.deleteSysUserFollowByUserIdAndFollowedUserId(userId, followedUserId);

        //--------------------------------- 修改互关状态---------------------------------------------
        SysUserFollow sysUserFollow = new SysUserFollow();
        sysUserFollow.setUserId(followedUserId);
        sysUserFollow.setFollowedUserId(userId);
        List<SysUserFollow> userFollowList = userFollowService.selectSysUserFollowList(sysUserFollow);
        // 如果有结果说明他们以前互关
        if(userFollowList.size() > 0){
            SysUserFollow sysUserFollow1 = userFollowList.get(0);
            sysUserFollow1.setFollowStatus("0");
            userFollowService.updateSysUserFollow(sysUserFollow1);
        }
        //----------------------------------修改互关状态end------------------------------------------

        // user_info 中本人 followings -1
        UserInfo userInfo = userInfoService.selectUserInfoByUserId(userId);
        userInfo.setFollowings(userInfo.getFollowings()-1);
        userInfoService.updateUserInfo(userInfo);

        // 被关注者 user_info 中被关注者 followers -1
        UserInfo userInfo1 = userInfoService.selectUserInfoByUserId(followedUserId);
        userInfo1.setFollowers(userInfo1.getFollowers()-1);
        userInfoService.updateUserInfo(userInfo1);

        // 删除消息通知
        userNotificationService.deleteSysUserNotificationBySenderIdAndUserId(userId, followedUserId, "1");

        return success("取消关注成功");

    }



    // 新增关注
    @GetMapping("/addFollower/{followedUserId}")
    @Transactional
    public AjaxResult addFollower(@PathVariable("followedUserId") Long followedUserId)
    {
        Long userId = SecurityUtils.getUserId();

        SysUserFollow sysUserFollow = new SysUserFollow();

        sysUserFollow.setUserId(userId);
        sysUserFollow.setFollowedUserId(followedUserId);

        List<SysUserFollow> userFollowList = userFollowService.selectSysUserFollowList(sysUserFollow);
        if(userFollowList != null && userFollowList.size() > 0 && userFollowList.get(0).getStatus().equals("0")){
            return AjaxResult.error("已关注");
        }
        else{

            // 查看是否互关
            SysUserFollow sysUserFollow1 = new SysUserFollow();

            sysUserFollow1.setUserId(followedUserId);
            sysUserFollow1.setFollowedUserId(userId);
            List<SysUserFollow> userFollowList1 = userFollowService.selectSysUserFollowList(sysUserFollow1);

//            System.out.println("userFollowList1: "+userFollowList1.size());
//            SysUserFollow userFollow = userFollowList1.get(0);
//            System.out.println("userFollow: "+userFollow + "status"+ userFollow.getFollowStatus());

            if(userFollowList1.size() > 0 && userFollowList1.get(0).getFollowStatus().equals("0")){
                // 互相关注
                sysUserFollow.setFollowStatus("1");

                // 他的follow_status也要成1 变成互相关注
                SysUserFollow userFollow1 = userFollowList1.get(0);
                userFollow1.setFollowStatus("1");
                // 更新关注状态
                userFollowService.updateSysUserFollow(userFollow1);


            }


            // 修改状态实现关注
            if(userFollowList != null && userFollowList.size() > 0 && userFollowList.get(0).getStatus().equals("1")){
                sysUserFollow = userFollowList.get(0);
                sysUserFollow.setStatus("0");
                // 直接更新数据就行
                userFollowService.updateSysUserFollow(sysUserFollow);

            }
            else{
                // 新增关注
                int back = userFollowService.insertSysUserFollow(sysUserFollow);
                if(back == 0){
                    return AjaxResult.error("新增关注失败");
                }
            }



//            String userName = sysUserService.selectUserById(userId).getNickName();

            //发送消息通知
            SysUserNotification sysUserNotification = new SysUserNotification();
            sysUserNotification.setUserId(followedUserId);
            sysUserNotification.setSenderId(userId);
            sysUserNotification.setDetail("关注了你");

            // 关注信息
            sysUserNotification.setType("1");
            sysUserNotification.setStatus("0");

            // 发送消息
            int back1 = userNotificationService.insertSysUserNotification(sysUserNotification);
            if(back1 == 0){
                return AjaxResult.error("新增关注消息失败");
            }

            // user_info中更新关注数
            UserInfo userInfo = userInfoService.selectUserInfoByUserId(userId);
            userInfo.setFollowings(userInfo.getFollowings() + 1);
            userInfoService.updateUserInfo(userInfo);

            // user_info 中 被关注者被关注人数加1
            UserInfo userInfo1 = userInfoService.selectUserInfoByUserId(followedUserId);
            userInfo1.setFollowers(userInfo1.getFollowers() + 1);
            userInfoService.updateUserInfo(userInfo1);

            return AjaxResult.success("新增关注成功");


        }


    }

    // 消息--查看新增关注数
    @GetMapping("/addFollowerCount")
    public AjaxResult addFollowerCount()
    {
        Long userId = getUserId();

        Long count = userNotificationService.getAddFollowerCount(userId);

        return success(count);

    }
    // 消息--获取新增关注列表
    @GetMapping("/addFollowerList")
    public TableDataInfo addFollowerList()
    {
        Long userId = getUserId();
        startPage();
        List<FollowerListDto> addFollowerList = userFollowService.getAddFollowerList(userId);


        //------------------------------------消息已读-------------------------------------------
//        // 把消息置为已读
//        SysUserNotification sysUserNotification = new SysUserNotification();
//
//        sysUserNotification.setUserId(userId);
//        // 消息类型为新增关注
//        sysUserNotification.setType("1");
//        // 改变状态为已读
//        sysUserNotification.setStatus("1");

        // 更新数据库
        userNotificationService.readNotifiaction(userId, "1", "1");

        //-------------------------------------消息已读end-----------------------------------------

        return getDataTable(addFollowerList);

    }

//    // 测试 warning返回码
//    @GetMapping("/warning")
//    public AjaxResult warning()
//    {
//        return AjaxResult.warn("警告");
//    }

    // 消息-- 查看系统消息列表(系统审核消息,退款消息)
    @GetMapping("/systemMessage")
    public TableDataInfo systemMessage()
    {
        startPage();
        List<SysNotificationDto> sysNotificationDtoList = userNotificationService.getSystemMessage(getUserId());

        System.out.println("sysNotificationDtoList : "+sysNotificationDtoList.size());

        return getDataTable(sysNotificationDtoList);
    }

    //消息--根据消息id查看消息详情
    @GetMapping("/getSystemMessageDetail/{id}")
    public AjaxResult getSystemMessageDetail(@PathVariable("id") Long id)
    {
        SysUserNotification sysUserNotification = userNotificationService.selectSysUserNotificationById(id);

        Long userId = getUserId();

        if(!sysUserNotification.getUserId().equals(userId)){
            return error("请不要查看不是自己的消息");
        }

        // 改变状态为已读
        sysUserNotification.setStatus("1");

        // 更新数据库
        userNotificationService.updateSysUserNotification(sysUserNotification);
        return success(sysUserNotification);
    }

    //消息--查看新增喜爱数
    @GetMapping("/addLikeCount")
    public AjaxResult addLikeCount()
    {
        Long userId = getUserId();

        Long count = userNotificationService.getAddLikeCount(userId);
        System.out.println("count : "+count);
        return success(count);

    }

    //消息--获取点赞列表
    @Transactional
    @GetMapping("/getWorkLikeList")
    public TableDataInfo getWorkLikeList()
    {
        Long userId = getUserId();

        // 点了之后所有的点赞信息应该已读
        userNotificationService.readNotifiaction(userId, "2", "1");

        startPage();
        // 先从系统通知中获取
        List<WorkLikeDto> addLikeList = userNotificationService.getWorkLikeList(userId);
        for(WorkLikeDto workLikeDto : addLikeList){
            if (workLikeDto.getWorkName() == null){
                workLikeDto.setWorkName("已删除的作品");
            }
        }
        return getDataTable(addLikeList);

    }

    // 更多--新增点赞信息
    @GetMapping("/addLike/{workId}")
    @Transactional
    public AjaxResult addLike(@PathVariable("workId") Long workId)
    {
        // 避免未登录点赞
        Long userId = null;
        try{
            userId = getUserId();
        }
        catch (Exception e){
            return error("请先登录");
        }

        // 不支持重复点赞

        // 新增点赞记录
        SysUserLike sysUserLike = new SysUserLike();
        sysUserLike.setUserId(userId);
        sysUserLike.setTargetId(workId);
        // 点赞发布作品
        sysUserLike.setTargetType("1");


        List<SysUserLike> sysUserLikeList = sysUserLikeService.selectSysUserLikeList(sysUserLike);
        if(sysUserLikeList != null && sysUserLikeList.size() > 0 && sysUserLikeList.get(0).getStatus().equals("0")){
            return error("请不要重复点赞");
        }

        // 已有点赞数据,但取消点赞了
        if(sysUserLikeList != null && sysUserLikeList.size() > 0){
            System.out.println("sysUserLikeList : "+sysUserLikeList.size());
            sysUserLike = sysUserLikeList.get(0);
            sysUserLike.setStatus("0");
            sysUserLikeService.updateSysUserLike(sysUserLike);
        }
        else{
            sysUserLikeService.insertSysUserLike(sysUserLike);
        }




        // 作品点赞数加1
        UserWork userWork = userWorkService.selectUserWorkByWorkId(workId);
        userWork.setReceiveRockets(userWork.getReceiveRockets() + 1);
        userWorkService.updateUserWork(userWork);

        // 用户信息中点赞数(收到火箭数)加1
        UserInfo userInfo = userInfoService.selectUserInfoByUserId(userId);
        userInfo.setSendRockets(userInfo.getSendRockets() + 1);
        userInfoService.updateUserInfo(userInfo);

        // 用户信息中被点赞数(收到火箭数)加1
        UserInfo userInfo2 = userInfoService.selectUserInfoByUserId(userWork.getUserId());
        userInfo2.setReceiveRockets(userInfo2.getReceiveRockets() + 1);
        userInfoService.updateUserInfo(userInfo2);



        // 发送点赞消息, 自己给自己点赞就不发消息了
        if(!userId.equals(userWork.getUserId())){

            SysUserNotification sysUserNotification = new SysUserNotification();
            sysUserNotification.setSenderId(userId);
            sysUserNotification.setUserId(userWork.getUserId());
            sysUserNotification.setType("2");
            sysUserNotification.setStatus("0");
            sysUserNotification.setTargetId(workId);
            sysUserNotification.setDetail("点赞了你的作品");
            userNotificationService.insertSysUserNotification(sysUserNotification);
        }


        if(userWork.getSourceId()!= null){

            // 每日资源位互动次数加1
            DailySource dailySource = dailySourceService.getDailySourceBySourceIdAndDate(userWork.getSourceId(), LocalDate.now());
            if (dailySource != null){
                dailySource.setInteractions(dailySource.getInteractions()+1);
                dailySourceService.updateDailySource(dailySource);
            }
            else{
                dailySource = new DailySource();
                dailySource.setSourceId(userWork.getSourceId());
                dailySource.setDate(LocalDate.now());
                dailySource.setInteractions(1L);
                dailySourceService.insertDailySource(dailySource);

            }
        }


        return success("点赞成功");

    }

    // 更多--查看更多别人发布的作品
    @GetMapping("/getMoreUserWork")
    public TableDataInfo getMoreUserWork()
    {

        startPage();
        List<UserPublishWorkDetailDto> userWorkList = userWorkService.getUserPublishWorkList();
        for(UserPublishWorkDetailDto userPublishWorkDetail:userWorkList){
            //----------------------------------查看是否点赞该作品--------------------------------------------------
            SysUserLike sysUserLike = new SysUserLike();
            try{
                sysUserLike.setUserId(getUserId());
                sysUserLike.setTargetId(userPublishWorkDetail.getWorkId());
                sysUserLike.setTargetType("1");
                sysUserLike.setStatus("0");
                List<SysUserLike> sysUserLikeList = sysUserLikeService.selectSysUserLikeList(sysUserLike);
                if(sysUserLikeList.size() > 0){
                    // 已点赞
                    userPublishWorkDetail.setIsAddLike("1");
                }else{
                    userPublishWorkDetail.setIsAddLike("0");
                }
            }
            catch (Exception e){
                // 未登录
                userPublishWorkDetail.setIsAddLike("0");
//                continue;
            }

            //----------------------------------查看是否点赞该作品end-----------------------------------------------



            //----------------------------------查看是否关注该用户-----------------------------------------------
            SysUserFollow userFollow = new SysUserFollow();
            // 这里允许匿名访问
            try{
                userFollow.setUserId(getUserId());
                userFollow.setFollowedUserId(userPublishWorkDetail.getUserId());
                userFollow.setStatus("0");
                List<SysUserFollow> userFollowList = userFollowService.selectSysUserFollowList(userFollow);


                if(userFollowList.size() > 0){
                    // 以关注
                    userPublishWorkDetail.setIsFollow("1");
                }else{
                    userPublishWorkDetail.setIsFollow("0");
                }
            }catch (Exception e)
            {
                // 未登录
                userPublishWorkDetail.setIsFollow("0");
            }

            //----------------------------------查看是否关注该用户end-----------------------------------------------
        }
        return getDataTable(userWorkList);
    }

    // 取消点赞
    @Transactional
    @GetMapping("/cancelLike/{workId}")
    public AjaxResult cancelLike(@PathVariable("workId") Long workId)
    {
        Long userId = getUserId();
        System.out.println("userId : "+userId);
        //
        SysUserLike sysUserLike = new SysUserLike();
        sysUserLike.setUserId(userId);
        sysUserLike.setTargetId(workId);
        // 点赞发布作品
        sysUserLike.setTargetType("1");
//        sysUserLike.setStatus("0");

        List<SysUserLike> sysUserLikeList = sysUserLikeService.selectSysUserLikeList(sysUserLike);
        if(sysUserLikeList==null || sysUserLikeList.get(0).getStatus().equals("1")){
            return error("请不要取消自己没点赞过的作品的赞");
        }
        sysUserLike = sysUserLikeList.get(0);
        // 取消点赞
        sysUserLike.setStatus("1");

        System.out.println("sysUserLike id : "+sysUserLike.getId());

        sysUserLikeService.updateSysUserLike(sysUserLike);

        // 作品点赞数减1
        UserWork userWork = userWorkService.selectUserWorkByWorkId(workId);
        userWork.setReceiveRockets(userWork.getReceiveRockets() - 1);
        userWorkService.updateUserWork(userWork);

        // 原先收到点赞的哪个人收到点赞数(收到火箭数)减1
        UserInfo userInfo = userInfoService.selectUserInfoByUserId(userWork.getUserId());
        userInfo.setReceiveRockets(userInfo.getReceiveRockets() - 1);
        userInfoService.updateUserInfo(userInfo);

        // 本人发送赞数(发送火箭数)减1
        UserInfo userInfo2 = userInfoService.selectUserInfoByUserId(userId);
        userInfo2.setSendRockets(userInfo2.getSendRockets() - 1);
        userInfoService.updateUserInfo(userInfo2);

        // 删除点赞消息通知
        userNotificationService.deleteSysUserNotificationBySenderIdAndUserId(userId, userWork.getUserId(), "2");


        return success("取消点赞成功");
    }

    // 更多--查看发布作品详情
    @GetMapping("/getMoreUserPublishWorkDetail/{workId}")
    public AjaxResult getMoreUserPublishWorkDetail(@PathVariable("workId") Long workId)
    {
        UserPublishWorkDetailDto userPublishWorkDetail = userWorkService.getUserPublishWorkDetail(workId);
        //----------------------------------查看该作品所属的资源位----------------------------------------------
        List<UserPublishWorkSourceListDto> sourceList = sysSourceService.getUserPublishWorkSourceList(workId);

        for(UserPublishWorkSourceListDto userPublishWorkSourceListDto: sourceList){
            userPublishWorkSourceListDto.setSource(userPublishWorkSourceListDto.getCity()+userPublishWorkSourceListDto.getScenic()+userPublishWorkSourceListDto.getPart()+userPublishWorkSourceListDto.getCoordinate());

//            ------------------------- 测试版本先注释掉--------------------------------------
            LocalDate now = LocalDate.now();
            long daysBetween = ChronoUnit.DAYS.between(now, userPublishWorkSourceListDto.getEndTime());
            userPublishWorkSourceListDto.setrDays(daysBetween);
//            ---------------------------测试版本先注释掉end----------------------------------
//            userPublishWorkSourceListDto.setrDays(0L);
        }
        //-----------------------------------查看该作品所属资源位end---------------------------------------------

        //----------------------------------查看是否关注该用户-----------------------------------------------
        SysUserFollow userFollow = new SysUserFollow();
        // 这里允许匿名访问
        try{
            userFollow.setUserId(getUserId());
            userFollow.setFollowedUserId(userPublishWorkDetail.getUserId());
            userFollow.setStatus("0");
            List<SysUserFollow> userFollowList = userFollowService.selectSysUserFollowList(userFollow);


            if(userFollowList.size() > 0){
                // 以关注
                userPublishWorkDetail.setIsFollow("1");
            }else{
                userPublishWorkDetail.setIsFollow("0");
            }
        }catch (Exception e)
            {
                // 未登录
                userPublishWorkDetail.setIsFollow("0");
            }

        //----------------------------------查看是否关注该用户end-----------------------------------------------

        //----------------------------------查看是否点赞该作品--------------------------------------------------
        try{
            SysUserLike sysUserLike = new SysUserLike();
            sysUserLike.setUserId(getUserId());
            sysUserLike.setTargetId(workId);
            sysUserLike.setTargetType("1");
            sysUserLike.setStatus("0");
            List<SysUserLike> sysUserLikeList = sysUserLikeService.selectSysUserLikeList(sysUserLike);
            if(sysUserLikeList.size() > 0){
                // 已点赞
                userPublishWorkDetail.setIsAddLike("1");
            }else{
                userPublishWorkDetail.setIsAddLike("0");
            }
        }
        catch (Exception e){
            // 未登录
            userPublishWorkDetail.setIsAddLike("0");
        }

        //----------------------------------查看是否点赞该作品end-----------------------------------------------

        userPublishWorkDetail.setSourceList(sourceList);
        return success(userPublishWorkDetail);
    }

    // 更多--查看他的详情
    @GetMapping("/getMoreUserDetail/{userId}")
    public AjaxResult getMoreUserDetail(@PathVariable("userId") Long userId)
    {
        MoreUserDetailDto  moreUserDetailDto = sysUserService.getMoreUserDetail(userId);
        moreUserDetailDto.setUserId(userId);

        //----------------------------------查看是否关注该用户-----------------------------------------------
        try{
            SysUserFollow userFollow = new SysUserFollow();
            userFollow.setUserId(getUserId());
            userFollow.setFollowedUserId(userId);
            userFollow.setStatus("0");
            List<SysUserFollow> userFollowList = userFollowService.selectSysUserFollowList(userFollow);
            if(userFollowList.size() > 0){
                // 已关注
                moreUserDetailDto.setIsFollow("1");
            }else{
                moreUserDetailDto.setIsFollow("0");
            }
        }
        catch (Exception e){
            // 未登录
            moreUserDetailDto.setIsFollow("0");
        }

        //----------------------------------查看是否关注该用户end-----------------------------------------------

//        // 查看他人发布作品
//        moreUserDetailDto.setUserWorkList(userWorkService.getUserPublishWorkMore(userId));

        return success(moreUserDetailDto);
    }

    // 更多--查看他人发布作品
    @GetMapping("/getMoreUserPublishWork/{userId}")
    public TableDataInfo getMoreUserPublishWork(@PathVariable("userId") Long userId)
    {
        startPage();
        List<UserPublishWorkMoreDto> userPublishWorkMoreDtoList = userWorkService.getUserPublishWorkMore(userId);
        return getDataTable(userPublishWorkMoreDtoList);
    }


    @GetMapping("/getMessage")
    public AjaxResult getMessage()
    {
        UserMessageVo userMessageVo = userNotificationService.getUserMessages(SecurityUtils.getUserId());
        return AjaxResult.success(userMessageVo);
    }

    // 设置--注销账号--完全删除
    @Transactional
    @GetMapping("/deleteUserAccount")
    public AjaxResult deleteUserAccount()
    {
        Long userId = getUserId();
        if(sysUserService.deleteUserById(userId) > 0){


            // 对所有本账号关注的和关注本账号的数据, 删除 sys_user_follow中的数据
            // 现不删除其点赞数据.
            userFollowService.deleteSysUserFollowUserId(userId);

            // 清理系统通知 sys_user_notification 表中的数据, sender_id = user_id的数据
            userNotificationService.deleteSysUserNotificationBySenderId(userId);

            // 清理缓存中的用户登录token
            LoginUser loginUser = SecurityUtils.getLoginUser();
            String uuid = loginUser.getToken();
            if (StringUtils.isNotEmpty(uuid)){
                tokenService.delLoginUser(uuid);
            }

            return success();
        }else{
            return error();
        }
    }

    // 检查版本更新
    @GetMapping("/checkVersion/{version}")
    public AjaxResult checkVersion(@PathVariable("version") String version1)
    {
        AppVersion appVersion = appVersionService.getLatestVersion();
        String version2 = appVersion.getVersion();
        if(!version1.equals(version2)){
            return success(appVersion);
        }else{
            return success(new AppVersion());
        }
    }

    // 支付回调后返回订单信息
    @GetMapping("/getSystemOrder/{orderId}")
    public AjaxResult getSystemOrder(@PathVariable("orderId") Long orderId)
    {
        Long userId = getUserId();
        SysOrderPayBackDto sysOrderPayBackDto = sysOrderService.getSysOrderPayBackDto(orderId);

        if(sysOrderPayBackDto != null){

            if(!sysOrderPayBackDto.getUserId().equals(userId)){
                return error("请不要查看不是自己的订单");
            }

            List<SourceCoordinateDto> sourceList = sysSourceService.getSourceCoordinateByOrderId(orderId);
            String arLocation = "";
            for(SourceCoordinateDto sourceCoordinateDto : sourceList){
                arLocation = arLocation + sourceCoordinateDto.getPart() + String.format("%02d", sourceCoordinateDto.getcX())+String.format("%02d", sourceCoordinateDto.getcY())+" ";
            }

            sysOrderPayBackDto.setPayTime(sysOrderPayBackDto.getCreateTime());

            sysOrderPayBackDto.setArLocation(arLocation);

            return success(sysOrderPayBackDto);
        }
        return error("获取订单详情失败");
    }

    private void appvalidateCaptcha(String username, String code, String phone) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + phone;
            String captcha = redisCache.getCacheObject(verifyKey);

            // 尝试次数
            String countKey = CacheConstants.CAPTCHA_CODE_KEY_COUNT + phone;
            int captchaCount = redisCache.getCacheObject(countKey);

            if (captcha == null ) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaDisableException();
            }

            if(captchaCount >= 3){
                // 删除缓存
                redisCache.deleteObject(verifyKey);
                redisCache.deleteObject(countKey);

                // 验证码失效
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaDisableException();
            }


            if (!code.equalsIgnoreCase(captcha))
            {
                // 尝试次数加1
                redisCache.setCacheObject(countKey, captchaCount + 1);
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
            else{
                // 登录成功删除验证码
                redisCache.deleteObject(verifyKey);
            }
        }

    }

    private void appvalidateCaptchaJuhe(String username, String code, String phone) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + phone;
            String captcha = redisCache.getCacheObject(verifyKey);

            // 尝试次数
            String countKey = CacheConstants.CAPTCHA_CODE_KEY_COUNT + phone;
            int captchaCount = redisCache.getCacheObject(countKey);

            if (captcha == null ) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaDisableException();
            }

            if(captchaCount >= 3){
                // 删除缓存
                redisCache.deleteObject(verifyKey);
                redisCache.deleteObject(countKey);

                // 验证码失效
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaDisableException();
            }


            if (!code.equalsIgnoreCase(captcha))
            {

                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
            // 尝试次数加1
            redisCache.setCacheObject(countKey, captchaCount + 1);
//            else{
//                // 登录成功删除验证码
//                redisCache.deleteObject(verifyKey);
//                redisCache.deleteObject(countKey);
//            }
        }

    }




}
