package com.ruoyi.api;

import com.ruoyi.ai.domain.AiSampleAmount;
import com.ruoyi.ai.domain.AiSampleAmountRecord;
import com.ruoyi.ai.mapper.AiSampleAmountMapper;
import com.ruoyi.ai.service.EmailVerifyService;
import com.ruoyi.ai.service.IAiSampleAmountRecordService;
import com.ruoyi.ai.service.IAiUserService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.BalanceChangerConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.AiUser;
import com.ruoyi.common.core.domain.model.LoginAiUserBody;
import com.ruoyi.common.core.domain.model.RegisterAiUserBody;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


/**
 * ai-用户信息Controller
 *
 * @author shi
 * @date 2025-11-12
 */
@Api(tags = "ai-用户信息")
@RestController
@RequestMapping("/api/user")
public class AiUserApiController extends BaseController {

    @Autowired
    private SysLoginService loginService;

    @Autowired
    private IAiUserService aiUserService;

    @Autowired
    private EmailVerifyService emailVerifyService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private AiSampleAmountMapper aiSampleAmountMapper;

    @Autowired
    private IAiSampleAmountRecordService aiSampleAmountRecordService;

    @Autowired
    private ISysJobService sysJobService;


    @ApiOperation("用户登录")
    @PostMapping("/login")
    @Anonymous
    public AjaxResult loginAiUser(@Validated @RequestBody LoginAiUserBody loginAiUserBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.loginAiUser(loginAiUserBody);
        ajax.put(Constants.TOKEN, token);
        ajax.put("username", loginAiUserBody.getUsername() != null ? loginAiUserBody.getUsername() : loginAiUserBody.getEmail());
        return ajax;
    }


    @ApiOperation("获取ai-用户信息详细信息")
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo() {
        return success(aiUserService.getUserInfo(SecurityUtils.getAiUserId()));
    }


    @ApiOperation("用户注册")
    @PostMapping("/registerAiUser")
    @Anonymous
    public AjaxResult registerAiUser(@Validated @RequestBody RegisterAiUserBody registerAiUserBody) {
        AiUser aiUser = aiUserService.registerAiUser(registerAiUserBody);
        // 查询启用状态体验金活动
        AiSampleAmount aiSampleAmount = aiSampleAmountMapper.getSampleAmount();
        if (aiSampleAmount != null) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
            String dateTime = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String orderNo = dateTime + uuid;
            // 余额变更记录
            aiUserService.addUserBalance(orderNo, aiUser.getId(), aiSampleAmount.getAmount(), BalanceChangerConstants.EXPERIENCE_GOLD_GIFT);
            // 新增体验金记录
            AiSampleAmountRecord aiSampleAmountRecord = new AiSampleAmountRecord();
            aiSampleAmountRecord.setUserId(aiUser.getId());
            aiSampleAmountRecord.setSampleAmount(aiSampleAmount.getAmount());
            aiSampleAmountRecord.setRecycleTime(DateUtils.addHours(DateUtils.getNowDate(), aiSampleAmount.getDuration()));
            aiSampleAmountRecord.setStatus(0);
            aiSampleAmountRecordService.insertAiSampleAmountRecord(aiSampleAmountRecord);

            // 新增定时回收体验金任务
            SysJob sysJob = new SysJob();
            sysJob.setJobName("定时回收体验金");
            sysJob.setJobGroup("DEFAULT");
            sysJob.setInvokeTarget("ryTask.deductSampleAmount('" + aiUser.getId() + "')");
            sysJob.setCronExpression(CronUtils.generateCronExpression(aiSampleAmountRecord.getRecycleTime()));
            sysJob.setMisfirePolicy(ScheduleConstants.MISFIRE_DEFAULT);
            sysJob.setConcurrent("0");
            sysJob.setStatus("0");
            try {
                sysJobService.insertJob(sysJob);
            } catch (SchedulerException e) {
                throw new RuntimeException(e);
            } catch (TaskException e) {
                throw new RuntimeException(e);
            }

        }
        return AjaxResult.success("注册成功");
    }

    @ApiOperation("发送邮箱验证码")
    @GetMapping("/sendEmailCode")
    @Anonymous
    public AjaxResult sendEmailCode(String email) {
        try {
            // 判断邮箱是否重复
            if (aiUserService.getUserCountByEmail(email) > 0) {
                throw new ServiceException(MessageUtils.message("user.email.registered"), HttpStatus.CONFLICT);
            }
            emailVerifyService.sendVerifyCode(email);
            return AjaxResult.success(MessageUtils.message("email.send.success", null));
        } catch (MessagingException e) {
            return AjaxResult.error(MessageUtils.message("email.send.failure", null));
        }
    }


    @ApiOperation("发送修改密码或忘记密码邮箱验证码")
    @GetMapping("/sendEmailCodeV2")
    @Anonymous
    public AjaxResult sendUpdatePasswordEmailCode(String email) {
        try {
            // 判断邮箱是否重复
            if (aiUserService.getUserCountByEmail(email) == 0) {
                return AjaxResult.error(-1, "The email address is not registered");
            }
            emailVerifyService.sendVerifyCode(email);
            return AjaxResult.success(MessageUtils.message("email.send.success", null));
        } catch (MessagingException e) {
            return AjaxResult.error(MessageUtils.message("email.send.failure", null));
        }
    }


    @ApiOperation("重置密码")
    @Anonymous
    @PutMapping("/resetPassword")
    public AjaxResult resetPassword(String email, String password, String code) {
        AiUser aiUser = aiUserService.getUserByEmail(email);
        if (aiUser == null) {
            throw new ServiceException("email not registered", HttpStatus.BAD_REQUEST);
        }
        if (!emailVerifyService.verifyCode(aiUser.getEmail(), code)) {
            throw new ServiceException(MessageUtils.message("email.verification.code.error"), HttpStatus.BAD_REQUEST);
        }
        aiUser.setPassword(SecurityUtils.encryptPassword(password));
        aiUserService.updateAiUser(aiUser);
        return AjaxResult.success();
    }


    @ApiOperation("修改密码")
    @PutMapping("/updatePassword")
    public AjaxResult updatePassword(String oldPassword, String newPassword) {
        aiUserService.updatePassword(oldPassword, newPassword);
        return AjaxResult.success();
    }

    @ApiOperation("修改邮箱")
    @PutMapping("/updateEmail")
    public AjaxResult updateEmail(String email, String code) {
        aiUserService.updateEmail(email, code);
        return AjaxResult.success();
    }

    @ApiOperation("修改头像")
    @PutMapping("/updateAvatar")
    public AjaxResult updateAvatar(String avatar) {
        aiUserService.updateAvatar(avatar);
        return AjaxResult.success();
    }

    @Anonymous
    @ApiOperation("获取门户端logo")
    @GetMapping("/getPortalLogo")
    public AjaxResult getPortalLogo() {
        SysConfig sysConfig = sysConfigService.getPortalLogo();
        return AjaxResult.success("successfully", sysConfig.getConfigValue());
    }


    /**
     * 查询返佣比例配置
     *
     * @return
     */
    @GetMapping("/getRebateConfig")
    public AjaxResult getRebateConfig() {
        String result = aiUserService.getRebateConfig();
        return AjaxResult.success().put("result", result);
    }


    @GetMapping("/checkIsStandard")
    public AjaxResult checkIsStandard() {
        Map<String, Object> result = aiUserService.checkIsStandard();
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("result", result.get("result"));
        ajaxResult.put("totalAmount", result.get("totalAmount"));
        return ajaxResult;
    }


}
