package com.bohuikeji.delivery.backstage.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bohuikeji.delivery.backstage.constants.WxAppEm;
import com.bohuikeji.delivery.backstage.entity.AliPayConfig;
import com.bohuikeji.delivery.backstage.entity.TCustomer;
import com.bohuikeji.delivery.backstage.entity.TOrder;
import com.bohuikeji.delivery.backstage.entity.baidu.BaiDuConfig;
import com.bohuikeji.delivery.backstage.entity.bytedance.ByteConfig;
import com.bohuikeji.delivery.backstage.entity.kuaishou.KuaiShouConfig;
import com.bohuikeji.delivery.backstage.entity.wx.TWxUser;
import com.bohuikeji.delivery.backstage.mapper.TWxUserMapper;
import com.bohuikeji.delivery.backstage.pay.AliPay;
import com.bohuikeji.delivery.backstage.pay.BaiduPay;
import com.bohuikeji.delivery.backstage.pay.BytePay;
import com.bohuikeji.delivery.backstage.pay.KuaiShouPay;
import com.bohuikeji.delivery.backstage.service.IWxUserService;
import com.bohuikeji.delivery.backstage.util.WxUtils;
import com.bohuikeji.frame.module.admin.base.ServiceImplBase;
import com.bohuikeji.frame.module.admin.entity.back.APIEntity;
import com.bohuikeji.frame.module.admin.utils.WxAppLoginUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author 孙劲辉
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WxUserServiceImpl extends ServiceImplBase<TWxUserMapper, TWxUser> implements IWxUserService {

    @Autowired
    IWxUserService wxUserService;
    /**
     * 查询某个骑手微信应用授权信息
     *
     * @param userId 骑手ID
     * @param type
     * @return
     */
    @Override
    public TWxUser getUserByType(Integer userId, String type, WxAppEm app) {
        return getOne(new QueryWrapper<TWxUser>()
                .eq("user_id",userId)
                .eq("user_type", type)
                .eq("wx_app_id",app.getAppId()),false);
    }

    @Override
    public TWxUser getUserByLogin(Integer userId,String openId, String type, WxAppEm app) {
        return getOne(new QueryWrapper<TWxUser>()
                .eq("wx_user_openid",openId)
                .eq("user_type", type)
                .eq("wx_app_id",app.getAppId()),false);
    }

    /**
     * 获取公众自动授权链接
     * <p>授权成功后用户授权信息保存于t_wx_user表中</p>
     * @param userId 用户ID
     * @param userType 用户类型
     * @param path 跳转页面路径
     * @param gzh 公众号APP
     * @return
     */
    @Override
    public String getGzhAutoUrl(Integer userId, String userType, String path, WxAppEm gzh) {
        //微信授权链接
        String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid={}&redirect_uri={}&response_type=code&scope=snsapi_base&state=test#wechat_redirect";
        //回调链接
        String redirectUri="";
        try {
            redirectUri= URLEncoder.encode(StrUtil.format("https://wx.aouth.tcjskd.com/delivery/views/open/wx/oauth/?&appid={}&id={}&type={}&path={}&evn=os",gzh.getAppId(),userId,userType,path),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("微信公众自动授权失败：地址解码错误！",e);
            e.printStackTrace();
            return null;
        }
        return StrUtil.format(url, WxAppEm.GZH_TCJS.getAppId(),redirectUri);
    }

    @Override
    public TWxUser saveLoginWxUser(JSONObject res,WxAppEm app,Integer courierId) {
        TWxUser wxUser=new TWxUser();
        wxUser.setUserType(WxAppEm.WX_USER_TYPE_COURIER);
        wxUser.setUserId(Long.valueOf(courierId));
        wxUser.setWxAppType(app.getType());
        wxUser.setWxAppId(app.getAppId());
        wxUser.setWxAppName(app.getName());
        wxUser.setWxUserOpenid(res.getString("openid"));
        wxUser.setWxUserUnionid(res.getString("unionid"));
        wxUser.setWxUserSessionkey(res.getString("session_key"));
        wxUserService.saveOrUpdate(wxUser);
        return null;
    }


    /**
     * 快手支付宝授权绑定账户
     * @param order
     * @return
     */
    @Override
        public TWxUser saveWxUser(TOrder order) {
        TWxUser wxUser = new TWxUser();
        String openId=null;
        if("快手小程序".equals(order.getOrderChannel())){
            openId = KuaiShouPay.getOpenId(order.getCode());
            wxUser.setWxAppId(KuaiShouConfig.App_ID);
            wxUser.setWxAppType("KUAISHOU");
            wxUser.setWxAppName("客户端小程序（快手）");
        }
        if("支付宝小程序".equals(order.getOrderChannel())){
            try {
                openId = AliPay.getUserId(order.getCode()).getString("user_id");
                wxUser.setWxAppId(AliPayConfig.appID);
                wxUser.setWxAppType("ALICLIENT");
                wxUser.setWxAppName("客户端小程序（支付宝）");
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
        if(openId == null){
            return null;
        }
        log.info("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@openId：[{}]",openId);
        wxUser.setUserId(Long.valueOf(order.getPlayerId()));
        wxUser.setUserType(WxAppEm.WX_USER_TYPE_CUSTOMER);
        wxUser.setWxUserOpenid(openId);
        save(wxUser);
        return wxUser;
    }

    @Override
    public TWxUser saveCusOrWxUser(String grantCode, String loginType, TCustomer customer) throws AlipayApiException {
        TWxUser wxUser = new TWxUser();
        switch (loginType){
            case "APP":
                wxUser.setWxUserOpenid(WxAppLoginUtils.getWxChatLogin(grantCode));
                wxUser.setWxAppId(AliPayConfig.appID);
                wxUser.setWxAppType("WXAPP");
                wxUser.setWxAppName("客户端APP（微信）");break;
            case "JSAPI":
                wxUser.setWxUserOpenid(WxAppLoginUtils.getWxMpLogin(grantCode).getString("openId"));
                wxUser.setWxAppId(AliPayConfig.appID);
                wxUser.setWxAppType("WXCLIENT");
                wxUser.setWxAppName("客户端小程序（微信）");break;
            case "alipay":
                wxUser.setWxUserOpenid(AliPay.getUserInfo(grantCode).getUserId());
                wxUser.setWxAppId(AliPayConfig.appID);
                wxUser.setWxAppType("ALIAPP");
                wxUser.setWxAppName("客户端APP（支付宝）");break;
            case "aliClient":
                wxUser.setWxUserOpenid(AliPay.getUserId(grantCode).getString("user_id"));
                wxUser.setWxAppId(AliPayConfig.appID);
                wxUser.setWxAppType("ALICLIENT");
                wxUser.setWxAppName("客户端小程序（支付宝）");break;
            case "baidu":
                wxUser.setWxUserOpenid(BaiduPay.getBaiDuOpenId(grantCode));
                wxUser.setWxAppId(BaiDuConfig.App_ID);
                wxUser.setWxAppType("BAIDU");
                wxUser.setWxAppName("客户端小程序（百度）");break;
            case "douyin":
                wxUser.setWxUserOpenid(BytePay.getDouYinOpenId(grantCode));
                wxUser.setWxAppId(ByteConfig.App_ID);
                wxUser.setWxAppType("DOUYIN");
                wxUser.setWxAppName("客户端小程序（抖音）");break;
            case "kuaiShou":
                wxUser.setWxUserOpenid(KuaiShouPay.getOpenId(grantCode));
                wxUser.setWxAppId(KuaiShouConfig.App_ID);
                wxUser.setWxAppType("KUAISHOU");
                wxUser.setWxAppName("客户端小程序（快手）");break;
        }
        wxUser.setUserId(Long.valueOf(customer.getCustomerId()));
        wxUser.setUserType(WxAppEm.WX_USER_TYPE_CUSTOMER);
        save(wxUser);
        return wxUser;
    }

    /*@Override
    public boolean getBinding(TOrder tOrder, TCustomer customer) {
        if("aliClient".equals(tOrder.getType())){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",customer.getCustomerId()).eq("wx_app_type","ALICLIENT"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
        }
        if("kuaiShou".equals(tOrder.getType())){
            TWxUser wxUser = wxUserService.getOne(new QueryWrapper<TWxUser>().eq("user_id",customer.getCustomerId()).eq("wx_app_type","KUAISHOU"));
            if(wxUser == null){
                return APIEntity.fail("请用户授权");
            }
            openId = wxUser.getWxUserOpenid();
        }
        return false;
    }*/
}
