package cn.pluss.platform.ysExtension.v20220615;

import cn.pluss.platform.channel.MerchProtocolService;
import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.entity.MerchantImage;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchantChannelImg.MerchantChannelImgService;
import cn.pluss.platform.util.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.Base64;
import java.util.Objects;
import java.util.UUID;

@Slf4j
public abstract class AbstractYsImgUploadService implements MerchProtocolService, MerchantAuditService {

    @Autowired
    private YsConfigExtensionV2 ysConfig;

    @Autowired
    protected RestTemplate restTemplate;

    @Autowired
    protected MerchantChannelImgService channelImgService;

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

    /**
     * @param merchantImage 图片信息
     */
    @Override
    public void imageUpload(MerchantImage merchantImage) {
        String imgBase64Data = FileUtil.getBase64FromUrl(merchantImage.getPicUrl());

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

        String picType = imgTypeTransform(merchantImage.getPhotoType());
        if (picType == null) {
            // 没有找到对应的图片类型，即不需要保存
            return;
        }

        JSONObject param = new JSONObject();
        param.put("sysFlowId", merchantImage.getPhotoUrl());
        param.put("picType", picType);
        try {
            byte[] bytes = Base64.getDecoder().decode(imgBase64Data);
            ByteArrayResource byteArrayResource = new ByteArrayResource(bytes) {
                @Override
                public String getFilename() {
                    return picType + ".png";
                }
            };
            String encryptOriginData = SignUtils.getSignContent(param);
            log.info("加签源数据==============>" + encryptOriginData);
            param.put("signValue", RSAUtils.sign(ysConfig.getPriKeyV2(), encryptOriginData));
            param.put("file", byteArrayResource);
        } catch (Exception e) {
            log.error("数据异常" + e.getMessage());
        }


        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        int retryTimes = 3;
        while (true) {
            param.put("reqFlowId", "YS" + System.currentTimeMillis() % 10000000 + UUID.randomUUID().toString().substring(4, 7));

            //        headers.add("User-Agent",
            //                "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

            MultiValueMap<String, Object> reqParam = MapUtils.map2MultiValueMap(param);
            HttpEntity<MultiValueMap<String, Object>> reqEntity = new HttpEntity<>(reqParam, headers);

            try {
                String respStr = restTemplate.postForObject(YsConfigExtensionV2.IMG_UPLOAD, reqEntity, String.class);
                log.info("result : " + respStr);
                JSONObject resultJson = JSON.parseObject(respStr);
                JSONObject data = resultJson.getJSONObject("data");
                if (!"00".equals(data.getString("code"))) {
                    throw new MsgException(data.getString("note"));
                }
                break;
            } catch (Exception e) {
                log.info(e.getClass().getName());
                // 超时后自动重试
                retryTimes--;
                if (retryTimes <= 0) {
                    throw new MsgException("图片3次上传失败：" + e.getMessage());
                }
            }
        }
    }

    @Override
    public String imgTypeTransform(String imageType) {
        switch (imageType) {
            case MerchantImage.ImageType.BUSINESS_LICENSE:
                return "A001";
            case MerchantImage.ImageType.IDCARD_FRONT:
                return "A002";
            case MerchantImage.ImageType.IDCARD_BACK:
                return "A003";
            case MerchantImage.ImageType.BANK_CARD_FRONT:
                return "A004";
            case MerchantImage.ImageType.BANK_CARD_BACK:
                return "A005";
            case MerchantImage.ImageType.SHOP_FRONT_DOOR:
                return "A006";
            case MerchantImage.ImageType.STORE_INTERIOR_PHOTO:
                return "A007";
            case MerchantImage.ImageType.CASH_DESK_PHOTO:
                return "A008";
            case MerchantImage.ImageType.HAND_IDCARD_PHOTO:
                return "A009";
            case MerchantImage.ImageType.ACCOUNT_PERMITS:
                return "A011";
            case MerchantImage.ImageType.SETTLE_IDCARD_FRONT:
                return "A013";
            case MerchantImage.ImageType.SETTLE_IDCARD_BACK:
                return "A014";
            case MerchantImage.ImageType.NON_LEG_SETTLE_AUTH:
                return "B005";
            case MerchantImage.ImageType.HAND_NON_LEG_SETTLE_AUTH:
                return "B004";
            default:
                return null;
        }
    }
}
