package com.crm.ucard.controller;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.dto.base.BaseReportResultDto;
import com.crm.rely.backend.core.dto.base.BaseResultDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
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.system.reasons.refusal.SysReasonsRefusalSearchDto;
import com.crm.rely.backend.core.dto.ucard.*;
import com.crm.rely.backend.core.dto.wasabi.WasabiActiveCardDto;
import com.crm.rely.backend.core.dto.wasabi.WasabiBalanceInfoDto;
import com.crm.rely.backend.core.dto.wasabi.WasabiOccupationsDto;
import com.crm.rely.backend.core.dto.wasabi.WasabiUpdatePinDto;
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.system.reasons.refusal.SysReasonsRefusalSearchEntity;
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;
import java.util.Map;

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

    @Autowired
    private UcardCardService ucardCardService;
    @Autowired
    private CustomInfoService customInfoService;
    @Autowired
    private AccountInfoFeignService accountInfoFeignService;
    @Autowired
    private WasabiDocumentApiService wasabiDocumentApiService;
    @Autowired
    private UcardPermissionService ucardPermissionService;
    @Autowired
    private KycService kycService;
    @Autowired
    private UcardFileService ucardFileService;
    @Autowired
    private UcardTypeConfigService ucardTypeConfigService;
    @Autowired
    private UcardEmailService ucardEmailService;
    @Autowired
    private GlobalService globalService;
    @Autowired
    private UcardBlockchainService ucardBlockchainService;
    @Autowired
    private VaultodyService vaultodyService;
    @Autowired
    private SysReasonsRefusalService sysReasonsRefusalService;
    @Autowired
    private UcardAppVersionService ucardAppVersionService;
    @Autowired
    private UcardAppCommonProblemService ucardAppCommonProblemService;
    @Autowired
    private UcardAppPrivacyPolicyService ucardAppPrivacyPolicyService;
    @Autowired
    private UcardAppCommonProblemTypeService ucardAppCommonProblemTypeService;

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

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

    /**
     * 身份认证获取web链接
     *
     * @param entity
     * @return
     */
    @PostMapping("/getWebsdkLink")
    public BaseResultDto getWebsdkLink(@RequestBody WebsdkLinkAliEntity entity, InfoEntity infoEntity) throws Exception {
        return kycService.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 ucardCardService.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 ucardCardService.updateMerchantUser(request);
    }


    /**
     * 更新用户邮寄地址
     */
    @PostMapping("/merchant/user/address/update")
    public BaseResultDto updateUserMailingAddress(@RequestBody WasabiSaveUserMailingAddressEntity request) throws ServiceException {
        return ucardCardService.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 ucardCardService.merchantUserSingle(infoEntity.getCustomInfo().getId());
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * 上传文件
     */
    @PostMapping("/upload/file")
    public BaseResultDto uploadFile(@RequestParam(value = "file") MultipartFile file) throws Exception {
        String middlePath = "/wasabi";
        wasabiDocumentApiService.validatedFile(file);
        String path = ucardFileService.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(ucardCardService.getCardCountryList(request));
    }

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

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

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

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

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

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

    /**
     * 验证邮箱验证码查询cvv
     */
    @PostMapping("/query/cvv/verify/code")
    public BaseResultDto queryCvvVerifyCode(@RequestBody @Validated CardQueryCvvVerifyEmailCodeEntity entity) throws Exception {
        return ucardEmailService.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 Exception {
        return BaseResultDto.success(globalService.queryExchangeRate(entity));
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    /**
     * 拒绝理由单个查询
     *
     * @param entity
     * @return
     * @throws Exception
     */
    @PostMapping("/reasons/refusal/search/single")
    public BaseResultDto searchLingle(@RequestBody @Validated SingleLongEntity entity) throws Exception {

        SysReasonsRefusalSearchDto result = sysReasonsRefusalService.searchSingle(entity);

        return BaseResultDto.success(result);
    }

    @PostMapping("/reasons/refusal/list")
    public BaseResultDto list(@RequestBody @Validated SysReasonsRefusalSearchEntity entity) throws Exception {

        BaseResultDto<Map<String, SysReasonsRefusalSearchDto>> result = sysReasonsRefusalService.searchList(entity);

        return result;
    }

    /**
     * 币种所有字段名称
     */
    @PostMapping("/global/field/params")
    public BaseResultDto getGlobalFieldParams() throws ServiceException {
        return globalService.getGlobalFieldParams();
    }

    /**
     * 获取最新一条app版本配置
     */
    @PostMapping("/card/app/version/detail")
    public BaseResultDto getLatestCardAppVersion(@RequestBody @Validated CardAppVersionDetailEntity entity) throws ServiceException {
        return ucardAppVersionService.getLatestCardAppVersion(entity);
    }

    /**
     * app常见问题列表
     */
    @PostMapping("/card/app/common/problem/page")
    ResultWithPagerDto<CardAppCommonProblemDto> getCardAppCommonProblemPageList(@RequestBody CardAppCommonProblemPageEntity entity) throws ServiceException{
        return ucardAppCommonProblemService.getCardAppCommonProblemPageList(entity);
    }

    /**
     * app隐私政策列表
     */
    @PostMapping("/card/app/privacy/policy/page")
    ResultWithPagerDto<CardAppPrivacyPolicyDto> getCardAppPrivacyPolicyPageList(@RequestBody CardAppPrivacyPolicyPageEntity entity) throws ServiceException{
        return ucardAppPrivacyPolicyService.getCardAppPrivacyPolicyPageList(entity);
    }

    /**
     * 常见问题类型下拉列表
     */
    @PostMapping("/card/app/common/problem/type/dropdown")
    BaseResultDto cardAppCommonProblemTypeDropdown(@RequestBody @Validated CardAppCommonProblemTypeDropdown entity) throws ServiceException{
        return ucardAppCommonProblemTypeService.cardAppCommonProblemTypeDropdown(entity);
    }

}
