package com.jeequan.jeepay.member.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.bizcommons.manage.sms.SmsManager;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.QRCodeParams;
import com.jeequan.jeepay.core.model.context.MchAppConfigContext;
import com.jeequan.jeepay.core.utils.JeepayKit;
import com.jeequan.jeepay.db.entity.MchQrcodeCard;
import com.jeequan.jeepay.db.entity.MchStore;
import com.jeequan.jeepay.db.entity.MemberInfo;
import com.jeequan.jeepay.service.impl.MchQrcodeCardService;
import com.jeequan.jeepay.service.impl.MemberInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 查询上游订单， &  补单服务实现类
 *
 * @author terrfly
 * @date 2021/6/8 17:40
 */

@Service
@Slf4j
public class MemberService extends CommonService {

    @Autowired
    private AuthService authService;
    @Autowired
    private MemberInfoService memberInfoService;
    @Autowired
    private MchQrcodeCardService mchQrcodeCardService;
    @Autowired
    private SmsManager smsManager;

    /**
     * 查询商户信息
     */
    public ApiRes getMchInfo(MchAppConfigContext mchAppConfigContext, QRCodeParams qrCodeParams) {
        JSONObject resultJSON = new JSONObject();

        MchQrcodeCard mchQrCode = mchQrcodeCardService.getById(qrCodeParams.getId());
        if (mchQrCode == null || mchQrCode.getQrcState() != CS.YES) {
            throw new BizException("当前静态码不存在或不可用");
        }
        if (mchQrCode.getFixedFlag() == CS.YES) {
            resultJSON.put("amount", mchQrCode.getFixedPayAmount());
            resultJSON.put("fixedFlag", true);
        }

        MchStore mchStore = mchStoreService.getById(mchQrCode.getStoreId());
        if (mchStore != null && StringUtils.isNotBlank(mchStore.getStoreName())) {
            resultJSON.put("mchName", mchStore.getStoreName());
            resultJSON.put("storeLogo", mchStore.getStoreLogo());
        } else {
            resultJSON.put("mchName", mchAppConfigContext.getMchInfo().getMchShortName());
        }


        return ApiRes.ok(resultJSON);
    }

    /**
     * 查询会员信息
     */
    public ApiRes getMemberInfo(String mchNo, String channelUesrId, String pageType) {
        log.info("查询会员信息接口，mchNo={}, channelUesrId={}, pageType={}", mchNo, channelUesrId, pageType);

        MemberInfo memberInfo = memberInfoService.selectOne(mchNo, null, null, channelUesrId, pageType);
        if (memberInfo == null) {
            return ApiRes.ok();
        }

        return ApiRes.ok(authService.authByMbrId(memberInfo.getMbrId(), null));
    }

    /**
     * 会员绑定手机号
     */
    public ApiRes mbrTelBind(MemberInfo memberInfo, String code, String channelUesrId, String pageType) {

        String mbrTel = memberInfo.getMbrTel();

        // 校验短信验证码
        smsManager.checkSmsVercodeThrowBizEx(mbrTel, code, CS.SMS_TYPE_API_ENUM.TYPE_MBR_TEL_BIND);

        if (StringUtils.equalsAny(pageType, QRCodeParams.PAGE_TYPE_ALIPAY_H5, QRCodeParams.PAGE_TYPE_ALIPAY_LITE)) {
            memberInfo.setAliUserId(channelUesrId);
            memberInfo.setMbrName("支付宝用户" + getTel4Last(memberInfo.getMbrTel()));

        } else if (StringUtils.equals(pageType, QRCodeParams.PAGE_TYPE_WECHAT_H5)) {
            memberInfo.setWxMpOpenId(channelUesrId);
            memberInfo.setMbrName("微信用户" + getTel4Last(memberInfo.getMbrTel()));

        } else if (StringUtils.equals(pageType, QRCodeParams.PAGE_TYPE_WECHAT_LITE)) {
            memberInfo.setWxLiteOpenId(channelUesrId);
            memberInfo.setMbrName("微信用户" + getTel4Last(memberInfo.getMbrTel()));

        } else if (StringUtils.equals(pageType, QRCodeParams.PAGE_TYPE_YSFPAY_H5)) {
            memberInfo.setYsfUserId(channelUesrId);
            memberInfo.setMbrName("云闪付用户" + getTel4Last(memberInfo.getMbrTel()));

        } else {
            throw new BizException("不支持的客户端");
        }

        // 手机号查询会员，若手机号已绑定，将更新会员的channelUserId
        MemberInfo dbRecord = memberInfoService.selectOne(memberInfo.getMchNo(), null, mbrTel, null, null);
        if (dbRecord != null) {
            memberInfo.setMbrId(dbRecord.getMbrId());
            memberInfo.setMbrName(null); // 不更新会员名称
            memberInfo.setSafeKey(null);
        } else {
            memberInfo.setMbrId("B" + DateUtil.currentSeconds());
            memberInfo.setSafeKey(JeepayKit.genAccountSafeKey(memberInfo.getMbrId(), 0L));
            memberInfo.setAvatarUrl(getMemberAvatarDefault());
        }

        boolean result = memberInfoService.saveOrUpdate(memberInfo);
        if (!result) {
            return ApiRes.customFail("操作失败");
        }

        return ApiRes.ok(authService.authByMbrId(memberInfo.getMbrId(), null));
    }

    /**
     * 手机尾号4位
     **/
    public String getTel4Last(String memberTel) {
        if (StringUtils.isEmpty(memberTel)) {
            return null;
        }
        return memberTel.substring(memberTel.length() - 4);
    }


}
