package com.jeequan.jeepay.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeequan.jeepay.core.model.DBAppPushConfig;
import com.jeequan.jeepay.db.entity.MchAppPushInfo;
import com.jeequan.jeepay.service.mapper.MchAppPushInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 商户app推送设备表 服务实现类
 * </p>
 *
 * @author [mybatis plus generator]
 * @since 2022-02-17
 */
@Slf4j
@Service
public class MchAppPushInfoService extends ServiceImpl<MchAppPushInfoMapper, MchAppPushInfo> {

    @Autowired SysConfigService sysConfigService;


    public void saveMchCid(JSONObject reqParams, String mchNo, Long userId){
        // 报错 不影响正常业务
        String logPrefix = "【更新uniPush推送cid】";

        try {
            DBAppPushConfig appPushConfig = sysConfigService.getDBAppPushConfig();
            if (appPushConfig.getUniPushVersion() == null) {
                log.error("{}系统未配置app推送", logPrefix);
                return;
            }

            log.info("{}系统配置uniPush版本：{}，请求参数：{}", logPrefix, appPushConfig.getUniPushVersion(), reqParams.toJSONString());

            // 版本只有1，2，cid1对应unipush1.0，cid2对应2.0
            String cid;
            String orgCid = null;  // 原始cid，小程序端cid会更换，小程序端请求参数携带原始cid则更新，否则新增
            MchAppPushInfo mchAppPushInfo = null;
            if (appPushConfig.getUniPushVersion() == MchAppPushInfo.UNI_PUSH_VERSION_1) {
                cid = reqParams.getString("cid1"); // push1.0的cid

                // 查询DB
                mchAppPushInfo = this.getOne(MchAppPushInfo.gw()
                        .eq(MchAppPushInfo::getCid, cid)
                        .eq(MchAppPushInfo::getCidType, MchAppPushInfo.PUSH_CID_TYPE_APP)
                        .eq(MchAppPushInfo::getUniPushVersion, MchAppPushInfo.UNI_PUSH_VERSION_1)
                );

            }else if (appPushConfig.getUniPushVersion() == MchAppPushInfo.UNI_PUSH_VERSION_2) {
                cid = reqParams.getString("cid2"); // push2.0的cid
                String cidType = reqParams.getString("cidType"); // APP端：app_plus，小程序端：mp_weixin

                // 微信小程序端
                if (MchAppPushInfo.PUSH_CID_TYPE_WX.equals(cidType)) {
                    orgCid = reqParams.getString("orgCid"); // 原始cid，小程序端cid会更换，携带原始cid则更新，否则新增

                    // 根据原始cid查询
                    if (StringUtils.isNotBlank(orgCid)) {
                        mchAppPushInfo = this.getOne(MchAppPushInfo.gw()
                                .eq(MchAppPushInfo::getCid, orgCid)
                                .eq(MchAppPushInfo::getCidType, MchAppPushInfo.PUSH_CID_TYPE_WX)
                                .eq(MchAppPushInfo::getUniPushVersion, MchAppPushInfo.UNI_PUSH_VERSION_2)
                        );
                    }
                }
                if (mchAppPushInfo == null) {
                    mchAppPushInfo = this.getOne(MchAppPushInfo.gw()
                            .eq(MchAppPushInfo::getCid, cid)
                            .eq(MchAppPushInfo::getUniPushVersion, MchAppPushInfo.UNI_PUSH_VERSION_2)
                    );
                }

            }else {
                log.error("{}系统uniPush版本未配置", logPrefix);
                return;
            }

            if (StringUtils.isBlank(cid)) {
                log.error("{}cid为空", logPrefix);
                return;
            }

            if(mchAppPushInfo != null) {
                MchAppPushInfo updateRecord = new MchAppPushInfo();
                updateRecord.setMchNo(mchNo);
                updateRecord.setSysUserId(userId);
                if (StringUtils.isNotBlank(orgCid)) {
                    updateRecord.setCid(cid);
                }

                this.update(updateRecord, new LambdaUpdateWrapper<MchAppPushInfo>()
                        .eq(MchAppPushInfo::getCid, StringUtils.isNotBlank(orgCid) ? orgCid : cid)
                        .eq(MchAppPushInfo::getUniPushVersion, appPushConfig.getUniPushVersion())
                );
            }else{
                MchAppPushInfo newRecord = new MchAppPushInfo();
                newRecord.setMchNo(mchNo);
                newRecord.setSysUserId(userId);
                newRecord.setCid(cid);
                newRecord.setCidType(StringUtils.defaultString(reqParams.getString("cidType"), MchAppPushInfo.PUSH_CID_TYPE_APP));
                newRecord.setUniPushVersion(appPushConfig.getUniPushVersion());
                save(newRecord);
            }

        } catch (Exception e) {
            log.error("", e);
        }
    }

}
