package cn.pluss.platform.impl;

import cn.pluss.platform.BankCardService;
import cn.pluss.platform.channel.MerchantAuditService;
import cn.pluss.platform.dto.AccountDTO;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.mapper.BankCardMapper;
import cn.pluss.platform.mapper.BankCodeSxfMapper;
import cn.pluss.platform.merchant.AccountService;
import cn.pluss.platform.merchantChannelStatus.MerchantChannelStatusService;
import cn.pluss.platform.merchantImage.MerchantImageService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.vo.BankCardRecordVO;
import cn.pluss.platform.wxCityInfo.WxCityInfoService;
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.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.Setter;
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.*;

/**
 * <p>
 * 银行卡信息 服务实现类
 * </p>
 *
 * @author Djh
 * @since 2020-10-16
 */
@Service
public class BankCardServiceImpl extends ServiceImpl<BankCardMapper, BankCard> implements BankCardService {

    @Setter(onMethod_ = {@Lazy, @Autowired})
    private MerchantAuditService sxfMerchantAuditService;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private UserAppService userAppService;
    @Setter(onMethod_ = {@Lazy, @Autowired})
    private WxCityInfoService wxCityInfoService;

    @Setter(onMethod_ = {@Autowired})
    private BankCodeSxfMapper bankCodeSxfMapper;

    @Autowired
    private MerchantImageService imgService;

    @Autowired @Lazy
    private AccountService accountService;

    @Autowired @Lazy
    private MerchantChannelStatusService mcsService;

    @Override
    public List<Map<String, Object>> getAccBankCardList(String userId) {
        List<Map<String, Object>> result = new ArrayList<>();
        LambdaQueryWrapper<UserApp> qWrapper = new LambdaQueryWrapper<>();
        qWrapper.eq(UserApp::getUserId, userId);
        UserApp ua = userAppService.getOne(qWrapper);
        AccountDTO d1 = accountService.getRealAccount(userId, Account.CHANNEL_TYPE_D1);
        if (d1 == null) {
            return result;
        }

        LambdaQueryWrapper<MerchantChannelStatus> mcsQueryWrapper = Wrappers.lambdaQuery();
        mcsQueryWrapper.eq(MerchantChannelStatus::getMerchantCode, ua.getMerchantCode());
        mcsQueryWrapper.eq(MerchantChannelStatus::getVirChannelFlag, Account.CHANNEL_TYPE_D1);
        mcsQueryWrapper.in(MerchantChannelStatus::getStatus,
                MerchantChannelStatus.AUDIT_STATUS_SUCCESS,
                MerchantChannelStatus.AUDIT_STATUS_DATA_EDIT);
        MerchantChannelStatus mcs = mcsService.getOne(mcsQueryWrapper);
        if (mcs != null) {
            Map<String, Object> d1Data = new HashMap<>(4);
            d1Data.put("type", Account.CHANNEL_TYPE_D1);
            d1Data.put("data", BankCard.desensitized(d1.getBankCard()));
            if (MerchantChannelStatus.AUDIT_STATUS_DATA_EDIT.equals(mcs.getStatus())) {
                BankCard edit = d1.getBak().toJavaObject(BankCard.class);
                d1Data.put("editData", BankCard.desensitized(edit));
            }

            result.add(d1Data);
        }

        AccountDTO d0 = accountService.getRealAccount(userId, Account.CHANNEL_TYPE_D0);
        if (d0 == null) {
            return result;
        }

        mcsQueryWrapper.clear();
        mcsQueryWrapper.eq(MerchantChannelStatus::getMerchantCode, ua.getMerchantCode());
        mcsQueryWrapper.eq(MerchantChannelStatus::getVirChannelFlag, Account.CHANNEL_TYPE_D0);
        mcsQueryWrapper.in(MerchantChannelStatus::getStatus,
                MerchantChannelStatus.AUDIT_STATUS_SUCCESS,
                MerchantChannelStatus.AUDIT_STATUS_DATA_EDIT);
        mcs = mcsService.getOne(mcsQueryWrapper);
        if (mcs != null) {
            Map<String, Object> d0Data = new HashMap<>(4);
            d0Data.put("type", Account.CHANNEL_TYPE_D0);
            d0Data.put("data", BankCard.desensitized(d0.getBankCard()));
            if (MerchantChannelStatus.AUDIT_STATUS_DATA_EDIT.equals(mcs.getStatus())) {
                BankCard edit = d0.getBak().toJavaObject(BankCard.class);
                d0Data.put("editData", BankCard.desensitized(edit));
            }

            result.add(d0Data);
        }

        return result;
    }

    /**
     * 保存实名信息的时候，默认将实名信息保存为
     *
     * @param entity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveOrUpdate(BankCard entity) {
        WxCityInfo wxCityInfo = new WxCityInfo();

        if (entity.getBranchProvince() != null && entity.getBranchCity() != null && entity.getBranchArea() != null) {
            wxCityInfo.setCityName("中国," + entity.getBranchProvince() + "," + entity.getBranchCity() + "," + entity.getBranchArea());
            wxCityInfo = wxCityInfoService.queryWxCityInfo(wxCityInfo);

            if (wxCityInfo != null) {
                entity.setBankAddressNo(wxCityInfo.getCityCode());
            }
        }

        if (entity.getAccountType().equals(BankCard.ACCOUNT_TYPE_CERT)) {
            return saveCertBankCard(entity);
        } else {
            return saveAccountBankCard(entity);
        }
    }

    @Override
    public boolean saveCertBankCard(BankCard entity) {
        if (!BankCard.ACCOUNT_TYPE_CERT.equals(entity.getAccountType())) {
            return false;
        }

        UserApp ua = new UserApp().setUserId(Long.parseLong(entity.getUserId()));
        ua = userAppService.getOne(new QueryWrapper<>(ua));

        if (Objects.equals(3, ua.getStatus())) {
            throw new MsgException("当前状态不能修改实名银行卡信息");
        }

        BankCard exist = new BankCard()
                .setUserId(entity.getUserId())
                .setAccountType(BankCard.ACCOUNT_TYPE_CERT);

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

        if (exist != null) {
            entity.setId(exist.getId());
            return updateById(entity);
        } else {
            return save(entity);
        }
    }

    @Override
    public boolean saveAccountBankCard(BankCard entity) {
        if (BankCard.ACCOUNT_TYPE_CERT.equals(entity.getAccountType())) {
            return false;
        }

        

        return false;
    }

    @Override
    public void checkBankInfo(BankCard bankCard) {
        BankCodeSxf bankCodeSxf = new BankCodeSxf();
        bankCodeSxf.setCnapsCode(bankCard.getContactLine());
        bankCodeSxf = bankCodeSxfMapper.selectOne(new QueryWrapper<>(bankCodeSxf));

        String bankName = bankCard.getBankName().replace("银行", "");

        if ("浦发".equals(bankName)) {
            bankName = "浦东发展";
        }

        if (!bankCodeSxf.getBankName().contains(bankName) && !"其他".equals(bankName)) {
            MsgException.throwException("开户行与支行信息不匹配，请检查银行卡信息");
        }
    }

    @Override
    public Page<BankCardRecordVO> pageBankCardRecord(Page<BankCardRecordVO> page, Long userId) {
        return null;
    }
}
