package org.jeecg.modules.apiservice.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.apiBean.*;
import org.jeecg.modules.apiUtils.printUtil;
import org.jeecg.modules.apiservice.InfoApiService;

import org.jeecg.modules.cheerConf.entity.CheerConf;
import org.jeecg.modules.cheerConf.service.ICheerConfService;
import org.jeecg.modules.cheerRecharge.entity.CheerRecharge;
import org.jeecg.modules.cheerRecharge.service.ICheerRechargeService;
import org.jeecg.modules.cheerWater.entity.CheerWater;
import org.jeecg.modules.cheerWater.service.ICheerWaterService;

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.Date;
import java.util.List;

@Service
public class InfoApiServiceImpl implements InfoApiService {

    //缓存记录
    @Resource
    private RedisUtil redisUtil;
    //权限验证
    @Resource
    private ShiroRealm shiroRealm;
    //获取个人信息接口
    @Resource
    private IHanHaiMemberService hanHaiMemberService;






    //加油小程序
    @Resource
    private ICheerWaterService cheerWaterService;
    @Resource
    private ICheerConfService cheerConfService;
    @Resource
    private ICheerRechargeService cheerRechargeService;
    //支付接口
    @Autowired
    private MpWxPayService mpWxPayService;





    //获取个人信息接口
    @Override
    public Result<?> getInfo(String token){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        return Result.OK("查询成功", hanHaiMember);
    }

    //修改个人信息接口
    @Override
    public Result<?> updateInfo(String token, HanHaiMember bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        bean.setId(hanHaiMember.getId());
        hanHaiMemberService.updateById(bean);
        return Result.OK("修改成功");
    }






    /********************************************************************************************/
    /**************************************加油小程序相关*****************************************/

    //加油小程序-获取订单流水信息
    @Override
    public Result<?> getOrderWaterPage(String token, OrderWaterPageBean bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        Page<CheerWater> page = new Page<CheerWater>(bean.getPageNo(), bean.getPageSize());
        Page<CheerWater> page1 = cheerWaterService.lambdaQuery()
                .eq(CheerWater::getUserId, hanHaiMember.getId())
                .eq(CheerWater::getState, "1")
                .orderByDesc(CheerWater::getCreateTime)
                .page(page);

        return Result.OK("加油流水",page1);
    }


    //加油小程序-用户输入支付创建支付订单并且支付
    @Override
    public Result<?> createOrderPay(String token, OrderPayBean bean){
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiOpenId(token);
        //判断输入金额是否为空
        if(bean.getMoney() == null){
            return Result.error("支付金额不能为空");
        }
        //查询当前折扣
        CheerConf one = cheerConfService.lambdaQuery()
                .eq(CheerConf::getKeyValue, "preferential")
                .one();
        //判断折扣是否为空
        if(one == null){
            return Result.error("当前没有折扣");
        }
        //得到折扣值转为BigDecimal类型
        BigDecimal discount = new BigDecimal(one.getKeyCentent());
        if(bean.getMoney().compareTo(new BigDecimal(0)) == 0){
            return Result.error("支付金额不能为0");
        }
        if(bean.getMoney().compareTo(new BigDecimal(0)) == -1){
            return Result.error("支付金额不能为负数");
        }
        BigDecimal oldMoney = bean.getMoney();
        //支付金额乘折扣保留两位小数
        BigDecimal money = bean.getMoney().divide(discount).setScale(2, BigDecimal.ROUND_HALF_UP);


        //根据配置信息获得当前
        CheerConf title = cheerConfService.lambdaQuery()
                .eq(CheerConf::getKeyValue,"title")
                .one();


        //创建订单流水
        CheerWater cheerWater = new CheerWater();
        cheerWater.setUserId(hanHaiMember.getId());
        cheerWater.setOldPrice(money);
        cheerWater.setPrice(oldMoney);
        cheerWater.setState("0");
        cheerWater.setCreateTime(new Date());
        cheerWater.setName(title.getKeyCentent());
        cheerWater.setUserHead(hanHaiMember.getHeadImage());
        cheerWaterService.save(cheerWater);



        //吊起微信支付
        String s = bean.getMoney().multiply(new BigDecimal(100)).toString();
        int i1 = Double.valueOf(s).intValue();
        Object appOrder = mpWxPayService.createOrderGo(
                "购买"+cheerWater.getName() ,
                "127.0.0.1",
                cheerWater.getId(),
                i1,
                cheerWater.getId(),
                hanHaiMember.getAppletOpenid(),
                cheerWater.toString());



        return Result.OK("支付成功",appOrder);
    }










    //获取充值套餐列表
    @Override
    public Result<?> getRechargePage(OrderRechargeBean bean) {
        Page<CheerRecharge> page = new Page<>(bean.getPageNo(),bean.getPageSize());
        Page<CheerRecharge> page1 = cheerRechargeService
                .lambdaQuery()
                .orderByDesc(CheerRecharge::getCreateTime)
                .page(page);

        return Result.OK("充值套餐",page1);
    }

    //获取配置信息：折扣、客户电话、客户微信
    @Override
    public Result<?> getConfig(String keyValue) {

        CheerConf one = cheerConfService.lambdaQuery()
                .eq(CheerConf::getKeyValue, keyValue)
                .one();
        return Result.OK("配置信息", one);
    }



    //支付回调
    @Override
    public Object createNotify(String requestBody){
        WxPayOrderNotifyResult notify = mpWxPayService.notify(requestBody);

        String outTradeNo = notify.getOutTradeNo();

        //开始处理业务逻辑
        CheerWater  byId = cheerWaterService.getById(outTradeNo);

        if(byId!=null){
            if(!byId.getState().equals("1")){
                cheerWaterService.lambdaUpdate()
                        .set(CheerWater::getState,"1")
                        .eq(CheerWater::getId,outTradeNo)
                        .update();

                //根据流水中的用户标识查询用户信息
                HanHaiMember hanHaiMember = hanHaiMemberService.getById(byId.getUserId());

                //根据配置信息获得当前单价
                CheerConf price = cheerConfService.lambdaQuery()
                        .eq(CheerConf::getKeyValue,"price")
                        .one();

                //根据配置信息获得当前
                CheerConf title = cheerConfService.lambdaQuery()
                        .eq(CheerConf::getKeyValue,"title")
                        .one();

                //获取配置中的打印次数
                CheerConf num = cheerConfService.lambdaQuery()
                        .eq(CheerConf::getKeyValue,"num")
                        .one();



                //拼接打印信息
                String content = printUtil.spellMessage(hanHaiMember.getNickName(),byId.getOldPrice().toString(),byId.getPrice().toString(),title.getKeyCentent(),price.getKeyCentent());

                //客户要求打印两次
                for (int i = 0; i < Integer.parseInt(num.getKeyCentent()); i++){
                    printUtil.printBill(content);
                }


            }
        }
        return null;
    }

}
