package cn.pluss.platform.ys.impl;

import cn.pluss.platform.channel.BaseMerchantAuditService;
import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.entity.MerchantChannelImg;
import cn.pluss.platform.entity.MerchantImage;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchantChannelImg.MerchantChannelImgService;
import cn.pluss.platform.util.Base64Util;
import cn.pluss.platform.util.FileUtil;
import cn.pluss.platform.util.LogExceptionUtils;
import cn.pluss.platform.yinsheng.RespEntity;
import cn.pluss.platform.ys.YSConstants;
import cn.pluss.platform.ys.YsConfig;
import cn.pluss.platform.ys.YsService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

/**
 * 上传图片方法实现
 * @author djh
 */
@Slf4j
public abstract class AbYsImgUploadService extends BaseMerchantAuditService {

    @Autowired
    protected YsService ysService;

    @Autowired
    protected RestTemplate restTemplate;

    @Autowired
    protected MerchantChannelImgService channelImgService;

    /**
     * 银盛的通道，进件失败一次，就得重新上传一次图片，所以这里将商户的外部商户号存储起来
     * @param merchantImage 图片信息
     */
    @Override
    public void imageUpload(MerchantImage merchantImage) {
        val merchantChannelImg = new MerchantChannelImg()
                .setSrcUrl(merchantImage.getPicUrl())
                .setChannelType(4);
        val existData = channelImgService.getOne(new QueryWrapper<>(merchantChannelImg));
        if (existData != null) {
            // 这里的channelImg的id由merchantImage带过去
            merchantImage.setId(existData.getId());
        } else {
            merchantImage.setId(null);
        }


        String imgBase64Data = FileUtil.getBase64FromUrl(merchantImage.getPicUrl());

        try {
            if (!Objects.equals(merchantImage.getPhotoType(), MerchantImage.ImageType.BUSINESS_LICENSE)) {
                log.debug("压缩图片");
                imgBase64Data = Base64Util.compressPic(imgBase64Data, 500);
            } else {
                log.debug("压缩图片 - 营业执照");
                imgBase64Data = Base64Util.compressPic(imgBase64Data, 1024);
            }
        } catch (Exception e) {
            LogExceptionUtils.printStack(log, e, null);
            throw new MsgException("上传文件失败");
        }

        JSONObject reqData = new JSONObject();
        reqData.put("picFile", imgBase64Data);
        reqData.put(YSConstants.MER_CODE, merchantImage.getMerchantCode());

        val response = ysService.requestApiCommon(YsConfig.IMG_UPLOAD, reqData, "AUDIT");

        log.info("上传图片返回结果为{}", response.toJSONString());
        afterUpload(merchantImage, response);
    }

    @Override
    public void imageUpload(String url, String picType) {
        val merchantImage = new MerchantImage().setPicUrl(url);
        imageUpload(merchantImage);
    }

    @Override
    public String imgTypeTransform(String imageType) {
        return null;
    }

    /**
     * 返回参数处理
     * @param merchantImage  图片信息
     * @param responseData  返回数据
     */
    private void afterUpload(MerchantImage merchantImage, JSONObject responseData) {
        val status = responseData.getString("status");
        val statusMeg = responseData.getString("statusMeg");

        if (!status.equals(RespEntity.SUCCESS)) {
            throw new MsgException(statusMeg);
        }

        val fileCode = responseData.getString("fileCode");
        var channelImg = new MerchantChannelImg()
                .setChannelType(4)
                // 这里的channelImg的id由merchantImage带过来
                .setId(merchantImage.getId())
                .setSrcUrl(merchantImage.getPicUrl())
                .setChannelImgUrl(fileCode);

        merchantImage.setPhotoUrl(fileCode);
        channelImgService.saveOrUpdate(channelImg);
    }
}
