package com.fs.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.app.annotation.Login;
import com.fs.common.core.domain.R;
import com.fs.live.domain.Live;
import com.fs.live.domain.LiveGift;
import com.fs.live.domain.LiveRewardRecord;
import com.fs.live.domain.LiveUserGift;
import com.fs.live.enums.FsUserIntegralLogTypeEnum;
import com.fs.live.param.SendGiftParam;
import com.fs.live.service.ILiveGiftService;
import com.fs.live.service.ILiveRewardRecordService;
import com.fs.live.service.ILiveService;
import com.fs.live.service.ILiveUserGiftService;
import com.fs.store.domain.FsUser;
import com.fs.store.service.IFsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 直播间礼物Controller
 */
@RestController
@RequestMapping("/app/live/liveGift")
public class LiveGiftController extends AppBaseController {

    @Autowired
    private ILiveGiftService liveGiftService;

    @Autowired
    private ILiveUserGiftService liveUserGiftService;

    @Autowired
    private IFsUserService fsUserService;

    @Autowired
    private ILiveRewardRecordService liveRewardRecordService;

    @Autowired
    private ILiveService liveService;


    /**
     * 接口①：查询正常状态的礼物列表，按价格升序排列
     */
    @GetMapping("/activeList")
    public R getActiveGiftList() {
        List<LiveGift> gifts = liveGiftService.selectActiveLiveGiftList();
        return R.ok().put("data", gifts);
    }

    /**
     * 接口②：用户送礼物
     * @param param 包含giftId和liveId
     */
    @Login
    @PostMapping("/send")
    @Transactional
    public R sendGift(@RequestBody SendGiftParam param) {
        try {
            // 获取当前用户ID
            String userIdStr = getUserId();
            if (userIdStr == null) {
                return R.error("用户未登录");
            }
            Long userId = Long.parseLong(userIdStr);
            Long giftId = param.getGiftId();
            Long liveId = param.getLiveId();

            // 1. 查询礼物信息
            LiveGift gift = liveGiftService.selectLiveGiftByGiftId(giftId);
            if (gift == null) {
                return R.error("礼物不存在");
            }
            if (!"1".equals(gift.getStatus())) {
                return R.error("礼物已停用");
            }

            // 2. 查询直播间信息
            Live live = liveService.selectLiveByLiveId(liveId);
            if (live == null) {
                return R.error("直播间不存在");
            }

            // 3. 查询用户信息
            FsUser user = fsUserService.selectFsUserById(userId);
            if (user == null) {
                return R.error("用户不存在");
            }

            // 4. 计算需要消耗的积分（礼物价格，默认数量为1）
            BigDecimal giftPrice = gift.getPrice();
            if (giftPrice == null || giftPrice.compareTo(BigDecimal.ZERO) <= 0) {
                return R.error("礼物价格无效");
            }
            Long integralCost = giftPrice.longValue();
            if (param.getCn() != null && param.getCn() > 1) {
                integralCost = giftPrice.multiply(BigDecimal.valueOf(param.getCn())).longValue();
            }

            // 5. 判断用户积分是否足够
            BigDecimal userIntegral = user.getIntegral();
            if (userIntegral == null || userIntegral.compareTo(BigDecimal.valueOf(integralCost)) < 0) {
                return R.error("积分不足，无法送礼物");
            }

            // 6. 记录积分消耗前的余额
            BigDecimal beforeIntegral = userIntegral;
            BigDecimal afterIntegral = userIntegral.subtract(BigDecimal.valueOf(integralCost));

            // 7. 扣除用户积分
            fsUserService.decIntegral(userId, integralCost.doubleValue());

            // 8. 保存用户送礼物记录
            LiveUserGift liveUserGift = new LiveUserGift();
            liveUserGift.setUserId(userId);
            liveUserGift.setGiftId(giftId);
            liveUserGift.setGiftName(gift.getGiftName());
            liveUserGift.setLiveId(liveId);
            liveUserGift.setGiftTime(new Date());
            liveUserGift.setCn(param.getCn() != null ? param.getCn() : 1L);
            liveUserGiftService.save(liveUserGift);

            // 9. 记录积分消耗记录
            LiveRewardRecord record = new LiveRewardRecord();
            record.setLiveId(liveId);
            record.setUserId(userId);
            record.setIncomeType(2L); // 支出
            record.setSourceType(4L); // 来源类型：4送礼物（1观看奖励 2答题红包 3观看积分 4送礼物）
            record.setSourceId(giftId);
            record.setRewardType(2L); // 积分
            record.setNum(BigDecimal.valueOf(integralCost));
            record.setBeforeNum(beforeIntegral);
            record.setAfterNum(afterIntegral);
            record.setCreateTime(new Date());
            record.setCreateBy(String.valueOf(userId));
            liveRewardRecordService.insertLiveRewardRecord(record);

            // 10. 调用开放平台接口更新用户积分（异步）
            // 注意：传递负数表示扣除积分，unifyIntegral传0表示使用userIntegralList中的值
            FsUser userForPlatform = new FsUser();
            userForPlatform.setUserId(userId);
            userForPlatform.setIntegral(BigDecimal.valueOf(-integralCost)); // 负数表示扣除
            List<FsUser> result = new ArrayList<>();
            result.add(userForPlatform);
            fsUserService.openPlatformGeneralUserIntegralHandle(
                    result,
                    liveId,
                    0L, // unifyIntegral传0，使用userIntegralList中的值
                    FsUserIntegralLogTypeEnum.TYPE_26.getValue() // 赠送礼物扣除积分
            );

            return R.ok("送礼物成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("送礼物失败：" + e.getMessage());
        }
    }

}
