package cn.pluss.platform.merchantImage.impl;

import cn.pluss.platform.IdCardService;
import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.constants.CommonError;
import cn.pluss.platform.converter.ImgConverter;
import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.MerchantImageMapper;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchant.MerchantBaseInfoService;
import cn.pluss.platform.merchantImage.MerchantImageService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author SSS
 */
@Slf4j
@Service("merchantImageService")
public class MerchantImageServiceImpl extends ServiceImpl<MerchantImageMapper, MerchantImage> implements MerchantImageService {

    @Lazy
    @Autowired
    private MerchantBaseInfoService mbiService;

    @Lazy
    @Autowired
    private AccountService accountService;

    @Autowired @Lazy
    private IdCardService idCardService;

    @Lazy
    @Autowired
    private MerchantAuditService sxfMerchantAuditService;

    @Override
    public List<MerchantImage> getListOfMerch(String userId, String channelType) {
        MerchantBaseInfo mbi = mbiService.getMerchantBaseInfoByUserId(userId);
        LambdaQueryWrapper<MerchantImage> qWrapper = Wrappers.lambdaQuery();
        qWrapper.eq(MerchantImage::getMerchantCode, mbi.getMerchantCode())
                .notIn(MerchantImage::getPhotoType, MerchantImage.ImageType.SETTLE_IDCARD_FRONT
                        , MerchantImage.ImageType.SETTLE_IDCARD_BACK
                        , MerchantImage.ImageType.ACCOUNT_PERMITS
                        , MerchantImage.ImageType.NON_LEG_SETTLE_AUTH
                        , MerchantImage.ImageType.BANK_CARD_FRONT
                        , MerchantImage.ImageType.IDCARD_FRONT
                        , MerchantImage.ImageType.IDCARD_BACK);
        List<MerchantImage> miList = list(qWrapper);

        AccountDTO accountDTO = accountService.getRealAccount(userId, channelType);

        MsgException.checkNull(accountDTO.getIdcard(), CommonError.NO_ACCOUNT_ID_CARD);
        MsgException.checkBlank(accountDTO.getIdcard().getImgPositive(), CommonError.NO_PART_ACCOUNT_ID_CARD_HEAD);
        MsgException.checkBlank(accountDTO.getIdcard().getImgNegative(), CommonError.NO_PART_ACCOUNT_ID_CARD_EMBLEM);

        MsgException.checkNull(accountDTO.getBankCard(), CommonError.NO_ACCOUNT_BANK_CARD);
        if (accountDTO.getBankCard().getAccountType().equals(BankCard.ACCOUNT_TYPE_CORPORATE)) {
            // 对公
            MsgException.checkBlank(accountDTO.getBankCard().getLicenseUrl(), CommonError.NO_ACCOUNT_BANK_CARD_LICENSE);
        } else {
            // 对私
            MsgException.checkBlank(accountDTO.getBankCard().getImgUrl(), CommonError.NO_ACCOUNT_BANK_CARD_IMG);
        }

        if (accountDTO.getSettleType().startsWith(Account.SETTLE_TYPE_PRIVATE_ILLEGAL)) {
            // 非法人结算需要非法人授权函
            MsgException.checkBlank(accountDTO.getCertificateUrl(), CommonError.NO_ILLEGAL_ACCOUNT_CERTIFICATE_URL);

            MerchantImage mi = new MerchantImage();
            mi.setPicUrl(accountDTO.getCertificateUrl());
            mi.setPhotoType(MerchantImage.ImageType.NON_LEG_SETTLE_AUTH);
            miList.add(mi);
        }

        MerchantImage mi = new MerchantImage();
        mi.setPicUrl(accountDTO.getIdcard().getImgPositive());
        mi.setPhotoType(MerchantImage.ImageType.SETTLE_IDCARD_FRONT);
        miList.add(mi);

        mi = new MerchantImage();
        mi.setPicUrl(accountDTO.getIdcard().getImgNegative());
        mi.setPhotoType(MerchantImage.ImageType.SETTLE_IDCARD_BACK);
        miList.add(mi);

        mi = new MerchantImage();
        if (accountDTO.getBankCard().getAccountType().equals(BankCard.ACCOUNT_TYPE_CORPORATE)) {
            mi.setPicUrl(accountDTO.getBankCard().getLicenseUrl());
            mi.setPhotoType(MerchantImage.ImageType.ACCOUNT_PERMITS);
        } else {
            mi.setPicUrl(accountDTO.getBankCard().getImgUrl());
            mi.setPhotoType(MerchantImage.ImageType.BANK_CARD_FRONT);
        }
        miList.add(mi);

        IdCard legalIdCard = idCardService.getLegalIdCard(userId);
        if (legalIdCard == null) {
            legalIdCard = accountDTO.getIdcard();
        }
        mi = new MerchantImage();
        mi.setPicUrl(legalIdCard.getImgPositive());
        mi.setPhotoType(MerchantImage.ImageType.IDCARD_FRONT);
        miList.add(mi);

        mi = new MerchantImage();
        mi.setPicUrl(legalIdCard.getImgNegative());
        mi.setPhotoType(MerchantImage.ImageType.IDCARD_BACK);
        miList.add(mi);

        return miList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMerchantImageUpload(String merchantCode, String url, String type) {

        // 保存图片信息
        MerchantImage merchantImage;

        MerchantImage existImage = new MerchantImage().setMerchantCode(merchantCode)
                .setPhotoType(type);

        existImage = getOne(new QueryWrapper<>(existImage));

        if (existImage != null) {
            merchantImage = existImage;
        } else {
            merchantImage = new MerchantImage();
            merchantImage.setMerchantCode(merchantCode);
            merchantImage.setPhotoType(type);
            merchantImage.setCreateDt(new Date());
        }

        merchantImage.setPicUrl(url);
        merchantImage.setUpdateDt(new Date());
        saveOrUpdate(merchantImage);
        // 上传图片到通道商服务器
//        sxfMerchantAuditService.imageUpload(merchantImage);
    }

    @Override
    public boolean saveOrUpdate(MerchantImage entity) {
        MsgException.checkBlank(entity.getMerchantCode(), "缺少商户code");
        MsgException.checkBlank(entity.getPhotoType(), "缺少图片类型");
        MsgException.checkBlank(entity.getPicUrl(), "缺少图片链接");

        // 获取已经存在的数据
        MerchantImage existData = ImgConverter.INSTANCE.imgCopy(entity);
        existData.setPicUrl(null);
        existData = getOne(new QueryWrapper<>(existData));

        Optional.ofNullable(existData).ifPresent(merchantImage -> entity.setId(merchantImage.getId()));

        return super.saveOrUpdate(entity);
    }
}

