package com.chaozhanggui.admin.system.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chaozhanggui.common.system.config.MsgException;
import com.chaozhanggui.dao.system.dao.*;
import com.chaozhanggui.dao.system.entity.*;
import com.chaozhanggui.dao.system.entity.DTO.AccountDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

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

/**
 * @author lyf
 */
@Service
@Slf4j
public class AccountService {
    @Resource
    private TbPlussAccountMapper accountMapper;
    @Resource
    private TbPlussBankCardMapper bankCardMapper;
    @Resource
    private TbPlussIdCardMapper idCardMapper;
    @Resource
    private TbPlussMerchantBaseInfoMapper merchantBaseInfoMapper;
    @Resource
    private TbPlussUserAppMapper userAppMapper;
    @Resource
    private TbPlussMerchantImageMapper merchantImageMapper;
    @Resource
    private TbPlussMerchantChannelStatusMapper merchantChannelStatusMapper;

    public AccountDTO getRealAccount(String userId) {
        return getRealAccount(userId, TbPlussAccount.CHANNEL_TYPE_D1);
    }
    public AccountDTO getRealAccount(String userId, String channelType) {
        if (!TbPlussAccount.CHANNEL_TYPE_D1.equals(channelType) && !TbPlussAccount.CHANNEL_TYPE_D0.equals(channelType)) {
            throw new MsgException("未知的通道类型");
        }

        TbPlussAccount account = new TbPlussAccount();
        account.setUserid(userId);
        account.setChanneltype(channelType);

        return getRealAccount(account);
    }
    public AccountDTO getRealAccount(TbPlussAccount account) {
        String userId = account.getUserid();
        if (account.getChanneltype() == null) {
            throw new MsgException("缺少结算通道类型");
        }

        List<String> bloomFilter = new ArrayList<>(2);
        bloomFilter.add(TbPlussAccount.CHANNEL_TYPE_D0);
        bloomFilter.add(TbPlussAccount.CHANNEL_TYPE_D1);
        if (!bloomFilter.contains(account.getChanneltype())) {
            throw new MsgException("未知的结算类型");
        }
        account = accountMapper.selectByAccount(account);
        AccountDTO accountDTO = toDTO(account);
        TbPlussMerchantBaseInfo mbi = new TbPlussMerchantBaseInfo();
        mbi.setUserid(Integer.valueOf(userId));
        mbi = merchantBaseInfoMapper.selectByUserId(userId);

        if (mbi == null) {
            return null;
        }

        // 用户不存在结算信息
        String merchantType = mbi.getMerchanttype();

        if (account == null && "1".equals(merchantType)) {
            AccountDTO result = new AccountDTO();
            result.setUserid(String.valueOf(mbi.getUserid()));
            result.setSettletype(TbPlussAccount.SETTLE_TYPE_MICRO_STORE);
            return result;
        }

        // 异或，小微但结算信息不是小微，非小微但结算信息是小微
        if (account == null || "1".equals(merchantType) ^ account.getSettletype().equals(TbPlussAccount.SETTLE_TYPE_MICRO_STORE)) {
            return null;
        }

        // 获取身份证信息
        TbPlussIdCard idCard = idCardMapper.selectByPrimaryKey(Integer.valueOf(account.getIdcardid()));
        accountDTO.setIdcard(idCard);

        // 获取银行卡信息
        TbPlussBankCard bankCard = bankCardMapper.selectByPrimaryKey(Integer.valueOf(account.getBankcardid()));
        accountDTO.setBankCard(bankCard);

        if (account.getSettletype() == null) {
            throw new MsgException("未知结算类型");
        }

        Optional.ofNullable(account.getSettletype()).ifPresent(s -> {
            if (s.startsWith(TbPlussAccount.SETTLE_TYPE_PRIVATE_ILLEGAL)) {
                TbPlussUserApp userApp = userAppMapper.selectByUserId(Integer.valueOf(userId));

                TbPlussMerchantImage merchantImage = new TbPlussMerchantImage();
                merchantImage.setMerchantcode(userApp.getMerchantcode());
                merchantImage.setPhotoType(TbPlussMerchantImage.NON_LEG_SETTLE_AUTH);

                merchantImage = merchantImageMapper.selectByMerchantCodeType(userApp.getMerchantcode(), TbPlussMerchantImage.NON_LEG_SETTLE_AUTH);

                Optional.ofNullable(merchantImage).ifPresent(v -> accountDTO.setCertificateurl(v.getPicurl()));
            }
        });


        TbPlussMerchantChannelStatus mcs = merchantChannelStatusMapper.getByMerchantCodeAndChannelType(mbi.getMerchantcode(), account.getChanneltype());
        if (mcs == null || !TbPlussMerchantChannelStatus.AUDIT_STATUS_DATA_EDIT.equals(mcs.getStatus())) {
            account.setBak(null);
        }

        return accountDTO;
    }
    public AccountDTO toDTO(TbPlussAccount account) {
        if ( account == null ) {
            return null;
        }

        AccountDTO accountDTO = new AccountDTO();

        accountDTO.setId( account.getId() );
        accountDTO.setUserid( account.getUserid() );
        accountDTO.setCertificateurl( account.getCertificateurl() );
        accountDTO.setSettletype( account.getSettletype() );
        accountDTO.setIdcardid( account.getIdcardid() );
        accountDTO.setBankcardid( account.getBankcardid() );
        accountDTO.setChanneltype( account.getChanneltype() );
        accountDTO.setCreatetime( account.getCreatetime() );
        accountDTO.setUpdatetime( account.getUpdatetime() );
        String jSONObject = account.getBak();
        if ( jSONObject != null ) {
            accountDTO.setBak(  jSONObject );
        }
        accountDTO.setValid( account.getValid() );

        return accountDTO;
    }

}
