package org.dromara.web.controller;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lakala.zf.laop.java.sdk.demo.utils.KlkConstant;
import com.lakala.zf.laop.java.sdk.demo.utils.LakalaUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysUserService;
import org.dromara.web.utils.*;
import org.dromara.work.domain.TpFollow;
import org.dromara.work.domain.TpUserAuth;
import org.dromara.work.domain.bo.RechargeBo;
import org.dromara.work.domain.bo.TpOrderPayBo;
import org.dromara.work.domain.bo.TpUserAuthBo;
import org.dromara.work.domain.vo.MyCountVo;
import org.dromara.work.domain.vo.TpUserAuthVo;
import org.dromara.work.service.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 用户接口
 * @author Maosw
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/user")
@Tag(name = "用户接口")
public class ApiUserController {

    private final ISysUserService tzUserService;

    private final TokenStore tokenStore;

    private final ITpUserAuthService tpUserAuthService;

    private final ITpFollowService tpFollowService;

    private final ITpWorksNumService tpWorksNumService;

    private final ITpPictureService tpPictureService;

    private final ITpOrderPayService tpOrderPayService;


    @PostMapping("/getUserPhoneNumber")
    @Operation(summary = "微信接口获取手机号码" , description = "微信接口获取手机号码")
    @Parameter(name = "code", description = "code", required = true)
    public R<JSONObject> getUserPhoneNumber(@RequestParam(value = "code") String code) {
        return R.ok(WxXcxUtils.getUserPhoneNumber(code));
    }

    @PostMapping("/register")
    @Operation(summary = "注册登录" , description = "用户绑定手机号注册登录")
    public R<TokenInfoVO> register(@Valid @RequestBody UserRegisterParam userRegisterParam) {
        if (StrUtil.isBlank(userRegisterParam.getNickName())) {
            userRegisterParam.setNickName(userRegisterParam.getUserName());
        }

        SysUser tzUser = tzUserService.getUserByUserMobile(userRegisterParam.getMobile());
        if (ObjectUtil.isNotEmpty(tzUser)) {
            //登录
            UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
            userInfoInTokenBO.setUserId(tzUser.getUserId());
            userInfoInTokenBO.setSysType(0);
            userInfoInTokenBO.setEnabled(true);
            return R.ok(tokenStore.storeAndGetVo(userInfoInTokenBO));
        }else {
            //注册并登录
            Date now = new Date();
            SysUser user = new SysUser();
            user.setLoginDate(now);
            user.setCreateTime(now);
            user.setStatus("0");
            user.setPhonenumber(userRegisterParam.getMobile());
            user.setUserName(userRegisterParam.getMobile());
            user.setNickName(userRegisterParam.getNickName());
            user.setEmail(userRegisterParam.getUserMail());
            user.setAvatar(userRegisterParam.getImg());
            user.setIdentity(userRegisterParam.getSysType());
            user.setPassword(BCrypt.hashpw(userRegisterParam.getPassWord()));
            user.setOpenId(userRegisterParam.getOpenId());
            tzUserService.save(user);
            // 2. 登录
            UserInfoInTokenBO userInfoInTokenBO = new UserInfoInTokenBO();
            userInfoInTokenBO.setUserId(user.getUserId());
            userInfoInTokenBO.setSysType(0);
            userInfoInTokenBO.setEnabled(true);
            return R.ok(tokenStore.storeAndGetVo(userInfoInTokenBO));
        }
    }

    @PutMapping("/updatePwd")
    @Operation(summary = "修改密码" , description = "修改密码")
    public R<Boolean> updatePwd(@Valid @RequestBody UserRegisterParam userPwdUpdateParam) {
        Long userId = SecurityUtils.getUserId();
        SysUserVo user = tzUserService.selectUserById(userId);
        if (user == null) {
            // 无法获取用户信息
            throw new ServiceException("无法获取用户信息");
        }
        if (StrUtil.isBlank(userPwdUpdateParam.getPassWord())) {
            // 新密码不能为空
            throw new ServiceException("新密码不能为空");
        }
        String password = BCrypt.hashpw(userPwdUpdateParam.getPassWord());
        if (StrUtil.equals(password, user.getPassword())) {
            // 新密码不能与原密码相同
            throw new ServiceException("新密码不能与原密码相同");
        }
        user.setPassword(password);

        SysUser tzUser = MapstructUtils.convert(user, SysUser.class);
        return R.ok(tzUserService.updateById(tzUser));
    }

    /**
     * 修改昵称/头像
     */
    @PutMapping("/updateUserInfo")
    @Operation(summary = "修改昵称/头像" , description = "修改昵称/头像")
    public R<Boolean> updateUserInfo(@Valid @RequestBody SysUserVo sysUserVo) {
        Long userId = SecurityUtils.getUserId();
        SysUserVo user = tzUserService.selectUserById(userId);
        if (user == null) {
            // 无法获取用户信息
            throw new ServiceException("无法获取用户信息");
        }
        if (StrUtil.isNotBlank(sysUserVo.getNickName())) {
            user.setNickName(sysUserVo.getNickName());
        }
        if (StrUtil.isNotBlank(sysUserVo.getAvatar())) {
            user.setAvatar(sysUserVo.getAvatar());
        }
        SysUser tzUser = MapstructUtils.convert(user, SysUser.class);
        return R.ok(tzUserService.updateById(tzUser));
    }

    /**
     * 用户提交认证信息
     */
    @PostMapping("/submitUserAuth")
    @Operation(summary = "用户提交认证信息" , description = "用户提交认证信息")
    public R<Boolean> submitUserAuth(@Valid @RequestBody TpUserAuthBo tpUserAuthBo) {
        Long userId = SecurityUtils.getUserId();
        tpUserAuthBo.setUserId(userId);
        tpUserAuthBo.setStatus(1);
        return R.ok(tpUserAuthService.insertByBo(tpUserAuthBo));
    }

    /**
     * 用户获取认证信息
     */
    @GetMapping("/getUserAuth")
    @Operation(summary = "用户获取认证信息" , description = "用户获取认证信息")
    public R<TpUserAuthVo> getUserAuth() {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<TpUserAuth> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TpUserAuth::getUserId, userId);
        TpUserAuth tpUserAuth = tpUserAuthService.getOne(queryWrapper);
        return R.ok(MapstructUtils.convert(tpUserAuth, TpUserAuthVo.class));
    }

    /**
     * 获取我的信息
     */
    @GetMapping("/getMyInfo")
    @Operation(summary = "获取我的信息" , description = "获取我的信息")
    public R<SysUserVo> getMyInfo() {
        Long userId = SecurityUtils.getUserId();
        SysUserVo user = tzUserService.queryUserById(userId);
        return R.ok(user);
    }

    /**
     * 根据用户ID获取用户信息
     */
    @GetMapping("/getUserInfo/{userId}")
    @Operation(summary = "根据用户ID获取用户信息" , description = "根据用户ID获取用户信息")
    public R<SysUserVo> getUserInfo(@PathVariable Long userId) {
        SysUserVo user = tzUserService.selectUserById(userId);
        return R.ok(user);
    }

    /**
     * 获取我的关注数、粉丝数、收藏作品数、我的作品数、我的动态数
     */
    @GetMapping("/getMyCount")
    @Operation(summary = "获取我的关注数、粉丝数、收藏作品数、我的作品数" , description = "获取我的关注数、粉丝数、收藏作品数、我的作品数")
    public R<MyCountVo> getMyCount() {
        Long userId = SecurityUtils.getUserId();
        MyCountVo myCountVo = new MyCountVo();
        myCountVo.setFollowCount(tpFollowService.getFollowCount(userId));
        myCountVo.setFansCount(tpFollowService.getFansCount(userId));
        myCountVo.setCollectCount(tpWorksNumService.getCollectionCount(userId));
        myCountVo.setMyPictureCount(tpPictureService.getMyPictureCount(userId,2));
        myCountVo.setMyDynamicsCount(tpPictureService.getMyPictureCount(userId,3));
        return R.ok(myCountVo);
    }

    /**
     * 根据用户ID获取用户的关注数、粉丝数、收藏作品数、作品数
     */
    @GetMapping("/getUserCount/{userId}")
    @Operation(summary = "根据用户ID获取用户的关注数、粉丝数、收藏作品数、作品数" , description = "根据用户ID获取用户的关注数、粉丝数、收藏作品数、作品数")
    public R<MyCountVo> getUserCount(@PathVariable Long userId) {
        MyCountVo myCountVo = new MyCountVo();
        myCountVo.setFollowCount(tpFollowService.getFollowCount(userId));
        myCountVo.setFansCount(tpFollowService.getFansCount(userId));
        myCountVo.setCollectCount(tpWorksNumService.getCollectionCount(userId));
        myCountVo.setMyPictureCount(tpPictureService.getMyPictureCount(userId,2));
        myCountVo.setMyDynamicsCount(tpPictureService.getMyPictureCount(userId,3));
        return R.ok(myCountVo);
    }

    /**
     * 分页获取我的关注用户列表
     */
    @GetMapping("/getMyFollowList")
    @Operation(summary = "分页获取我的关注用户列表" , description = "分页获取我的关注用户列表")
    public R<IPage<SysUserVo>> getMyFollowList(PageQuery pageQuery) {
        Long userId = SecurityUtils.getUserId();
        List<Long> userIds = tpFollowService.queryListIds(userId);
        if (CollUtil.isEmpty(userIds)) {
            return R.fail("没有关注人");
        }
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDelFlag, 0);
        queryWrapper.in(SysUser::getUserId, userIds);
        return R.ok(tzUserService.selectPageList(pageQuery, queryWrapper));
    }

    /**
     * 分页获取我的粉丝用户列表
     */
    @GetMapping("/getMyFansList")
    @Operation(summary = "分页获取我的粉丝用户列表" , description = "分页获取我的粉丝用户列表")
    public R<IPage<SysUserVo>> getMyFansList(PageQuery pageQuery) {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<TpFollow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TpFollow::getToUserId, userId);
        List<Long> userIds = tpFollowService.queryListToUserIds(userId);
        LambdaQueryWrapper<SysUser> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(SysUser::getDelFlag, 0);
        queryWrapper2.in(SysUser::getUserId, userIds);
        return R.ok(tzUserService.selectPageList(pageQuery, queryWrapper2));
    }

    /**
     * 余额充值
     */
    @PostMapping("/recharge")
    @Operation(summary = "余额充值" , description = "余额充值")
    public R<JSONObject> recharge(@Valid @RequestBody RechargeBo rechargeBo) throws Exception {
        Long userId = SecurityUtils.getUserId();
        SysUserVo sysUser = tzUserService.selectUserById(userId);
        String uuid = UUID.randomUUID().toString().replace("-", "");

        JSONObject jsonObject = LakalaUtils.createOrderPay(uuid, rechargeBo.getPrice(), KlkConstant.RECHARGE_ORDER);
        if ("000000".equals(jsonObject.get("code"))) {
            System.out.println(jsonObject.get("resp_data").toString());
            JSONObject respData = jsonObject.getJSONObject("resp_data");
            String payOrderNo = respData.getString("pay_order_no");

            TpOrderPayBo orderPay = new TpOrderPayBo();
            orderPay.setUserId(sysUser.getUserId());
            orderPay.setUserName(sysUser.getRealName());
            orderPay.setUserPhone(sysUser.getPhonenumber());
            orderPay.setAmount(rechargeBo.getPrice());
            orderPay.setStatus(1);
            orderPay.setMethod(1);
            orderPay.setType(2);
            orderPay.setOrderNo(uuid);
            orderPay.setTransactionId(payOrderNo);
            orderPay.setCreateTime(new Date());
            if (!tpOrderPayService.insertByBo(orderPay)){
                throw new ServiceException("创建支付订单失败");
            }
        } else {
            throw new ServiceException("拉卡拉拉发起支付失败");
        }
        return R.ok(jsonObject);
    }

}
