package com.liquidnet.service.adam.controller.web.conversion;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.common.swagger.config.SwaggerApiVersion;
import com.liquidnet.service.ResponseDto;
import com.liquidnet.service.adam.common.AdamErrorCode;
import com.liquidnet.service.adam.config.swagger.AdamSwaggerApiVersionConstant;
import com.liquidnet.service.adam.constant.AdamBankConstants;
import com.liquidnet.service.adam.dto.AdamConversionDateDto;
import com.liquidnet.service.adam.dto.AdamConversionParam;
import com.liquidnet.service.adam.dto.base.AdamCurrentUser;
import com.liquidnet.service.adam.dto.base.AdamResultDto;
import com.liquidnet.service.adam.entity.AdamBankCcAccount;
import com.liquidnet.service.adam.entity.AdamConversion;
import com.liquidnet.service.adam.interceptor.annotation.NoAuth;
import com.liquidnet.service.adam.interceptor.annotation.RequiresPermissions;
import com.liquidnet.service.adam.service.IAdamBankCcAccountService;
import com.liquidnet.service.adam.service.IAdamConversionApiService;
import com.liquidnet.service.adam.service.IAdamConversionService;
import com.liquidnet.service.adam.service.feign.bank.IAdamFeignBankCcRateService;
import com.liquidnet.service.adam.util.CurrentUserUtil;
import com.liquidnet.service.adam.vo.AdamConversionVo;
import com.liquidnet.service.bank.currencycloud.dto.BankCcRateDto;
import com.liquidnet.service.bank.currencycloud.dto.BankCcRateParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "web conversion")
@Slf4j
@RestController
@RequestMapping("/adam-conversion")
public class AdamConversionController {

    @Autowired
    private IAdamFeignBankCcRateService adamFeignBankCcRateService;

    @Autowired
    private IAdamBankCcAccountService adamBankCcAccountService;

    @Autowired
    private IAdamConversionService adamConversionService;

    @Autowired
    private IAdamConversionApiService adamConversionApiService;

    @RequiresPermissions("AEE5E22D")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @ApiOperation(value = "create conversion")
    @PostMapping(value = "/create")
    public ResponseDto<AdamConversionVo> create(@ModelAttribute AdamConversionParam param,
                                                HttpServletRequest request) {
        AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
        String comId = currentUser.getComId();
        String userId = currentUser.getId();
        String logFx = "create conversion.comId=[" + comId + "]," + "userId=[" + userId + "]";
        try {
            log.info(logFx + "comId=[{}],createParam=[{}]", comId, JSON.toJSONString(param, SerializerFeature.WriteMapNullValue));
            param.setComId(comId);
            param.setUserId(userId);
            AdamResultDto<AdamConversion> resultDto = adamConversionApiService.createConversion(param);
            ResponseDto responseDto = AdamResultDto.getResponseDto(resultDto);
            if (resultDto.isSuccess()) {
                AdamConversion data = resultDto.getData();
                // 查询返回前端需要展示的数据
                AdamConversion conversion = adamConversionService.selectById(data.getId());
                AdamConversionVo vo = new AdamConversionVo();
                vo.conversion(conversion);
                responseDto.setData(vo);
                // 换汇完成,准备给用户发送pdf邮件
                adamConversionApiService.sendConfirm1(conversion.getId(), conversion.getComId());

            }
            return responseDto;
        } catch (Exception e) {
            log.error(logFx + "error", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "detailed rate")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @GetMapping("/detailed_rate")
    public ResponseDto<BankCcRateDto> detailedRate(@ModelAttribute BankCcRateParam param, HttpServletRequest request) {
        AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
        AdamBankCcAccount adamBankCcAccount = adamBankCcAccountService.selectById(currentUser.getComId());
        if (adamBankCcAccount == null) {
            return ResponseDto.failure(AdamErrorCode.ADAM_ACCOUNT_004001.getCode(), AdamErrorCode.ADAM_ACCOUNT_004001.getVal());
        }
        param.setContactId(adamBankCcAccount.getContactId());
        return adamFeignBankCcRateService.detailedRate(param);
    }

    @NoAuth
    @ApiOperation(value = "get conversion dates")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @ApiImplicitParams({
            @ApiImplicitParam(type = "query", dataType = "String", name = "conversionPair", value = "Concatenated string of the two currencies converted, eg. \"USDEUR\".", example = "USDEUR", required = true),
            @ApiImplicitParam(type = "query", dataType = "String", name = "startDate", value = "Start date of conversion. ISO 8601 format YYYY-MM-DD.")
    })
    @GetMapping("/get_conversion_dates")
    public ResponseDto<AdamConversionDateDto> getConversionDates(HttpServletRequest request,
                                                                 @RequestParam String conversionPair,
                                                                 @RequestParam(required = false) String startDate) {
        String bankChannel = AdamBankConstants.BankChannelEnum.CURRENCY_CLOUD.getCode();
        AdamResultDto<AdamConversionDateDto> resultDto = adamConversionApiService.getConversionDates(bankChannel, conversionPair, startDate);
        return AdamResultDto.getResponseDto(resultDto);
    }

    @ApiOperation(value = "send confirmation")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_2)
    @GetMapping("/send_confirm")
    public ResponseDto sendConfirm(HttpServletRequest request,
                                   @RequestParam String conversionId) {
        AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
        String comId = currentUser.getComId();
        AdamResultDto resultDto = adamConversionApiService.sendConfirm1(conversionId, comId);
        return AdamResultDto.getResponseDto(resultDto);
    }

}
