package com.chaozhanggui.admin.system.service;

import com.alibaba.fastjson.JSONObject;
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.IService;
import com.chaozhanggui.admin.system.model.CommonError;
import com.chaozhanggui.admin.system.util.Converter;
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.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
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;
    @Resource
    private TbPlussBankCodeSxfMapper bankCodeSxfMapper;
    @Resource
    private TbPlussRiskBlacklistMapper riskBlacklistMapper;


    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 = Converter.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;
    }

    /**
     *
     * @param accountDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveV4(AccountDTO accountDTO) {
        TbPlussMerchantBaseInfo mbi = merchantBaseInfoMapper.selectByUserId(accountDTO.getUserid());
        if (StringUtils.isEmpty(accountDTO.getChanneltype())) {
            //D1相关
            TbPlussMerchantChannelStatus mcsD1 = merchantChannelStatusMapper.getByMerchantCodeAndChannelType(mbi.getMerchantcode(),  TbPlussAccount.CHANNEL_TYPE_D1);
            mcsD1 = Optional.ofNullable(mcsD1).orElse(new TbPlussMerchantChannelStatus());
            if (Objects.equals(mcsD1.getStatus(), TbPlussMerchantChannelStatus.AUDIT_STATUS_SUCCESS)
                    || Objects.equals(mcsD1.getStatus(), TbPlussMerchantChannelStatus.AUDIT_STATUS_EXAMINING)
                    || Objects.equals(mcsD1.getStatus(), TbPlussMerchantChannelStatus.AUDIT_STATUS_DATA_EDIT)) {
                accountDTO.setChanneltype(TbPlussAccount.CHANNEL_TYPE_D0);
            } else {
                accountDTO.setChanneltype(TbPlussAccount.CHANNEL_TYPE_D1);
            }
        }





//        //TODO 测试时先注掉
//        if (checkFlag && !(settleTypeFlag)) {
//            // 执行银行卡四要素校验
//            aliyunService.checkBankCorrectNow(accountDTO.getBankCard().getPhone(), accountDTO.getBankCard().getBankCardNo()
//                    , accountDTO.getIdcard().getCertNo()
//                    , accountDTO.getBankCard().getBankHolder(), "结算人与结算银行卡不匹配，请核对结算信息");
//        }

    }

    /**
     * 校验银行卡信息是否合法
     * @param bankCard
     */
    public void checkBankInfo(TbPlussBankCard bankCard) {
        TbPlussBankCodeSxf bankCodeSxf = new TbPlussBankCodeSxf();
        bankCodeSxf.setCnapsCode(bankCard.getContactline());
        bankCodeSxf = bankCodeSxfMapper.selectOne(new QueryWrapper<>(bankCodeSxf));

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

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

        if("长安".equals(bankName)){
            bankName="城市商业银行";
        }

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

    /**
     * 清理指定用户的结算信息
     * @param userId
     * @param channelType
     */
    public void delAccount(String userId, String channelType) {
        TbPlussAccount account = accountMapper.selectByUser(Integer.valueOf(userId),channelType);
        if (account == null) {
            return;
        }
        accountMapper.deleteByPrimaryKey(account.getId());

        if (!account.getSettletype().equals(TbPlussAccount.SETTLE_TYPE_CORPORATE)
                && !account.getSettletype().startsWith(TbPlussAccount.SETTLE_TYPE_PRIVATE_LEGAL)) {
            LambdaQueryWrapper<TbPlussAccount> queryWrapper2 = Wrappers.lambdaQuery();
            queryWrapper2.eq(TbPlussAccount::getUserid, userId)
                    .eq(TbPlussAccount::getIdcardid, account.getIdcardid());
            Integer countIdCardUsedAccount = accountMapper.selectCountIdCardId(userId,account.getIdcardid());
            if (countIdCardUsedAccount == null || countIdCardUsedAccount == 0) {
                // idCard如果没有再被使用
                idCardMapper.deleteByPrimaryKey(Integer.valueOf(account.getIdcardid()));
            }
        }
        Integer countBankCardUsedAccount = accountMapper.selectCountBankCard(account.getBankcardid(),userId);
        if (countBankCardUsedAccount == null || countBankCardUsedAccount == 0) {
            // bankCard如果没有再被使用
            bankCardMapper.deleteByPrimaryKey(Integer.valueOf(account.getBankcardid()));
        }

    }
}
