package org.jeecg.modules.apiService.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.apiBean.PageBean;
import org.jeecg.modules.apiService.AmountService;
import org.jeecg.modules.apiUtils.CommonUtils;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.pay.MpWxPayService;
import org.jeecg.modules.teambuyBalanceLog.entity.TeambuyBalanceLog;
import org.jeecg.modules.teambuyBalanceLog.service.ITeambuyBalanceLogService;
import org.jeecg.modules.teambuyCash.entity.TeambuyCash;
import org.jeecg.modules.teambuyCash.service.ITeambuyCashService;
import org.jeecg.modules.teambuyOrderMember.entity.TeambuyOrderMember;
import org.jeecg.modules.teambuyTeamLeader.entity.TeambuyTeamLeader;
import org.jeecg.modules.teambuyTeamLeader.service.ITeambuyTeamLeaderService;
import org.jeecg.modules.teambuyTeamRelation.service.ITeambuyTeamRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Slf4j
@Service
public class AmountServiceImpl implements AmountService {
    /******************************************************************************************************************/
    //支付回调地址
    @Value("${wx.miniapp.cashNotifyUrl}")
    private String cashNotifyUrl;
    //支付接口
    @Autowired
    private MpWxPayService mpWxPayService;
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    //用户信息
    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    //收支信息
    @Resource
    private ITeambuyBalanceLogService teambuyBalanceLogService;
    //充值提现信息
    @Resource
    private ITeambuyCashService teambuyCashService;
    /******************************************************************************************************************/

    //充值
    @Override
    public Result<?> cashIn(String token, TeambuyCash teambuyCash) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        try{
            //订单信息
            String payNo = IdWorker.getIdStr();//生成订单号
            teambuyCash.setId(payNo);//订单编号
            teambuyCash.setTitle("金额充值");//订单名称
            teambuyCash.setType("0");//类型为充值
            teambuyCash.setUserId(hanHaiMember.getId());//关联用户

            //创建订单信息
            teambuyCashService.save(teambuyCash);

            //吊起微信支付
            BigDecimal price = teambuyCash.getAmount();//价格
            String productName = teambuyCash.getTitle();//服务名称

            String s = price.multiply(new BigDecimal(100)).toString();
            int i1 = Double.valueOf(s).intValue();
            Object appOrder = mpWxPayService.createOrder(
                    "充值"+ productName ,
                    "127.0.0.1",
                    teambuyCash.getId(),
                    i1,
                    teambuyCash.getId(),
                    hanHaiMember.getAppletOpenid(),
                    teambuyCash.toString(),
                    cashNotifyUrl);
            return Result.OK("充值成功",appOrder);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("充值失败");
        }
    }

    @Override
    public Result<?> queryAmountLog(String token, TeambuyBalanceLog balanceLog, PageBean pageBean) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //返回信息
        String massege = "";
        //分页信息
        Page<TeambuyBalanceLog> page = null;
        //查询信息
        LambdaQueryChainWrapper<TeambuyBalanceLog> query = null;
        //返回信息
        Page<TeambuyBalanceLog> pageList = null;

        try{
            //分页
            page = new Page<TeambuyBalanceLog>(pageBean.getPageNo(), pageBean.getPageSize());
            query = teambuyBalanceLogService
                    .lambdaQuery();

            //收支关联者
            query.eq(TeambuyBalanceLog::getUserId, hanHaiMember.getId());

            //收支类型
            if(StringUtils.isNotBlank(balanceLog.getCashType())){
                query.eq(TeambuyBalanceLog::getCashType, balanceLog.getCashType());
            }
            //记录类型
            if(StringUtils.isNotBlank(balanceLog.getRecordType())){
                query.eq(TeambuyBalanceLog::getRecordType, balanceLog.getRecordType());
            }

            //按照排序编号降序排列
            query.orderByDesc(TeambuyBalanceLog::getCreateTime);

            //获取商品信息信息
            pageList = query.page(page);

            return Result.OK("收支列表", pageList);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("收支列表查询失败");
        }
    }

    //充值回调
    public Result<?> CashNotify(String requestBody){
        WxPayOrderNotifyResult notify = mpWxPayService.notify(requestBody);
        String outTradeNo = notify.getOutTradeNo();
        log.info("充值回调订单号码："+outTradeNo);

        try{

            //查询订单信息
            TeambuyCash teambuyCash = teambuyCashService.getById(outTradeNo);
            //如果订单存在则修改订单状态
            if (null != teambuyCash){
                if("0".equals(teambuyCash.getStatus())){
                    teambuyCash.setStatus("1");//订单状态
                    teambuyCash.setPayTime(CommonUtils.getCurrentTime());//订单支付时间
                    teambuyCashService.updateById(teambuyCash);

                    //用户余额修改
                    HanHaiMember hanHaiMember = hanHaiMemberService.getById(teambuyCash.getUserId());
                    BigDecimal balance = hanHaiMember.getBalance().add(teambuyCash.getAmount());
                    hanHaiMember.setBalance(balance);
                    hanHaiMemberService.updateById(hanHaiMember);

                    //添加充值日志
                    TeambuyBalanceLog balanceLog = new TeambuyBalanceLog();
                    balanceLog.setAmount(teambuyCash.getAmount());//充值金额
                    balanceLog.setCashType("0");//收入
                    balanceLog.setRecordType("1");//余额充值
                    balanceLog.setUserId(teambuyCash.getUserId());
                    balanceLog.setTitle("余额充值");
                    teambuyBalanceLogService.save(balanceLog);
                }
            }

        }catch (Exception e){
            log.info("充值回调失败，订单号码："+outTradeNo);
            e.printStackTrace();
        }
        return null;
    }

}
