package com.jeequan.jeepay.member.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.ctrls.AbstractCtrl;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.interfaces.IConfigContextQueryService;
import com.jeequan.jeepay.core.model.BaseModel;
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.MchInfo;
import com.jeequan.jeepay.db.entity.MchQrcodeCard;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.member.secruity.JeeMemberDetails;
import com.jeequan.jeepay.service.impl.MchInfoService;
import com.jeequan.jeepay.service.impl.MchQrcodeCardService;
import com.jeequan.jeepay.service.impl.PayOrderService;
import com.jeequan.jeepay.service.impl.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: zx
 * @date: 2023/04/13 16:53
 */
public class CommonCtrl extends AbstractCtrl {

    @Autowired protected PayOrderService payOrderService;
    @Autowired protected IConfigContextQueryService configContextQueryService;
    @Autowired protected SysConfigService sysConfigService;
    @Autowired protected MchQrcodeCardService mchQrcodeCardService;
    @Autowired protected MchInfoService mchInfoService;

    /** 获取当前会员 */
    protected JeeMemberDetails getCurrentUser(){
        return (JeeMemberDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    }

    /** 获取当前会员ID **/
    protected String getCurrentMbrId() {
        return getCurrentUser().getMbrId();
    }

    /** 解析聚合码token，与payment解析一致 **/
    public QRCodeParams tokenConvert(){
        QRCodeParams qrCodeParams = JSON.parseObject(JeepayKit.aesDecode(getToken()), QRCodeParams.class); //解析token
        qrCodeParams.setPageType(getCurrentPageType()); //封装页面类型
        return qrCodeParams;
    }

    public String getToken(){

        String token = request.getHeader(JeepayKit.TOKEN_KEY);
        if(StringUtils.isEmpty(token)) {
            throw new BizException("获取二维码参数失败");
        }
        return token;
    }

    public String getCurrentPageType(){
        String pageType = request.getHeader("pageType");
        if(StringUtils.isEmpty(pageType)) {
            throw new BizException("不支持的客户端");
        }
        return pageType;
    }


    public MchAppConfigContext getQrParamsMchAppConfigContext(QRCodeParams qrCodeParams, boolean checkState){

        /*if(qrCodeParams.getType() == QRCodeParams.TYPE_PAY_ORDER){ // 订单

            PayOrder payOrder = getPayOrder(checkState);
            return configContextQueryService.queryMchInfoAndAppInfo(payOrder.getMchNo(), payOrder.getAppId());

        }else */
        if(qrCodeParams.getType() == QRCodeParams.TYPE_QRC){ // 码牌二维码

            MchQrcodeCard mchQrCode = mchQrcodeCardService.getById(qrCodeParams.getId());
            if (mchQrCode == null || mchQrCode.getQrcState() != CS.YES) {
                throw new BizException("码牌不存在或已停用");
            }
            if (mchQrCode.getBindState() != CS.YES) {
                throw new BizException("请先绑定商户");
            }

            return configContextQueryService.queryMchInfoAndAppInfoV2(mchQrCode.getMchNo(), mchQrCode.getAppId(),null);
        }
        throw new BizException("二维码参数有误");
    }

    public PayOrder getPayOrder(boolean checkState){

        JSONObject qrParams = JSON.parseObject(JeepayKit.aesDecode(getToken())); //解析token
        String payOrderId = qrParams.getString("id");

        PayOrder payOrder = payOrderService.getById(payOrderId);
        if(checkState == false) {
            return payOrder;
        }
        if(payOrder == null) {
            throw new BizException("订单不存");
        }
        if(payOrder.getState() == PayOrder.STATE_SUCCESS) {
            throw new BizException("订单已支付");
        }
        if(payOrder.getState() != PayOrder.STATE_INIT) {
            throw new BizException("订单状态不正确");
        }
        return payOrder;
    }


    /** model 存入商户名称 **/
    public void setMchName(List<? extends BaseModel> modeList) {

        if(modeList == null || modeList.isEmpty()){
            return ;
        }
        ArrayList<String> mchNoList = new ArrayList<>();
        for (BaseModel model:modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String mchNo = json.getString("mchNo");
            mchNoList.add(mchNo);
        }
        List<MchInfo> mchInfoList = mchInfoService.list(MchInfo.gw().select(MchInfo::getMchNo, MchInfo::getMchName).in(MchInfo::getMchNo, mchNoList));
        for (BaseModel model:modeList) {
            JSONObject json = (JSONObject) JSONObject.toJSON(model);
            String mchNo = json.getString("mchNo");

            if(StringUtils.isBlank(mchNo)) {
                continue;
            }

            for (MchInfo info:mchInfoList) {
                if (mchNo.equals(info.getMchNo())) {
                    model.addExt("mchName", info.getMchName());
                }
            }
        }
    }
}
