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.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.employAmountLog.entity.EmployAmountLog;
import org.jeecg.modules.employAmountLog.service.IEmployAmountLogService;
import org.jeecg.modules.employTrade.entity.EmployTrade;
import org.jeecg.modules.employTrade.service.IEmployTradeService;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.pay.MpWxPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class AmountServiceImpl implements AmountService {

    /******************************************************************************************************************/
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;

    //支付接口
    @Autowired
    private MpWxPayService mpWxPayService;

    //交易订单
    @Resource
    private IEmployTradeService employTradeService;

    //金额明细
    @Resource
    private IEmployAmountLogService employAmountLogService;

    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    /******************************************************************************************************************/

    //我的钱包-我的余额
    @Override
    public Result<?> queryBalance(String token) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        return Result.OK("余额",hanHaiMember.getPrice());
    }

    //我的钱包-累计提现
    @Override
    public Result<?> CountCashOut(String token) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        try{
            //查询提现记录
            List<EmployAmountLog> cashOutAmount = employAmountLogService
                    .lambdaQuery()
                    .eq(EmployAmountLog::getTitle, "提现")
                    .eq(EmployAmountLog::getUserId, hanHaiMember.getId())
                    .list();

            //累加提现金额
            BigDecimal amount = BigDecimal.valueOf(0);
            for (EmployAmountLog amountLog : cashOutAmount) {
                amount.add(amountLog.getAmount());
            }

            return Result.OK("累计提现金额", amount);
        }catch (Exception e){
            e.printStackTrace();
            return Result.OK("累计提现查询失败！");
        }

    }

    //我的钱包-提现
    @Override
    public Result<?> CashOut(String token) {
        return Result.OK("接口内容暂未完成");
    }

    //我的钱包-充值
    @Override
    public Result<?> recharge(String token, BigDecimal amount) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);

        try{
            //生成订单信息
            EmployTrade employTrade = new EmployTrade();
            String payNo = IdWorker.getIdStr();//生成订单号
            employTrade.setTitle("金额充值");
            employTrade.setId(payNo);//订单号
            employTrade.setUserId(hanHaiMember.getId());//关联用户id
            employTrade.setAmount(amount);//金额

            //添加交易订单记录
            employTradeService.save(employTrade);

            //吊起微信支付
            BigDecimal price = employTrade.getAmount();//价格
            String productName = employTrade.getTitle();//产品名称

            String s = price.multiply(new BigDecimal(100)).toString();
            int i1 = Double.valueOf(s).intValue();
            Object appOrder =
                    mpWxPayService.createOrder(
                    "购买"+ productName ,
                    "127.0.0.1",
                    employTrade.getId(),
                    i1,
                    employTrade.getId(),
                    hanHaiMember.getAppletOpenid(),
                    employTrade.toString());

            return Result.OK("支付成功",appOrder);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("金额充值失败");
        }
    }

    //开通vip-支付回调
    public Result<?> payNotify(String requestBody){
        WxPayOrderNotifyResult notify = mpWxPayService.notify(requestBody);
        String outTradeNo = notify.getOutTradeNo();
        log.info("支付回调订单号码："+outTradeNo);

        try{
            //查询订单信息
            EmployTrade employTrade = employTradeService.getById(outTradeNo);
            //如果订单存在则修改订单状态
            if (employTrade!=null){
                if("0".equals(employTrade.getStatus())){
                    employTrade.setStatus("1");
                }
                employTradeService.updateById(employTrade);

                //用户钱包金额增加
                HanHaiMember hanHaiMember = hanHaiMemberService.getById(employTrade.getUserId());
                BigDecimal newPrice = hanHaiMember.getPrice().add(employTrade.getAmount());
                hanHaiMember.setPrice(newPrice);
                hanHaiMemberService.updateById(hanHaiMember);

                //添加金额明细记录
                EmployAmountLog amountLog = new EmployAmountLog();
                amountLog.setTitle(employTrade.getTitle());
                amountLog.setAmount(employTrade.getAmount());
                amountLog.setType("0");//收入
                amountLog.setUserId(employTrade.getUserId());
                employAmountLogService.save(amountLog);
            }

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

        return null;
    }

    //我的钱包-金额明细
    @Override
    public Result<?> amountLog(String token, String type, PageBean pageBean) {
        //权限验证
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //返回信息
        String message = "获取金额明细列表失败!";
        //金额明细列表
        Page<EmployAmountLog> pageList = null;
        //分页信息
        Page<EmployAmountLog> page = null;

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

            //金额明细关联用户
            query.orderByDesc(EmployAmountLog::getCreateTime);

            if(null != type){
                query.eq(EmployAmountLog::getType, type);
            }

            //按时间倒序
            query.orderByDesc(EmployAmountLog::getCreateTime);


            //获取工作信息列表
            pageList = query.page(page);

            //判断执行结果
            if(null != pageList){
                message = "金额明细列表信息";
            }else {
                message = "金额明细列表信息为空";
            }

            //返回执行结果
            return Result.OK(message, pageList);

        }catch (Exception e){
            //错误信息打印
            e.printStackTrace();
            return Result.error(message, pageList);
        }
    }
}
