package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.dto.req.OrderReq;
import com.yonge.cooleshow.biz.dal.entity.PianoRoomTime;
import com.yonge.cooleshow.biz.dal.entity.PlatformCashAccountRecord;
import com.yonge.cooleshow.biz.dal.entity.UserOrder;
import com.yonge.cooleshow.biz.dal.enums.AccountBizTypeEnum;
import com.yonge.cooleshow.biz.dal.enums.InOrOutEnum;
import com.yonge.cooleshow.biz.dal.service.*;
import com.yonge.cooleshow.biz.dal.vo.*;
import com.yonge.cooleshow.biz.dal.vo.res.OrderCreateRes;
import com.yonge.cooleshow.common.entity.HttpResponseResult;
import com.yonge.cooleshow.common.enums.CacheNameEnum;
import com.yonge.cooleshow.common.enums.PostStatusEnum;
import com.yonge.toolset.payment.util.DistributedLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yonge.cooleshow.biz.dal.entity.PianoRoomBuyRecord;
import com.yonge.cooleshow.biz.dal.dto.search.PianoRoomBuyRecordSearch;
import com.yonge.cooleshow.biz.dal.dao.PianoRoomBuyRecordDao;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


@Service
public class PianoRoomBuyRecordServiceImpl extends ServiceImpl<PianoRoomBuyRecordDao, PianoRoomBuyRecord> implements PianoRoomBuyRecordService {
    private final static Logger log = LoggerFactory.getLogger(PianoRoomBuyRecordServiceImpl.class);

    @Autowired
    private PianoRoomSettingsService pianoRoomSettingsService;
    @Autowired
    private PianoRoomTimeService pianoRoomTimeService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private PlatformCashAccountRecordService platformCashAccountRecordService;
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PianoRoomBuyRecordVo detail(Long id) {
        return baseMapper.detail(id);
    }

    @Override
    public IPage<PianoRoomBuyRecordVo> selectPage(IPage<PianoRoomBuyRecordVo> page, PianoRoomBuyRecordSearch query) {
        return page.setRecords(baseMapper.selectPage(page, query));
    }

    @Override
    public HttpResponseResult<OrderCreateRes> orderCreate(OrderReq.OrderReqInfo orderReqInfo) {
        PianoRoomSettingsVo detail = pianoRoomSettingsService.detail(Long.parseLong(orderReqInfo.getBizContent().toString()));
        if (null == detail) {
            return HttpResponseResult.failed("未找到时长包");
        }
        OrderCreateRes orderCreateRes = new OrderCreateRes();
        orderCreateRes.setRes(true);
        orderCreateRes.setMerchId(0l);
        orderCreateRes.setBizId(detail.getId());
        orderCreateRes.setBizContent("琴房时长包购买-" + detail.getTimes() + "分");
        orderCreateRes.setGoodNum(1);
        orderCreateRes.setOriginalPrice(detail.getOriginalPrice());
        orderCreateRes.setExpectPrice(detail.getSalePrice());
        return HttpResponseResult.succeed(orderCreateRes);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void orderSuccess(UserOrderDetailVo orderDetailVo) {
        PianoRoomSettingsVo detail = pianoRoomSettingsService.detail(orderDetailVo.getBizId());
        if (null == detail) {
            return;
        }
        TeacherVo teacherVo = teacherService.detail(orderDetailVo.getUserId());

        //保存琴房购买记录
        save(new PianoRoomBuyRecord(teacherVo.getUserId(), detail.getId(), orderDetailVo.getOrderNo(),
                orderDetailVo.getSubOrderNo(), detail.getTimes()));

        //入琴房账户
        DistributedLock.of(redissonClient)
                .runIfLockToFunction(CacheNameEnum.LOCK_CHANGE_PIANO_ROOM_ACCOUNT.getRedisKey(orderDetailVo.getUserId())
                        , (o) -> {
                            PianoRoomTime pianoRoomTime = pianoRoomTimeService.getOne(Wrappers.<PianoRoomTime>lambdaQuery()
                                    .eq(PianoRoomTime::getTeacherId, orderDetailVo.getUserId()));
                            if (null == pianoRoomTime) {
                                pianoRoomTime = new PianoRoomTime();
                                pianoRoomTime.setTeacherId(orderDetailVo.getUserId());
                                pianoRoomTime.setRemainTime(detail.getTimes());
                                pianoRoomTimeService.save(pianoRoomTime);
                            } else {
                                pianoRoomTime.setRemainTime(pianoRoomTime.getRemainTime() + detail.getTimes());
                                pianoRoomTime.setUpdateTime(new Date());
                                pianoRoomTimeService.updateById(pianoRoomTime);
                            }
                            return null;
                        }, null, 10l);
    }

}