package cn.freemud.demo.manager.coupon;

import cn.freemud.constant.ResponseCodeConstant;
import cn.freemud.demo.entities.CouponDetailBO;
import cn.freemud.demo.entities.GetCouponDetailBO;
import cn.freemud.demo.entities.GetStoreBO;
import cn.freemud.demo.entities.bo.goods.add.MCoffeeAddGoodsBO;
import cn.freemud.demo.manager.store.StoreService;
import cn.freemud.entities.dto.GetAppKeyRequestDto;
import cn.freemud.entities.dto.GetAppKeyResponseDto;
import cn.freemud.entities.dto.GetCouponDetailResponseDto;
import cn.freemud.enums.ResponseResult;
import cn.freemud.redis.RedisCache;
import cn.freemud.service.thirdparty.CardBinClient;
import cn.freemud.service.thirdparty.CouponOnlineClient;
import cn.freemud.utils.LogUtil;
import cn.freemud.utils.RedisUtil;
import com.freemud.card.sdk.comm.Finals;
import com.freemud.card.sdk.comm.SignUtil;
import com.google.common.base.Joiner;
import ma.glasnost.orika.MapperFacade;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

@Service("KgdCouponService")
public class KgdCouponServiceImpl implements CouponService {

    @Autowired
    CouponOnlineClient couponOnlineClient;

    @Autowired
    @Qualifier("KgdStoreService")
    StoreService storeService;

    @Autowired
    CardBinClient cardBinClient;

    @Autowired
    private RedisCache redisCache;

    @Value("${coupon.app.id}")
    private String appid;

    @Resource
    private MapperFacade mapperFacade;

    @Override
    public CouponDetailBO getCouponDetail(GetCouponDetailBO getCouponDetailBO) {
        Map<String, String> map = new TreeMap<String, String>();
        if (StringUtils.isBlank(getCouponDetailBO.getPartnerId()) || StringUtils.isBlank(getCouponDetailBO.getCouponCode())) {
            return null;
        }
        map.put(Finals.CODES, getCouponDetailBO.getCouponCode());
        map.put(Finals.PARTNER_ID, getCouponDetailBO.getPartnerId());
        map.put(Finals.MERCHANT_ID, getCouponDetailBO.getPartnerId());
        map.put(Finals.ACTION, "code.allDetails");
        // 券码接口新增参数：组织机构（多个用英文逗号分离）
        GetStoreBO getStoreBO = new GetStoreBO();
        getStoreBO.setPartnerId(getCouponDetailBO.getPartnerId());
        getStoreBO.setStoreCode(getCouponDetailBO.getStoreCode());

        List<String> orgIds = storeService.getOrgIds(getStoreBO);
        String channelIds = CollectionUtils.isNotEmpty(orgIds) ? Joiner.on(",").join(orgIds) : "";
        map.put(Finals.CHANNEL_CODE_LIST, channelIds);
        String appSecret = getAppSecret(getCouponDetailBO.getPartnerId());
        String sign = SignUtil.createMD5Sign(map, appSecret);
        map.put(Finals.SIGN, sign);
        GetCouponDetailResponseDto responseDto = couponOnlineClient.getCouponDetails(map);
        if (ResponseCodeConstant.RESPONSE_SUCCESS_1.equals(responseDto.getResult())) {
            return convert2CouponDetailBO(responseDto);
        }
        return null;
    }

    private CouponDetailBO convert2CouponDetailBO(GetCouponDetailResponseDto responseDto) {
        CouponDetailBO couponDetailBO = mapperFacade.map(responseDto, CouponDetailBO.class);
        return couponDetailBO;
    }

    public String getAppSecret(String partnerId) {
        // 获取券服务的密钥
        String couponAppSecret = RedisUtil.getCouponAppSecret(partnerId);
        String appSecret = redisCache.getValue(couponAppSecret);
        if (StringUtils.isBlank(appSecret)) {
            GetAppKeyResponseDto getAppKeyResponseDto = cardBinClient.getAppKey(GetAppKeyRequestDto.builder().partnerId(partnerId).appId(appid).build());
            if (Objects.equals(String.valueOf(getAppKeyResponseDto.getStatusCode()), ResponseResult.SUCCESS.getCode())
                    && getAppKeyResponseDto.getData() != null) {
                redisCache.save(couponAppSecret, getAppKeyResponseDto.getData().getAppKey());
                appSecret = getAppKeyResponseDto.getData().getAppKey();
            }
        }
        return appSecret;
    }

}
