package org.jeecg.modules.xcx.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.shiro.ShiroRealm;
import org.jeecg.modules.bean.HttpConf;
import org.jeecg.modules.hanHaiMember.entity.HanHaiMember;
import org.jeecg.modules.hanHaiMember.resp.MyUserResp;
import org.jeecg.modules.hanHaiMember.resp.ShopIndexResp;
import org.jeecg.modules.hanHaiMember.service.IHanHaiMemberService;
import org.jeecg.modules.hotelbalancelog.entity.HotelBalanceLog;
import org.jeecg.modules.hotelbalancelog.service.IHotelBalanceLogService;
import org.jeecg.modules.hotelleaselog.service.IHotelLeaseLogService;
import org.jeecg.modules.hotelmemberaccount.entity.HotelMemberAccount;
import org.jeecg.modules.hotelmemberaccount.service.IHotelMemberAccountService;
import org.jeecg.modules.hotelshop.entity.HotelShop;
import org.jeecg.modules.hotelshop.service.IHotelShopService;
import org.jeecg.modules.xcx.shop.req.*;
import org.jeecg.modules.xcx.shop.service.IShopService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Service
public class ShopServiceImpl implements IShopService {

    @Resource
    private ShiroRealm shiroRealm;
    @Resource
    private IHotelShopService hotelShopService;
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private IHotelBalanceLogService hotelBalanceLogService;
    @Resource
    private IHotelMemberAccountService hotelMemberAccountService;
    @Resource
    private IHanHaiMemberService hanHaiMemberService;
    @Resource
    private HttpConf httpConf;
    @Resource
    private IHotelLeaseLogService hotelLeaseLogService;
    /**
     * 微信公众号-appid
     */
    @Value("${weixin.mpAppId}")
    private String mpAppId;

    /**
     * 微信公众号-appSecret
     */
    @Value("${weixin.mpAppSecret}")
    private String mpAppSecret;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> applyShop(ApplyShopReq applyShopReq) {
        Integer n = (Integer) redisUtil.get("apply:shop:"+applyShopReq.getToken());
        if(n != null){
            throw new JeecgBootException("请勿重复提交");
        }
        redisUtil.set("apply:shop:"+applyShopReq.getToken(),1,3);
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(applyShopReq.getToken());
        if(StringUtils.isBlank(applyShopReq.getName())){
            throw new JeecgBootException("请填写店铺名称");
        }
        if(StringUtils.isBlank(applyShopReq.getUserName())){
            throw new JeecgBootException("请填写您的姓名");
        }
        if(StringUtils.isBlank(applyShopReq.getPhone())){
            throw new JeecgBootException("请填写联系方式");
        }
        if(StringUtils.isBlank(applyShopReq.getLatitude()) || StringUtils.isBlank(applyShopReq.getLongitude())){
            throw new JeecgBootException("请选择您的所在地区");
        }
        if (StringUtils.isBlank(applyShopReq.getAddress())){
            throw new JeecgBootException("请填写地址");
        }
        if(StringUtils.isBlank(applyShopReq.getPassword())){
            throw new JeecgBootException("请输入密码");
        }
        HotelShop hotelShop = hotelShopService.lambdaQuery()
                .eq(HotelShop::getDelFlag, 0)
                .eq(HotelShop::getUserId, hanHaiMember.getId())
                .in(HotelShop::getStatus,0,1)
                .one();
        if(hotelShop != null){
            throw new JeecgBootException("您已申请过店铺，请勿重复申请");
        }

        String salt = oConvertUtils.randomGen(8);
        String encrypt = PasswordUtil.encrypt(applyShopReq.getPassword(), applyShopReq.getPhone(), salt);
        HanHaiMember hanHaiMember1 = new HanHaiMember();
        hanHaiMember1.setId(hanHaiMember.getId());
        hanHaiMember1.setPhone(applyShopReq.getPhone());
        hanHaiMember1.setPassword(encrypt);
        hanHaiMember1.setPasswordSalt(salt);
        hanHaiMemberService.updateById(hanHaiMember1);

        HotelShop hotelShop1 = new HotelShop();
        hotelShop1.setUserId(hanHaiMember.getId());
        hotelShop1.setName(applyShopReq.getName());
        hotelShop1.setUserName(applyShopReq.getUserName());
        hotelShop1.setPhone(applyShopReq.getPhone());
        hotelShop1.setLatitude(applyShopReq.getLatitude());
        hotelShop1.setLongitude(applyShopReq.getLongitude());
        hotelShop1.setAddress(applyShopReq.getAddress());
        hotelShop1.setStatus(0);
        hotelShop1.setOldId(hanHaiMember.getId());
        hotelShop1.setPic(applyShopReq.getPic());
        hotelShopService.save(hotelShop1);

        return Result.OK();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> applyWithdrawal(ApplyWithdrawalReq applyWithdrawalReq) {
        Integer n = (Integer) redisUtil.get("apply:withdrawal:"+applyWithdrawalReq.getToken());
        if(n != null){
            throw new JeecgBootException("请勿重复提交");
        }
        redisUtil.set("apply:withdrawal:"+applyWithdrawalReq.getToken(),1,3);
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(applyWithdrawalReq.getToken());
        HotelMemberAccount hotelMemberAccount = hotelMemberAccountService.lambdaQuery()
                .eq(HotelMemberAccount::getDelFlag, 0)
                .eq(HotelMemberAccount::getUserId, hanHaiMember.getId())
                .one();
        if(applyWithdrawalReq.getMoney() == null || applyWithdrawalReq.getMoney().compareTo(BigDecimal.ZERO) <= 0){
            throw new JeecgBootException("请填写正确的提现金额");
        }
        if(applyWithdrawalReq.getMoney().compareTo(hotelMemberAccount.getShopBalance()) == 1){
            throw new JeecgBootException("提现金额不能大于余额");
        }
        if(StringUtils.isBlank(applyWithdrawalReq.getName())){
            throw new JeecgBootException("请填写姓名");
        }
        if(StringUtils.isBlank(applyWithdrawalReq.getPhone())){
            throw new JeecgBootException("请填写电话");
        }
        if(StringUtils.isBlank(applyWithdrawalReq.getBankCard())){
            throw new JeecgBootException("请填写银行卡号");
        }
        if(StringUtils.isBlank(applyWithdrawalReq.getBankAddress())){
            throw new JeecgBootException("请填写银行卡支行地址");
        }

        BigDecimal money = hotelMemberAccount.getShopBalance().subtract(applyWithdrawalReq.getMoney());
        HotelMemberAccount hotelMemberAccount1 = new HotelMemberAccount();
        hotelMemberAccount1.setId(hotelMemberAccount.getId());
        hotelMemberAccount1.setShopBalance(money);
        hotelMemberAccountService.updateById(hotelMemberAccount1);

        HotelBalanceLog hotelBalanceLog = new HotelBalanceLog();
        hotelBalanceLog.setTitle("佣金提现");
        hotelBalanceLog.setUserId(hanHaiMember.getId());
        hotelBalanceLog.setBalance(applyWithdrawalReq.getMoney());
        hotelBalanceLog.setUserBalance(hotelMemberAccount.getShopBalance());
        hotelBalanceLog.setType(1);
        hotelBalanceLog.setStatus(0);
        hotelBalanceLog.setPayType(0);
        hotelBalanceLog.setName(applyWithdrawalReq.getName());
        hotelBalanceLog.setPhone(applyWithdrawalReq.getPhone());
        hotelBalanceLog.setBankCard(applyWithdrawalReq.getBankCard());
        hotelBalanceLog.setBankAddress(applyWithdrawalReq.getBankAddress());
        hotelBalanceLogService.save(hotelBalanceLog);
        return Result.OK();
    }

    @Override
    public Result<?> withdrawalPage(WithdrawalPageReq withdrawalPageReq) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(withdrawalPageReq.getToken());
        Page<HotelBalanceLog> page = new Page<>(withdrawalPageReq.getPageNo(), withdrawalPageReq.getPageSize());
        Page<HotelBalanceLog> hotelBalanceLogPage = hotelBalanceLogService.lambdaQuery()
                .eq(HotelBalanceLog::getDelFlag, 0)
                .eq(HotelBalanceLog::getUserId, hanHaiMember.getId())
                .eq(HotelBalanceLog::getType, withdrawalPageReq.getType())
                .orderByDesc(HotelBalanceLog::getCreateTime)
                .page(page);

        return Result.OK(hotelBalanceLogPage);
    }

    @Override
    public Result<?> myUser(MyUserReq myUserReq) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(myUserReq.getToken());
        HotelShop hotelShop = hotelShopService.lambdaQuery()
                .eq(HotelShop::getDelFlag, 0)
                .eq(HotelShop::getUserId, hanHaiMember.getId())
                .eq(HotelShop::getStatus, 1)
                .one();
        if(hotelShop == null){
            return Result.OK();
        }
        Page<MyUserResp> page = new Page<>(myUserReq.getPageNo(), myUserReq.getPageSize());
        IPage<MyUserResp> myUser = hanHaiMemberService.getMyUser(page, hotelShop.getId());
        return Result.OK(myUser);
    }

    @Override
    public Result<?> shopIndex(String token) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        HotelShop hotelShop = hotelShopService.lambdaQuery()
                .eq(HotelShop::getDelFlag, 0)
                .eq(HotelShop::getUserId, hanHaiMember.getId())
                .eq(HotelShop::getStatus, 1)
                .one();
        if(hotelShop == null){
            return Result.OK();
        }
        ShopIndexResp shopIndex = hanHaiMemberService.getShopIndex(hotelShop.getUserId(), hotelShop.getId());
        return Result.OK(shopIndex);
    }

    @Override
    public Result<?> getShop(String token) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(token);
        HotelShop hotelShop = hotelShopService.lambdaQuery()
                .eq(HotelShop::getDelFlag, 0)
                .eq(HotelShop::getId, hanHaiMember.getShopId())
                .eq(HotelShop::getStatus, 1)
                .one();
        if(hotelShop == null){
            return Result.OK();
        }
        return Result.OK(hotelShop);
    }


    @Override
    public Result<?> editShopJobTime(EditShopJobTimeReq editShopJobTimeReq) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(editShopJobTimeReq.getToken());
        HotelShop hotelShop = hotelShopService.lambdaQuery()
                .eq(HotelShop::getDelFlag, 0)
                .eq(HotelShop::getUserId, hanHaiMember.getId())
                .one();
        if(hotelShop == null){
            throw new JeecgBootException("未查询到店铺");
        }
        if(StringUtils.isBlank(editShopJobTimeReq.getTime())){
            throw new JeecgBootException("请输入正确的营业时间");
        }
        HotelShop hotelShop1 = new HotelShop();
        hotelShop1.setId(hotelShop.getId());
        hotelShop1.setJobTime(editShopJobTimeReq.getTime());
        hotelShopService.updateById(hotelShop1);

        return Result.OK();
    }

    @Override
    public Result<?> bindWx(BindWxReq bindWxReq) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(bindWxReq.getToken());
        if(StringUtils.isNotBlank(hanHaiMember.getAppletOpenid())){
            throw new JeecgBootException("您已绑定过微信");
        }
        if (org.apache.commons.lang.StringUtils.isBlank(bindWxReq.getCode())) {
            throw new JeecgBootException("小程序code为空");
        }
        String loginUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=" + mpAppId + "&secret=" + mpAppSecret+ "&js_code=" + bindWxReq.getCode() + "&grant_type=authorization_code";
        //使用工具类
        JSONObject json_test = httpConf.getJSONObject(loginUrl);
        String wxOpenid = json_test.getString("openid");
        String sessionKey = json_test.getString("session_key");
        if (org.apache.commons.lang.StringUtils.isBlank(wxOpenid)) {
            throw new JeecgBootException("未获取到openid");
        }
        HanHaiMember hanHaiMember2 = hanHaiMemberService.lambdaQuery()
                .eq(HanHaiMember::getAppletOpenid, wxOpenid)
                .one();
        if(hanHaiMember2 != null){
            throw new JeecgBootException("该微信已注册，无法绑定");
        }
        HanHaiMember hanHaiMember1 = new HanHaiMember();
        hanHaiMember1.setId(hanHaiMember.getId());
        hanHaiMember1.setAppletOpenid(wxOpenid);
        hanHaiMemberService.updateById(hanHaiMember1);
        return Result.OK();
    }

    @Override
    public Result<?> editShopInfo(EditShopInfoReq editShopInfoReq) {
        HanHaiMember hanHaiMember = shiroRealm.checkUserTokenIsEffectHanHaiAccount(editShopInfoReq.getToken());

        HotelShop hotelShop = hotelShopService.lambdaQuery()
                .eq(HotelShop::getDelFlag, 0)
                .eq(HotelShop::getUserId, hanHaiMember.getId())
                .one();

        HotelShop hotelShop1 = new HotelShop();
        hotelShop1.setId(hotelShop.getId());
        if(StringUtils.isNotBlank(editShopInfoReq.getPic())){
            hotelShop1.setPic(editShopInfoReq.getPic());
        }
        if(StringUtils.isNotBlank(editShopInfoReq.getName())){
            hotelShop1.setName(editShopInfoReq.getName());
        }

        hotelShopService.updateById(hotelShop1);

        return Result.OK();
    }


}
