package com.example.sjkbf.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.file.FileWriter;
import cn.hutool.log.StaticLog;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.sjkbf.common.FileManage;
import com.example.sjkbf.controller.verifyController;
import com.example.sjkbf.entity.DTO.LoginRequest;
import com.example.sjkbf.entity.Log;
import com.example.sjkbf.entity.ProjectPer;
import com.example.sjkbf.entity.User;
import com.example.sjkbf.entity.UserAndServer;
import com.example.sjkbf.entity.projectconfig.Project;
import com.example.sjkbf.mapper.UserMapper;
import com.example.sjkbf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bozhiqiang
 * @since 2025-04-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService  {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private ProjectPerService projectPerService;


    @Autowired
    private UserAndServerService userAndServerService;

    @Autowired
    private UserServerProjectService userServerProjectService;


    @Autowired
    private LogService logService;

    @Autowired
    FileManage fileManage;
    // 检查用户名是否存在
    public boolean isUsernameExist(String username) {
        return userMapper.selectCount(new QueryWrapper<User>().eq("username", username)) > 0;
    }


    // 注册用户
    public void registerUser(LoginRequest request) {
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword())); // 密码加密
        user.setQq(request.getQq());
        user.setGold(0);
        user.setName(generateRandomString());
        save(user);
    }
    public static String generateRandomString() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 8; i++) {
            int index = random.nextInt(characters.length());
            sb.append(characters.charAt(index));
        }
        return sb.toString();
    }




    @Override
    @Transactional//开启事务 保证同时成功或者失败
    public String buy(String ip, String projectName, String userName) {
        //获得插件项目信息
        Project byName = projectPerService.getByName(projectName);
        if (byName==null)return "查询不到该插件项目";
        if (userAndServerService.selectCount(ip, userName)==0){
            return "账号下不存在此服务器";
        }


        User username = getOne(new QueryWrapper<User>().eq("username", userName));

        int demandGold = projectPerService.getProjectPrice(projectName);
        if (demandGold>0) {
            StaticLog.info("用户："+userName+"购买项目："+projectName+" IP："+userName);
            //扣减金币
            if (username.getGold() < demandGold){
                StaticLog.info("用户："+userName+"购买项目："+projectName+" IP："+userName+"积分不足");
                return "积分不足";
            }
            username.setGold(username.getGold() - demandGold);
            updateById(username);

            verifyController.ipAndMac.remove(  ip);
        }
        // 这里还要对服务器脚本数据库进行添加
        userServerProjectService.addpro(ip, projectName, 31, userName);

        try {
            FileWriter writer = new FileWriter("/root/java/"+"log.txt");
            String now = DateUtil.now();
            writer.append(now + "用户："+userName+"购买项目："+projectName+" IP："+userName  +"购买完成");

            Log log1 = new Log();
            log1.setName(userName);
            log1.setLog("购买项目："+projectName+" IP："+ip  +"购买完成,花费积分"+ demandGold);

            if (demandGold>0){
                log1.setType(3);
            }else {
                log1.setType(2);
            }

            log1.setTime(DateUtil.date());
            logService.save(log1);
        }catch (Exception e){
            StaticLog.info("用户："+userName+"购买项目："+projectName+" IP："+userName+"写入日志失败");
            e.printStackTrace();
        }



        return "购买成功";
    }

    @Override
    public void updatePassword(LoginRequest request) {
        String username = request.getUsername();
        User username1 = getOne(new QueryWrapper<User>().eq("username", username));

        if (username1!=null && Objects.equals(request.getQq(), username1.getQq())){
            username1.setPassword(passwordEncoder.encode(request.getPassword()));
            updateById(username1);
        }else {
            throw new RuntimeException("验证信息错误");
        }
    }

    @Override
    public String addServer(String ip, String userName, String account, String password, String port) {
//        if (userAndServerService.selectCount(ip, userName)>0){
//            return "该服务器已存在，请不要重复添加";
//        }

        UserAndServer one = userAndServerService.getOne(new QueryWrapper<UserAndServer>().eq("server_ip", ip).eq("user_name", userName));
        if (one!=null){
            one.setAccount(account);
            one.setPassword(password);
            one.setPort(port);

            userAndServerService.update(one, new QueryWrapper<UserAndServer>().eq("server_ip", ip).eq("user_name", userName));

        }else {
            UserAndServer userAndServer = new UserAndServer();
            userAndServer.setUserName(userName);
            userAndServer.setServerIp(ip);
            userAndServer.setAccount(account);
            userAndServer.setPassword(password);
            userAndServer.setPort(port);
            userAndServerService.save(userAndServer);
        }

        return "添加成功";
    }

    @Override
    public String deleteServer(String ip, String userName) {
        if (userAndServerService.selectCount(ip, userName)>0){
            userAndServerService.remove(new QueryWrapper<UserAndServer>().eq("server_ip", ip).eq("user_name", userName));
            return "删除成功";
        }
        return "删除失败";
    }

    @Override
    public String setKey(String userName, String clientkey, String serverkey) {
        User username = getOne(new QueryWrapper<User>().eq("username", userName));
        if (username!=null){
            if (clientkey!=null) {
                username.setClientKey(clientkey);
            }
            if (serverkey!=null) {
                username.setServerKey(serverkey);
            }
            updateById(username);
            return "设置成功";
        }


        return "设置 请重新登录后再试";
    }

    @Override
    public String addgold(String userName, Integer gold) {

        User username = getOne(new QueryWrapper<User>().eq("username", userName));
        if (gold == 200){
            gold= 220;
        }
        if (gold == 500){
            gold= 570;
        }

        if (username!=null){
            username.setGold(username.getGold()+gold);
            updateById(username);
            //记录日志
            FileWriter writer = new FileWriter(fileManage.getFile()+"log.txt");
            String now = DateUtil.now();
            writer.append(now+ "："+userName+"充值"+gold+"成功\r\n");
            Log log1 = new Log();
            log1.setName(userName);
            log1.setLog("充值"+gold+"成功");
            log1.setType(1);
            log1.setTime(DateUtil.date());
            logService.save(log1);


            return "充值成功";
        }
        return "充值失败";
    }

    @Override
    @Transactional
    public String transfer(String myName, String username, Integer gold) {
        // 按固定顺序锁定账户，避免死锁
        String firstLock = myName.compareTo(username) < 0 ? myName : username;
        String secondLock = myName.compareTo(username) < 0 ? username : myName;

        // 使用for update锁定账户
        User firstUser = getOne(new QueryWrapper<User>()
                .eq("username", firstLock)
                .last("for update"));

        User secondUser = getOne(new QueryWrapper<User>()
                .eq("username", secondLock)
                .last("for update"));

        // 由于锁定顺序固定，我们需要根据实际转账方向确定哪个是转出账户，哪个是转入账户
        User myUser = firstLock.equals(myName) ? firstUser : secondUser;
        User targetUser = firstLock.equals(myName) ? secondUser : firstUser;

        if (targetUser == null) {
            return "被转让用户不存在，请检查用户名";
        }

        if (myUser.getGold() < gold) {
            return "余额不足";
        }

        // 更新余额
        myUser.setGold(myUser.getGold() - gold);
        updateById(myUser);

        targetUser.setGold(targetUser.getGold() + gold);
        updateById(targetUser);

        // 记录日志
        Log log1 = new Log();
        log1.setName(myName);
        log1.setLog(myName + "向" + username + "转让" + gold + "积分");
        log1.setType(4);
        log1.setTime(DateUtil.date());
        logService.save(log1);

        return "转让完毕";
    }


}
