package com.bonus.core.customer.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.constant.DelFlagEnum;
import com.bonus.constant.SourceTypeEnum;
import com.bonus.core.auth.mobile.api.AliPayApi;
import com.bonus.core.customer.dto.CustInfoDTO;
import com.bonus.core.customer.service.CustCasualService;
import com.bonus.core.customer.service.CustInfoBusiness;
import com.bonus.core.customer.service.CustInfoService;
import com.bonus.core.customer.vo.CustInfoVo;
import com.bonus.domain.CustCasual;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class CustInfoBusinessImpl implements CustInfoBusiness {
   private static final Logger log = LoggerFactory.getLogger(CustInfoBusinessImpl.class);
   private static final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
   @Resource
   private AliPayApi aliPayApi;
   @Resource
   @Lazy
   private CustCasualService custCasualService;
   @Resource
   @Lazy
   private CustInfoService custInfoService;
   @Override
   public CustInfoVo queryCustInfo(CustInfoDTO custInfoDTO) {
      String alipayContractNum = "";
      if (Objects.nonNull(custInfoDTO) && CharSequenceUtil.isNotBlank(custInfoDTO.getAuthCode())) {
         String openId = this.aliPayApi.paymentCodeDecod(custInfoDTO.getAuthCode());
         CustCasual casual = (CustCasual)this.custCasualService.getOne(Wrappers.<CustCasual>lambdaQuery()
                 .eq(CustCasual::getOpenid, openId)
                 .eq(CustCasual::getSourceType, SourceTypeEnum.ALI_LIFE_CODE.getKey())
                 .eq(CustCasual::getIfDel, DelFlagEnum.DEL_FALSE.key()));
         if (Objects.isNull(casual) || Objects.isNull(casual.getCustId())) {
            throw new ServiceException("用户不存在");
         }

         alipayContractNum = casual.getAlipayContractNum();
         custInfoDTO.setCustId(casual.getCustId());
      }

      CustInfoVo custInfoVo = this.custInfoService.queryCustInfo(custInfoDTO);
      if (ObjectUtil.isNotEmpty(custInfoVo) && ObjectUtil.isNotEmpty(alipayContractNum)) {
         custInfoVo.setAlipayContractNum(alipayContractNum);
      }

      return custInfoVo;
   }
}
