package cn.pluss.platform.jft.impl;

import cn.pluss.platform.IdCardService;
import cn.pluss.platform.converter.Converter;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.jft.*;
import cn.pluss.platform.merchant.JftMercPaymentChannelService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.yinsheng.v20210929.ReqMethod;
import cn.pluss.platform.ys.impl.v20210929.YsServiceV2;
import cn.pluss.platform.ysExtension.v20220615.YsAuditServiceImpl;
import cn.pluss.platform.ysExtension.v20220615.YsConfigExtensionV2;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author DJH
 */
@Slf4j
@Service
public class JftAuditServiceImpl implements JftAuditService {

    @Autowired
    private UserAppService uaService;

    @Autowired
    private IdCardService idCardService;

    @Resource
    private JftBankCardService jftBankCardService;

    @Autowired
    private JftMerchantRateRecordService jftMerchantRateRecordService;

    @Autowired
    private JftMerchantRateService jftMerchantRateService;

    @Autowired
    @Lazy
    private YsAuditServiceImpl ysAuditServiceExtensionV2;

    @Autowired @Lazy
    private JftMercPaymentChannelService jpcService;

    @Autowired
    private JftMercBaseInfoService jbiService;

    @Autowired
    private YsServiceV2 ysServiceV2;

    @Override
    public JftMercBaseInfo getMercBaseInfo(Long userId) {

        return jbiService.getMercBaseInfo(userId);
    }

    @Override
    public List<MerchantImage> listMerchImage(Long userId) {
        JftMercBaseInfo jbi = getMercBaseInfo(userId);

        List<MerchantImage> miList = new ArrayList<>();
        miList.add(MerchantImage.from(jbi.getFrontPic(), MerchantImage.ImageType.SHOP_FRONT_DOOR));
        miList.add(MerchantImage.from(jbi.getCashDesk(), MerchantImage.ImageType.CASH_DESK_PHOTO));
        miList.add(MerchantImage.from(jbi.getInterior(), MerchantImage.ImageType.STORE_INTERIOR_PHOTO));

        final IdCard certIdCard = idCardService.getCertIdCard(userId);

        final JftBankCard jftBankCard = jftBankCardService.getByUserId(userId);

        miList.add(MerchantImage.from(certIdCard.getImgPositive(), MerchantImage.ImageType.SETTLE_IDCARD_FRONT));

        miList.add(MerchantImage.from(certIdCard.getImgNegative(), MerchantImage.ImageType.SETTLE_IDCARD_BACK));

        miList.add(MerchantImage.from(jftBankCard.getImgUrl(), MerchantImage.ImageType.BANK_CARD_FRONT));

        return miList;
    }

    @Override
    public void audit(Long userId) {
        ysAuditServiceExtensionV2.merchantAudit(userId.toString(), false);
    }

    @Override
    public void apiAudit() {
        Calendar calendar = Calendar.getInstance();
        int i = calendar.get(Calendar.HOUR_OF_DAY);

        if (i < 8 || i > 21) {
            throw new MsgException("当前时段暂不支持入网，请于8:00-21:00提交");
        }

        final UserApp tokenUa = uaService.queryUserAppByToken();
        audit(tokenUa.getUserId());
    }

    @Override
    public void editBankCard(Long userId) {
        ysAuditServiceExtensionV2.editMerchantAudit(userId.toString());
    }

    @Override
    public void changeRate(Long userId, BigDecimal rate) {
        JftMercPaymentChannel jpc = jpcService.getByUserId(userId);

        if (jpc == null || !jpc.getStatus().equals(MerchantChannelStatus.AUDIT_STATUS_SUCCESS)) {
            return;
        }

        JftMerchantRate jftMerchantRate = new JftMerchantRate();
        jftMerchantRate.setMerchantId(jpc.getMerchantId());
        jftMerchantRate.setAliRate(rate);

        // 获取新的费率并保存一条修改记录
        final JftMerchantRateRecord rateRecord = Converter.INSTANCE.toRecord(jftMerchantRate);
        rateRecord.setStatus("0");

        jftMerchantRateRecordService.save(rateRecord);

        JSONObject reqParam = new JSONObject();

        JSONObject wxAliFee = new JSONObject();
        wxAliFee.put("wechatSignRate", rateRecord.getAliRate() / 100f + "");
        wxAliFee.put("wechatSignMin", "1");
        wxAliFee.put("alipaySignRate", rateRecord.getAliRate() / 100f + "");
        wxAliFee.put("alipaySignMin", "1");

        reqParam.put("mercId", jpc.getMerchantId());
//        reqParam.put("bankFee1", bankFee1);
//        reqParam.put("bankFee2", bankFee2);
        reqParam.put("wxAliFee", wxAliFee);

        // 发起修改费率请求
        JSONObject respData = ysServiceV2.req(YsConfigExtensionV2.MER_RATE_CHANGE, ReqMethod.MERCHANT_CHANGE_ONLINE_FEE, reqParam);
        log.info("请求结果：{}", respData);
        String changeFlowId = respData.getString("changeFlowId");
        jpc.getExtra().put("changeFlowId", changeFlowId);

        rateRecord.setCreateTime(new Date());
        rateRecord.setUpdateTime(new Date());
        rateRecord.setRemark(changeFlowId);
        jftMerchantRateRecordService.save(rateRecord);

        // 上传一张空白图作为结算信息修改申请表
        ysAuditServiceExtensionV2.imageUploadEdit("https://www.shouyinbei.net/resources/images/upload/blank.png", "B008", changeFlowId);
    }
}
