package cn.pluss.platform.ys.impl;

import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.AccountMapper;
import cn.pluss.platform.mcc.MccInfoSortService;
import cn.pluss.platform.util.ParametersUtil;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.ys.YSConstants;
import cn.pluss.platform.ys.YsConfig;
import cn.pluss.platform.ys.YsService;
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.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 银盛进件实现类
 *
 * @author djh
 */
@Slf4j
@Service("ysAuditService")
public class YsAuditServiceImpl extends AbYsAuditResultService {

    public static final String URI = "/api/auditCallback/ys";

    @Autowired
    private MccInfoSortService mccInfoSortService;

    @Resource
    private AccountMapper accountMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void merchantAudit(String userId, boolean isFailCheck) {
        merchantAuditCheck(userId, isFailCheck);

        AccountDTO account = accountService.getRealAccount(userId, Account.CHANNEL_TYPE_D0);
        IdCard idCard;
        IdCard legalIdCard = idCardService.getLegalIdCard(userId);
        MerchantBaseInfo mbi = merchantBaseInfoService.getMerchantBaseInfoByUserId(userId);
        if (account.getSettleType().startsWith(Account.SETTLE_TYPE_PRIVATE_ILLEGAL)) {
            mbi.setMerchantType("1");
        }

        int ysCount = accountMapper.selectYSAuditSmallCount(mbi.getUserId());
        if (ysCount >= 2 && "1".equals(mbi.getMerchantType())) {
            MsgException.throwException("非营业执照商户同一结算人最多可申请两次实时到账");
        }

        channelImgService.removeThirdImgRecord(mbi.getMerchantCode(), "4");
        List<MerchantImage> merchantChannelImgList = channelImgService.getAuditImg(userId, "4");

        JSONObject extra = new JSONObject();
        String outMerchantCode = mbi.getMerchantCode() + (System.currentTimeMillis() / 1000);
        extra.put(YSConstants.MER_CODE, outMerchantCode);

        JSONObject bizReqJson = new JSONObject();
        bizReqJson.put(YSConstants.MER_NAME, mbi.getMerchantName());
        bizReqJson.put(YSConstants.MER_ALIAS, mbi.getAlias());

        //
        bizReqJson.put(YSConstants.MER_CODE, outMerchantCode);
        bizReqJson.put(YSConstants.BUSINESS_TYPE, YSConstants.getBusinessType(mbi.getMerchantType()));
        if ("0".equals(bizReqJson.getString(YSConstants.BUSINESS_TYPE))) {
            // 添加营业执照信息
            bizReqJson.put(YSConstants.MER_LICENSE_CODE, mbi.getBussAuthNum());
            bizReqJson.put(YSConstants.MER_LICENSE_NAME, mbi.getBussAuthName());
            bizReqJson.put(YSConstants.MER_LICENSE_START, mbi.getBussAuthStartTime().replace("-", ""));
            bizReqJson.put(YSConstants.MER_LICENSE_END, YSConstants.getMerLicenseEnd(mbi.getBussAuthEndTime()));
            bizReqJson.put(YSConstants.MER_LICENSE_ADDRESS, mbi.getBussAuthAddress());
            // 营业执照图片信息在填写图片信息时填写
            idCard = legalIdCard;

            // 部分法人信息必传
            // 国籍中国
            bizReqJson.put(YSConstants.LEGAL_PERSON_COUNTRY, "249");
            MccInfoSort mccInfoSort = mccInfoSortService.getByMcc(mbi.getMcc());

            MsgException.checkNull(mccInfoSort, "请重新选择mcc");
            bizReqJson.put(YSConstants.LEGAL_PERSON_WORK, mccInfoSort.getCode());
            bizReqJson.put(YSConstants.LEGAL_PERSON_SEX, StringUtil.getSexFromCertNo(idCard.getCertNo()));
            bizReqJson.put(YSConstants.LEGAL_PERSON_ADDRESS, mbi.getAddress());
        } else {
            // 小微商户的
            idCard = account.getIdcard();
        }

        bizReqJson.put(YSConstants.MER_ADDRESS, mbi.getAddress());
        bizReqJson.put(YSConstants.LEGAL_PERSON_NAME, idCard.getCertName());
        bizReqJson.put(YSConstants.LEGAL_PERSON_ID, idCard.getCertNo());
        // 这里为保证准确性，使用
        bizReqJson.put(YSConstants.LEGAL_PERSON_PHONE, account.getBankCard().getPhone());
        // 身份证正反面填写图片信息时填写
        bizReqJson.put(YSConstants.LEGAL_PERSON_ID_START, idCard.getCertStartTime().replace("-", ""));
        bizReqJson.put(YSConstants.LEGAL_PERSON_ID_END, YSConstants.getIdCardLongExpire(idCard.getCertEndTime()));

        bizReqJson.put(YSConstants.LEGAL_PERSON_CARD_TYPE, "00");

        if ("03".equals(account.getSettleType())) {
            bizReqJson.put(YSConstants.ACCOUNT_CARD_TYPE, "21");
        } else {
            bizReqJson.put(YSConstants.ACCOUNT_CARD_TYPE, "11");
        }

        bizReqJson.put(YSConstants.ACCOUNT_CARD_NO, account.getBankCard().getBankCardNo());
        bizReqJson.put(YSConstants.ACCOUNT_CARD_NAME, account.getBankCard().getBankHolder());
        // 结算账户图片在填写图片信息时填写
        String province = account.getBankCard().getBranchProvince();
        String city = account.getBankCard().getBranchCity();
        String area = account.getBankCard().getBranchArea();
        RegionCodeYs regionCode = regionReflectService.getYsRegionCode(province, city, area);
        bizReqJson.put(YSConstants.OPEN_ACC_PROVINCE, regionCode.getProvince());
        bizReqJson.put(YSConstants.OPEN_ACC_CITY, regionCode.getCity());
        if (regionCode.getArea() != null) {
            bizReqJson.put(YSConstants.OPEN_ACC_AREA, regionCode.getArea());
        }


        bizReqJson.put(YSConstants.BANK_CONTACT_LINE, account.getBankCard().getContactLine());
        bizReqJson.put(YSConstants.CONTACT_PERSON, mbi.getContactName());
        bizReqJson.put(YSConstants.CONTACT_PERSON_PHONE, mbi.getContactMobile());
        bizReqJson.put(YSConstants.CONTACT_PERSON_EMAIL, "18062761507@163.com");
        bizReqJson.put(YSConstants.CONTACT_PERSON_ADDRESS, mbi.getAddress());

        String mbiProvince = account.getBankCard().getBranchProvince();
        String mbiCity = account.getBankCard().getBranchCity();
        String mbiArea = account.getBankCard().getBranchArea();
        RegionCodeYs mbiRegionCode = regionReflectService.getYsRegionCode(mbiProvince, mbiCity, mbiArea);
        bizReqJson.put(YSConstants.CONTACT_PROVINCE, mbiRegionCode.getProvince());
        bizReqJson.put(YSConstants.CONTACT_CITY, mbiRegionCode.getCity());
        String distinct = mbiRegionCode.getArea();
        if (distinct != null) {
            bizReqJson.put(YSConstants.CONTACT_REGION, distinct);
        }

        bizReqJson.put(YSConstants.BIZ_NAME, "收银呗");
        bizReqJson.put(YSConstants.MCC_CODE, mbi.getMcc());
        bizReqJson.put(YSConstants.MER_TYPE, YSConstants.getMerchantType(mbi.getMerchantType()));
        bizReqJson.put(YSConstants.WX_RATE, 0.38);
        bizReqJson.put(YSConstants.WX_RATE_MAX, 9999.00);
        bizReqJson.put(YSConstants.WX_RATE_MIN, 0.01);
        bizReqJson.put(YSConstants.ALI_RATE, 0.38);
        bizReqJson.put(YSConstants.ALI_RATE_MAX, 9999.00);
        bizReqJson.put(YSConstants.ALI_RATE_MIN, 0.01);

        bizReqJson.put(YSConstants.NOTIFY_ADDRESS, ParametersUtil.domain + URI);
        concatImgInfo(bizReqJson, merchantChannelImgList, outMerchantCode);


        log.info("{}银盛进件参数{}", userId, JSON.toJSONString(bizReqJson));

        JSONObject resp = ysService.requestApiCommon(YsConfig.MER_AUDIT, bizReqJson, YsService.TYPE_AUDIT);

        String status = resp.getString("status");
        String statusMsg = resp.getString("statusMeg");

        MerchantChannelStatus mcs = this.mcsService.getByMerchantCode(mbi.getMerchantCode(), 4);
        mcs.setThirdStatus(status);
        mcs.setRemark(statusMsg);
        mcs.setChannel(4);
        mcs.setExtra(extra);

        if ("wait".equals(status)) {
            mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_EXAMINING);
        } else if ("success".equals(status)) {
            mcs.setStatus(MerchantChannelStatus.AUDIT_STATUS_SUCCESS);
        } else {
            throw new MsgException(statusMsg);
        }
        this.mcsService.saveOrUpdate(mcs);
    }

    @Override
    public void merchantAuditCheck(String userId, boolean isFailCheck) {

    }

    @Override
    public void editMerchantAudit(String userId) {
        // 银盛没有进件修改接口
        MsgException.throwException("修改商户信息请联系客服");
    }

    /**
     * 上传图片时需要将外部上号传入
     *
     * @param bizReqJson      最终请求业务数据
     * @param imgList         图片列表
     * @param outMerchantCode 外部商户号
     */
    private void concatImgInfo(JSONObject bizReqJson, List<MerchantImage> imgList, String outMerchantCode) {
        for (MerchantImage merchantImage : imgList) {
            merchantImage.setMerchantCode(outMerchantCode);

            switch (merchantImage.getPhotoType()) {
                case MerchantImage.ImageType.IDCARD_FRONT:
                    if (!"3".equals(bizReqJson.getString(YSConstants.MER_TYPE))) {
                        imageUpload(merchantImage);
                        // 个体、企业
                        bizReqJson.put(YSConstants.LEGAL_PERSON_ID_IMG_FRONT, merchantImage.getPhotoUrl());
                        bizReqJson.put(YSConstants.LEGAL_PERSON_HAND_FRONT, merchantImage.getPhotoUrl());
                    }
                    break;
                case MerchantImage.ImageType.IDCARD_BACK:
                    if (!"3".equals(bizReqJson.getString(YSConstants.MER_TYPE))) {
                        imageUpload(merchantImage);
                        // 个体、企业
                        bizReqJson.put(YSConstants.LEGAL_PERSON_ID_IMG_BACK, merchantImage.getPhotoUrl());
                    }
                    break;
                case MerchantImage.ImageType.ACCOUNT_PERMITS:
                    if (!"3".equals(bizReqJson.getString(YSConstants.MER_TYPE))) {
                        imageUpload(merchantImage);
                        // 个体、企业
                        bizReqJson.put(YSConstants.ACCOUNT_CARD_FRONT, merchantImage.getPhotoUrl());
                    }
                    break;
                case MerchantImage.ImageType.SETTLE_IDCARD_FRONT:
                    if ("3".equals(bizReqJson.getString(YSConstants.MER_TYPE))) {
                        imageUpload(merchantImage);
                        // 个体、企业
                        bizReqJson.put(YSConstants.LEGAL_PERSON_ID_IMG_FRONT, merchantImage.getPhotoUrl());
                        bizReqJson.put(YSConstants.LEGAL_PERSON_HAND_FRONT, merchantImage.getPhotoUrl());
                    }
                    break;
                case MerchantImage.ImageType.SETTLE_IDCARD_BACK:
                    if ("3".equals(bizReqJson.getString(YSConstants.MER_TYPE))) {
                        imageUpload(merchantImage);
                        // 个体、企业
                        bizReqJson.put(YSConstants.LEGAL_PERSON_ID_IMG_BACK, merchantImage.getPhotoUrl());
                    }
                    break;
                case MerchantImage.ImageType.BANK_CARD_FRONT:
                    imageUpload(merchantImage);
                    bizReqJson.put(YSConstants.ACCOUNT_CARD_FRONT, merchantImage.getPhotoUrl());
                    break;
                case MerchantImage.ImageType.BUSINESS_LICENSE:
                    if (!"3".equals(bizReqJson.getString(YSConstants.MER_TYPE))) {
                        imageUpload(merchantImage);
                        // 非小微商户添加营业执照
                        bizReqJson.put(YSConstants.MER_LICENSE_IMG, merchantImage.getPhotoUrl());
                    }
                    break;
                case MerchantImage.ImageType.SHOP_FRONT_DOOR:
                    imageUpload(merchantImage);
                    bizReqJson.put(YSConstants.DOOR_FRONT_PIC, merchantImage.getPhotoUrl());
                    break;
                case MerchantImage.ImageType.CASH_DESK_PHOTO:
                    imageUpload(merchantImage);
                    bizReqJson.put(YSConstants.CASHIER_PIC, merchantImage.getPhotoUrl());
                    break;
                case MerchantImage.ImageType.STORE_INTERIOR_PHOTO:
                    imageUpload(merchantImage);
                    bizReqJson.put(YSConstants.SCENE_PIC, merchantImage.getPhotoUrl());
                    break;
                default:
                    break;
            }
        }
    }
}
