package com.github.wxiaoqi.security.admin.biz;

import cn.hutool.core.date.DateTime;
import com.github.wxiaoqi.security.admin.dto.UserInfoDTO;
import com.github.wxiaoqi.security.admin.entity.MyWallet;
import com.github.wxiaoqi.security.admin.entity.MyWalletDetail;
import com.github.wxiaoqi.security.admin.mapper.MyWalletDetailMapper;
import com.github.wxiaoqi.security.admin.mapper.MyWalletMapper;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.activity.feign.ActivityFeign;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.List;

/**
 * 钱包
 *
 * @author libin
 * @email 18178966185@163.com
 * @date 2019-07-09 10:00:42
 */
@Service
@Slf4j
public class MyWaterBiz extends BaseBiz<MyWalletMapper, MyWallet>{

    @Autowired
    MyWalletDetailBiz walletDetailBiz;

    @Autowired
    ActivityFeign activityFeign;


    //我的钱包入账
    public  void updMyWater(MyWalletDetail walletDetail){
        if (walletDetail==null){
            log.info("钱包入账-----参数为空");
        }
        Integer userId= walletDetail.getUserId();
        BigDecimal amount= walletDetail.getAmount();
        Integer source=walletDetail.getSource();
        log.info("---我的钱包入账----userId==="+userId+"----source===="+source+"----amount===="+amount);
        MyWallet wallet=new MyWallet();
        wallet.setUserId(userId);
        wallet=selectOne(wallet);
        //进账之前余额
        BigDecimal oldBalance=new BigDecimal("0.00");
        BigDecimal balance=new BigDecimal("0.00");
        //进账总额(元)
        BigDecimal totalAmount=new BigDecimal("0.00");
        //今日收益
        BigDecimal todayAmount=new BigDecimal("0.00");
        //未入账金额
        BigDecimal unbooked=new BigDecimal("0.00");
        Integer id=0;
        if(wallet==null){
            wallet=new MyWallet();
            wallet.setUserId(userId);
            totalAmount=amount;
            todayAmount=amount;
            balance=amount;
        }else {
            id=wallet.getId();
            oldBalance=wallet.getBalance();
            balance=wallet.getBalance().add(amount);
            totalAmount=wallet.getTotalAmount().add(amount);
            Long lastTime=wallet.getLastIntime();
            todayAmount=amount;
            if (lastTime!=null&&(lastTime==0||isToday(lastTime))){
                todayAmount=wallet.getTodayAmount().add(amount);
            }
        }
        unbooked=wallet.getUnbooked().subtract(unbooked);
        log.info("---我的钱包入账----userId==="+userId+"----balance===="+balance+"----totalAmount===="+totalAmount+"---todayAmount==="+todayAmount+"---unbooked=="+unbooked);
        walletDetail.setItype(0);
        walletDetail.setBalance(oldBalance);
        walletDetailBiz.insertSelective(walletDetail);
        Long time=System.currentTimeMillis();
        wallet.setBalance(balance);
        wallet.setUnbooked(unbooked);
        wallet.setTodayAmount(todayAmount);
        wallet.setTotalAmount(totalAmount);
        wallet.setUnbooked(unbooked);
        wallet.setLastIntime(time);
        wallet.setUpdTime(time);
        if(id>0){
        mapper.updMyWater(wallet);
        }else {
        wallet.setCrtTime(time);
        insertSelective(wallet);
        }
        log.info("---我的钱包入账----userId==="+userId+"----成功");
    }

    // 这个时间戳是不是今天
    public boolean  isToday(long time) {
        boolean isToday = false;
        Date date;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            date = sdf.parse(sdf.format(new Date()));
            if (time < (date.getTime()+24*3600*1000) && time > date.getTime()) {
                isToday = true;
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return isToday;
    }

    //钱包未入账的处理type1-进;2-出
    public  void updMyWalletUnbooked(Integer userId,BigDecimal amount,Integer type){
        log.info("---钱包未入账的处理updMyWalletUnbooked----userId==="+userId+"----type==="+type+"---amount==="+amount);

        MyWallet wallet=new MyWallet();
        wallet.setUserId(userId);
        wallet=selectOne(wallet);
        BigDecimal unbooked=new BigDecimal("0.00");
        if(wallet==null){
            wallet=new MyWallet();
            wallet.setUserId(userId);
            if (type==1){
                unbooked=amount;
            }
            wallet.setUnbooked(unbooked);
            insertSelective(wallet);
        }else {
            if (type==1){
                unbooked=wallet.getUnbooked().add(amount);
            }else {
                if (wallet.getUnbooked().compareTo(amount)>0){
                    unbooked=wallet.getUnbooked().subtract(amount);
                }
            }
            log.info("---钱包未入账的处理updMyWalletUnbooked----userId==="+userId+"----unbooked==="+unbooked);
            wallet.setUnbooked(unbooked);
            updateSelectiveById(wallet);
        }
    }

    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public int createWalletByUserId(Integer userId){
        MyWallet myWallet = new MyWallet();
        myWallet.setUserId(userId);
        myWallet.setCrtTime(Instant.now().toEpochMilli());
        myWallet.setUpdTime(Instant.now().toEpochMilli());
        return mapper.insertSelective(myWallet);
    }

    public ObjectRestResponse getUserProfit(Integer userId){

        try {
           UserInfoDTO dto=activityFeign.getUserInfo(userId);
           if (dto==null){
               dto=new UserInfoDTO();
               dto.setCouponNumber(0L);
               dto.setTotalPoint(0);
           }
            MyWallet wallet=new MyWallet();
            wallet.setUserId(userId);
            wallet=selectOne(wallet);
            if (wallet!=null){
                BeanUtils.copyProperties(wallet,dto);
            }else {
                dto.setBalance(BigDecimal.ZERO);
            }
            return  ObjectRestResponse.succ(dto);
        }catch (Exception e){
            e.printStackTrace();
            return  ObjectRestResponse.createDefaultFail();
        }

    }

    //定时处理今日收益
    public  void  updTodayAmount(){
        Example example=new Example(MyWallet.class);
        example.createCriteria().andGreaterThan("todayAmount",0).andEqualTo("isFrozen",0);
        List<MyWallet> list=selectByExample(example);
        log.info("---钱包定时处理今日收益updTodayAmount----size==="+list.size());
        XxlJobLogger.log("---钱包定时处理今日收益updTodayAmount----size==="+list.size());
        if (list.size()>0){
            for (MyWallet myWallet:list){
                log.info("---钱包定时处理今日收益updTodayAmount----userId==="+myWallet.getUserId());
                XxlJobLogger.log("---钱包定时处理今日收益updTodayAmount----userId==="+myWallet.getUserId());
                MyWallet myWallet1=new MyWallet();
                myWallet1.setUserId(myWallet.getUserId());
                myWallet1.setTodayAmount(new BigDecimal("0.00"));
                updateSelectiveById(myWallet1);
            }
        }

    }
}