package com.crm.ucard.controller;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.*;
import com.crm.rely.backend.core.dto.ib.account.AccountDropdownDto;
import com.crm.rely.backend.core.dto.ib.account.AccountInfoDto;
import com.crm.rely.backend.core.dto.ucard.*;
import com.crm.rely.backend.core.dto.wasabi.*;
import com.crm.rely.backend.core.entity.base.BaseEntity;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.custom.info.InfoEntity;
import com.crm.rely.backend.core.entity.custom.kyc.WebsdkLinkAliEntity;
import com.crm.rely.backend.core.entity.ib.account.AccountInfoListEntity;
import com.crm.rely.backend.core.entity.ucard.*;
import com.crm.rely.backend.core.entity.wasabi.*;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.util.GetIpAndMac;
import com.crm.ucard.service.*;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/wasabi/api")
public class WasabiCardApiController {

    @Autowired
    private UcardApiService ucardApiService;
    @Autowired
    private UcardService ucardService;

    @Autowired
    private WasabiCardService wasabiCardService;

    @Autowired
    private CustomInfoService customInfoService;
    @Autowired
    private AccountInfoFeignService accountInfoFeignService;

    /**
     * 获取卡片类型列表
     */
    @PostMapping("/card/types/page")
    public ResultWithPagerDto<CardTypeDto> getCardTypePageList(@RequestBody CardTypePageEntity entity) throws ServiceException {
        entity.setEnableStatus(1);
        return ucardService.getCardTypePageList(entity);
    }

    /**
     * 获取卡片类型
     */
    @PostMapping("/card/types/list")
    public BaseResultDto getCardTypeList(@RequestBody CardTypeEntity entity, InfoEntity infoEntity) throws ServiceException {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return BaseResultDto.success(wasabiCardService.getCardTypeList(entity));
    }

    /**
     * 身份认证获取web链接
     *
     * @param entity
     * @return
     */
    @PostMapping("/getWebsdkLink")
    public BaseResultDto getWebsdkLink(@RequestBody WebsdkLinkAliEntity entity, InfoEntity infoEntity) throws Exception {
        return wasabiCardService.getWebsdkLink(entity, infoEntity.getCustomInfo().getId());
    }

    /**
     * 商户用户注册
     */
    @PostMapping("/merchant/user/register")
    public BaseResultDto registerMerchantUser(@RequestBody @Validated CardMerchantUserEntity request,
                                              InfoEntity entity, HttpServletRequest servletRequest) throws ServiceException {
        String ip = GetIpAndMac.getIp(servletRequest);
        request.setIpAddress(ip);
        request.setCustomId(entity.getCustomInfo().getId());
        request.setCId(entity.getCustomInfo().getCId());
        request.setOperateUser(entity.getCustomInfo().getCId());
        return wasabiCardService.registerMerchantUser(request);
    }

    /**
     * 更新商户用户信息
     */
    @PostMapping("/merchant/user/update")
    public BaseResultDto updateMerchantUser(@RequestBody @Validated CardMerchantUserEntity request,
                                            InfoEntity entity) throws ServiceException {
        request.setCustomId(entity.getCustomInfo().getId());
        request.setCId(entity.getCustomInfo().getCId());
        request.setOperateUser(entity.getCustomInfo().getCId());
        return wasabiCardService.updateMerchantUser(request);
    }


    /**
     * 更新用户邮寄地址
     */
    @PostMapping("/merchant/user/address/update")
    public BaseResultDto updateUserMailingAddress(@RequestBody WasabiSaveUserMailingAddressEntity request) throws ServiceException {
        return wasabiCardService.updateUserMailingAddress(request);
    }

    /**
     * 获取开卡手续费优惠次数
     */
    @PostMapping("/apply/reduction/num")
    public BaseResultDto getApplyReductionNum(InfoEntity infoEntity) throws ServiceException {
        return BaseResultDto.success(customInfoService.getApplyReductionNum(infoEntity.getCustomInfo().getId()));
    }

    /**
     * 查看用户详情
     */
    @PostMapping("/merchant/user/single")
    public BaseResultDto merchantUserSingle(InfoEntity infoEntity) throws Exception {
        return wasabiCardService.merchantUserSingle(infoEntity.getCustomInfo().getId());
    }

    /**
     * 获取kyc认证分页列表
     */
    @PostMapping("/merchant/kyc/page")
    ResultWithPagerDto<CardKycStatusDto> getKycPageList(@RequestBody CardKycStatusPageEntity entity) throws ServiceException {
        return ucardService.getKycPageList(entity);
    }

    /**
     * 申请开卡
     */
    @PostMapping("/card/apply")
    public BaseResultDto applyCard(@RequestBody CardApplyEntity request, InfoEntity infoEntity) throws Exception {
        request.setCId(infoEntity.getCustomInfo().getId());
        return wasabiCardService.applyCard(request);
    }

    /**
     * 查询开卡进度
     */
    @PostMapping("/card/apply/progress")
    public BaseResultDto queryApplyProgress(@RequestBody CardApplyProgressEntity request) throws Exception {
        return wasabiCardService.queryApplyProgress(request);
    }

    /**
     * 获取卡片申请列表
     */
    @PostMapping("/card/apply/page")
    public ResultWithPagerDto<CardApplyDto> getCardApplyPageList(@RequestBody CardApplyPageEntity entity) throws ServiceException {
        return ucardService.getCardApplyPageList(entity);
    }

    /**
     * 获取卡片申请详情
     */
    @PostMapping("/card/apply/details")
    public BaseResultDto cardApplyDetails(@RequestBody BaseEntity entity) throws ServiceException {
        return wasabiCardService.cardApplyDetails(entity);
    }

    /**
     * 获取我的卡片列表
     */
    @PostMapping("/card/list")
    public BaseResultDto getCardList(@RequestBody CardPageEntity entity, InfoEntity infoEntity) throws ServiceException {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return BaseResultDto.success(ucardApiService.getCardList(entity));
    }

    /**
     * 获取卡片详情
     */
    @PostMapping("/card/single")
    public BaseResultDto getCardSingle(@RequestBody SingleLongEntity entity) throws ServiceException {
        return BaseResultDto.success(ucardApiService.getCardSingle(entity));
    }

    /**
     * 银行卡激活
     */
    @PostMapping("/card/activate")
    public BaseResultDto<WasabiActiveCardDto> activateCard(@RequestBody WasabiActiveCardEntity request,
                                                           InfoEntity infoEntity) throws ServiceException {
        request.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.activeCard(request);
    }

    /**
     * 银行卡充值
     */
    @PostMapping("/card/recharge")
    public BaseResultDto rechargeCard(@RequestBody WasabiBalanceEntity request, InfoEntity infoEntity) throws ServiceException {
        request.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.cardDeposit(request);
    }

    /**
     * 查询用户钱包余额
     */
    @PostMapping("/card/wallet/balance")
    public BaseResultDto<WalletBalanceDto> walletBalance(@RequestBody WalletBalanceEntity request,
                                                         InfoEntity infoEntity) throws ServiceException {
        request.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.walletBalance(request);
    }

    /**
     * 获取用户钱包记录列表
     */
    @PostMapping("/card/wallet/record/page")
    public ResultWithPagerDto<CardWalletRecordDto> getCardWalletRecordPageList(@RequestBody CardWalletRecordPageEntity entity, InfoEntity infoEntity) throws ServiceException {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.getCardWalletRecordPageList(entity);
    }

    /**
     * 充值记录分页查询
     */
    @PostMapping("/card/recharge/page")
    public BaseReportResultDto<List<CardRechargeOrderDto>, CardRechargeOrderSumDto> queryRechargePageList(@RequestBody CardRechargePageEntity request) throws ServiceException {
        return ucardService.queryRechargePageList(request);
    }

    /**
     * 查询卡片余额
     */
    @PostMapping("/card/balance")
    public BaseResultDto<WasabiBalanceInfoDto> queryCardBalance(@RequestBody WasabiBalanceInfoEntity request) throws ServiceException {
        return wasabiCardService.getBalanceInfo(request);
    }

    /**
     * 查询充值订单
     */
    @PostMapping("/card/recharge/order")
    public BaseResultDto queryRechargeOrder(@RequestBody CardRechargeOrderQueryEntity request) throws Exception {
        return wasabiCardService.queryDepositOrder(request);
    }

    /**
     * 修改密码
     */
    @PostMapping("/card/password/reset")
    public BaseResultDto<WasabiUpdatePinDto> resetPassword(@RequestBody WasabiUpdatePinEntity entity,
                                                           InfoEntity infoEntity) throws ServiceException {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.updatePin(entity);
    }

    /**
     * 冻结卡片
     */
    @PostMapping("/card/freeze")
    public BaseResultDto freezeCard(@RequestBody WasabiFreezeAndUnfreezeEntity request, InfoEntity infoEntity) throws Exception {
        request.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.cardFreeze(request);
    }

    /**
     * 解冻卡片
     */
    @PostMapping("/card/unfreeze")
    public BaseResultDto unfreezeCard(@RequestBody WasabiFreezeAndUnfreezeEntity request, InfoEntity infoEntity) throws Exception {
        request.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.cardUnfreeze(request);
    }

    /**
     * 查询交易记录分页列表
     */
    @PostMapping("/card/transac/page")
    public ResultWithPagerDto<CardTransacOrderDto> getTransactionPageList(@RequestBody CardTransacOrderPageEntity request) throws ServiceException {
        return ucardService.getTransacOrderPageList(request);
    }

    /**
     * 获取交易纪录详情
     */
    @PostMapping("/card/transac/single")
    public BaseResultDto getTransactionSingle(@RequestBody SingleLongEntity entity) throws ServiceException {
        return BaseResultDto.success(ucardApiService.getTransactionSingle(entity));
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload/file")
    public BaseResultDto uploadFile(@RequestParam(value = "file") MultipartFile file) throws Exception {
        String middlePath = "/wasabi";
        wasabiCardService.validatedFile(file);
        String path = wasabiCardService.commonUpload(file, middlePath);
        return BaseResultDto.success(Constants.UPLOAD_SUCCESS, path);
    }

    /**
     * 查询国家和城市
     */
    @PostMapping("/card/country")
    public BaseResultDto getCardCountry(@RequestBody CardCountryEntity request) throws ServiceException {
        request.setCardCategory(2);
        return BaseResultDto.success(ucardService.getCardCountryList(request));
    }

    /**
     * 查询职业信息
     */
    @PostMapping("/card/occupation/list")
    public BaseResultDto<List<WasabiOccupationsDto>> getOccupationList() throws ServiceException {
        return wasabiCardService.getOccupationList();
    }

    /**
     * 权限验证
     */
    @PostMapping("/card/permission/verify")
    public BaseResultDto permissionVerify(InfoEntity infoEntity) throws ServiceException {
        return wasabiCardService.permissionVerify(infoEntity.getCustomInfo());
    }

    /**
     * 扫码上传文件
     */
    @PostMapping("/scan/upload/file")
    public BaseResultDto scanUpload(@RequestBody CardWebSocketEntity entity) throws ServiceException {
        return wasabiCardService.scanUpload(entity);
    }

    /**
     * 证件类型配置列表
     */
    @PostMapping("/card/id/type/config/list")
    public ResultWithPagerDto<CardIdTypeConfigDto> getCardIdTypeConfigList(@RequestBody CardIdTypeConfigPageEntity entity) throws ServiceException {
        return wasabiCardService.getCardIdTypeConfigList(entity);
    }

    /**
     * 查询支持的城市列表
     */
    @PostMapping("/global/query/bank/cities")
    public BaseResultDto queryBankCities(@RequestBody CardBankCitiesEntity entity) throws ServiceException {
        return wasabiCardService.queryBankCities(entity);
    }

    /**
     * 查询CVV 发送短信验证码
     */
    @PostMapping("/query/cvv/send/code")
    public BaseResultDto queryCvvSendCode(@RequestBody @Validated CardQueryCvvSendEmailCodeEntity entity,
                                          HttpServletRequest req) throws ServiceException {

        entity.setIp(GetIpAndMac.getIp(req));
        entity.setTime(new Date());
        wasabiCardService.queryCvvSendCode(entity);
        return BaseResultDto.success(Constants.SEND_SUCCESS);
    }

    /**
     * 验证邮箱验证码查询cvv
     */
    @PostMapping("/query/cvv/verify/code")
    public BaseResultDto queryCvvVerifyCode(@RequestBody @Validated CardQueryCvvVerifyEmailCodeEntity entity) throws Exception {
        return wasabiCardService.queryCvvVerifyCode(entity);
    }

    @PostMapping("/account/dropdown")
    public BaseResultDto<List<AccountDropdownDto>> accountDropdown(@RequestBody AccountInfoListEntity entity, InfoEntity infoEntity) throws Exception {
        entity.setCustomId(infoEntity.getCustomInfo().getId());

        BaseResultDto<List<AccountInfoDto>> resultDto = accountInfoFeignService.accountDropdown(entity);
        if (resultDto.getCode() == 200) {
            List<AccountDropdownDto> dropdownDtos = Lists.newArrayList();
            List<AccountInfoDto> dtos = resultDto.getData();
            dtos.forEach((item) -> {
                AccountDropdownDto accountDropdownDto = new AccountDropdownDto();
                BeanUtils.copyProperties(item, accountDropdownDto);
                dropdownDtos.add(accountDropdownDto);
            });
            return BaseResultDto.success(dropdownDtos);

        } else {
            return BaseResultDto.error(resultDto.getMsg());
        }

    }

    /**
     * 查询汇率
     */
    @PostMapping("/global/query/exchange/rate")
    public BaseResultDto queryExchangeRate(@RequestBody GlobalQueryExchangeRateEntity entity) throws ServiceException {
        return BaseResultDto.success(wasabiCardService.queryExchangeRate(entity));
    }

    /**
     * 查询账户信息
     */
    @PostMapping("/card/account/dropdown")
    public BaseResultDto cardAccountDropdown(InfoEntity infoEntity) throws ServiceException {
        CardAccountDropdownEntity entity = new CardAccountDropdownEntity();
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.cardAccountDropdown(entity);
    }

    /**
     * 创建交易订单
     */
    @PostMapping("/global/create/order")
    public BaseResultDto globalCreateOrder(@RequestBody GlobalCreateOrderEntity entity, InfoEntity infoEntity) throws Exception {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.globalCreateOrder(entity);
    }

    /**
     * 速汇订单分页列表
     */
    @PostMapping("/global/order/page/list")
    public ResultWithPagerDto<GlobalOrderDto> globalOrderPageList(@RequestBody GlobalOrderPageEntity entity, InfoEntity infoEntity) throws Exception {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.globalOrderPageList(entity);
    }

    /**
     * 补充资料
     */
    @PostMapping("/global/supplementary/data")
    public BaseResultDto supplementaryData(@RequestBody WasabiTransactionSubmitRfiEntity entity, InfoEntity infoEntity) throws Exception {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.supplementaryData(entity);
    }

    /**
     * 支持的币种下拉列表
     */
    @PostMapping("/global/currencies/dropdown")
    public BaseResultDto getCurrenciesDropdown(@RequestBody GlobalCurrenciesDropdownEntity entity) throws ServiceException {
        return wasabiCardService.getCurrenciesDropdown(entity);
    }

    /**
     * 币种字段和可选值列表
     */
    @PostMapping("/global/currencies/field/list")
    public BaseResultDto getCurrenciesFieldList(@RequestBody @Validated GlobalCurrenciesFieldListEntity entity) throws ServiceException {
        return wasabiCardService.getCurrenciesFieldList(entity);
    }

    /**
     * 查询速汇订单详情
     */
    @PostMapping("/global/order/details")
    public BaseResultDto queryGlobalOrderDetails(@RequestBody BaseEntity entity) throws ServiceException {
        return wasabiCardService.queryGlobalOrderDetails(entity);
    }

    /**
     * 取消交易订单
     */
    @PostMapping("/global/cancel/order")
    public BaseResultDto globalCancelOrder(@RequestBody GlobalCancelOrderEntity entity, InfoEntity infoEntity) throws Exception {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.globalCancelOrder(entity);
    }

    /**
     * 速汇查询用户详情
     */
    @PostMapping("/global/user/details")
    public BaseResultDto findGlobalUserDetails(InfoEntity entity) throws ServiceException {
        return wasabiCardService.findGlobalUserDetails(entity);
    }

    /**
     * 获取收款用户列表
     */
    @PostMapping("/global/receiver/user/list")
    BaseResultDto getGlobalReceiverUserList(@RequestBody GlobalReceiverUserEntity entity) throws ServiceException {
        return wasabiCardService.getGlobalReceiverUserList(entity);
    }

    /**
     * 删除收款用户
     */
    @PostMapping("/global/receiver/user/delete")
    BaseResultDto deleteGlobalReceiverUser(@RequestBody BaseEntity entity) throws ServiceException {
        return wasabiCardService.deleteGlobalReceiverUser(entity);
    }

    /**
     * 区块链配置下拉列表
     */
    @PostMapping("/card/blockchain/config/dropdown")
    BaseResultDto getCardBlockchainConfigDropdown(@RequestBody CardBlockchainConfigDropdownEntity entity) throws ServiceException {
        return wasabiCardService.getCardBlockchainConfigDropdown(entity);
    }

    /**
     * 加密货币交易分页列表
     */
    @PostMapping("/encrypted/wallet/transaction/page")
    ResultWithPagerDto<EncryptedWalletTransactionDto> getEncryptedWalletTransactionPage(@RequestBody EncryptedWalletTransactionPageEntity entity, InfoEntity infoEntity) throws ServiceException {
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.getEncryptedWalletTransactionPage(entity);
    }

    /**
     * 卡扣款分页列表
     */
    @PostMapping("/card/withdraw/page")
    ResultWithPagerDto<CardWithdrawDto> queryCardWithdrawPage(@RequestBody CardWithdrawPageEntity entity, InfoEntity infoEntity) throws ServiceException{
        entity.setCId(infoEntity.getCustomInfo().getCId());
        return wasabiCardService.queryCardWithdrawPage(entity);
    }

}
