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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.liquidnet.common.exception.constant.ErrorCode;
import com.liquidnet.common.swagger.config.SwaggerApiVersion;
import com.liquidnet.service.ResponseDto;
import com.liquidnet.service.adam.config.swagger.AdamSwaggerApiVersionConstant;
import com.liquidnet.service.adam.constant.AdamBeneficiaryConstants;
import com.liquidnet.service.adam.constant.AdamPayerConstants;
import com.liquidnet.service.adam.dto.base.AdamCurrentUser;
import com.liquidnet.service.adam.dto.query.AdamBeneficiaryQuery;
import com.liquidnet.service.adam.interceptor.annotation.RequiresPermissions;
import com.liquidnet.service.adam.service.feign.bank.IAdamFeignBankCcBeneficiaryService;
import com.liquidnet.service.adam.vo.AdamBeneficiaryEnumVo;
import com.liquidnet.service.adam.dto.AdamBeneficiaryParam;
import com.liquidnet.service.adam.dto.base.AdamResultDto;
import com.liquidnet.service.adam.entity.AdamBeneficiary;
import com.liquidnet.service.adam.interceptor.annotation.NoAuth;
import com.liquidnet.service.adam.service.IAdamBeneficiaryService;
import com.liquidnet.service.adam.util.CurrentUserUtil;
import com.liquidnet.service.adam.util.EnumUtil;
import com.liquidnet.service.adam.vo.AdamBeneficiaryVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * <p>
 * 收款人信息 前端控制器
 * </p>
 *
 * @author liquidnet
 * @since 2020-11-02
 */
@Api(tags = "web beneficiary")
@Slf4j
@RestController
@RequestMapping("/adam-beneficiary")
public class AdamBeneficiaryController {

    @Autowired
    private IAdamBeneficiaryService adamBeneficiaryService;

    @Autowired
    private IAdamFeignBankCcBeneficiaryService adamFeignBankCcBeneficiaryService;

    @NoAuth
    @ApiOperation(value = "enum list")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @GetMapping("/enum_list")
    public ResponseDto<AdamBeneficiaryEnumVo> enumList() {
        AdamBeneficiaryEnumVo vo = new AdamBeneficiaryEnumVo();
        // 公司类型
        vo.setPaymentMethodPriorityChargeTypeList(EnumUtil.getList(AdamBeneficiaryConstants.PaymentMethodPriorityChargeTypeEnum.values()));
        return ResponseDto.success(vo);
    }

    @ApiOperation(value = "get")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @GetMapping("/get")
    public ResponseDto<AdamBeneficiary> get(HttpServletRequest request,
                                            @RequestParam String id) {
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            AdamResultDto<AdamBeneficiary> adamResultDto = adamBeneficiaryService.select(id, currentUser.getComId());
            ResponseDto responseDto = AdamResultDto.getResponseDto(adamResultDto);
            return responseDto;
        } catch (Exception e) {
            log.error("get beneficiary.error", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "list")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @GetMapping("/list")
    public ResponseDto list(HttpServletRequest request) {
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            AdamBeneficiaryParam selectParam = new AdamBeneficiaryParam();
            selectParam.setComId(currentUser.getComId());
            selectParam.setStatus(AdamPayerConstants.StatusEnum.NORMAL.getCode());
            List<AdamBeneficiary> list = adamBeneficiaryService.selectList(selectParam);
            return ResponseDto.success(list);
        } catch (Exception e) {
            log.error("list beneficiary.error", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

    @RequiresPermissions("A06B0297")
    @ApiOperation(value = "page")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @GetMapping("/page")
    public ResponseDto<Page<AdamBeneficiaryVo>> pageList(HttpServletRequest request,
                                                         @RequestParam(required = false) String search,
                                                         @RequestParam(required = false, value = "pageNum", defaultValue = "1") Integer pageNum,
                                                         @RequestParam(required = false, value = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            String comId = currentUser.getComId();
            AdamBeneficiaryQuery selectParam = new AdamBeneficiaryQuery();
            selectParam.setComId(comId);
            selectParam.setStatus(AdamBeneficiaryConstants.StatusEnum.NORMAL.getCode());
            selectParam.setSearch(search);
            Page<AdamBeneficiary> adamBeneficiaryPage = adamBeneficiaryService.selectPage(pageNum, pageSize, selectParam);

            List<AdamBeneficiaryVo> recordsDisplay = Lists.newArrayList();
            adamBeneficiaryPage.getRecords().forEach(r -> {
                AdamBeneficiaryVo vo = new AdamBeneficiaryVo();
                BeanUtils.copyProperties(r, vo);
                AdamBeneficiaryConstants.LegalEntityTypeEnum typeEnum = AdamBeneficiaryConstants.LegalEntityTypeEnum.getEnumByCode(r.getLegalEntityType());
                vo.setTypeDesc(typeEnum != null ? typeEnum.getDesc() : null);
                recordsDisplay.add(vo);
            });

            Page<AdamBeneficiaryVo> page = new Page<>();
            BeanUtils.copyProperties(adamBeneficiaryPage, page);
            page.setRecords(recordsDisplay);
            return ResponseDto.success(page);

        } catch (Exception e) {
            log.error("page beneficiary.error", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

    @RequiresPermissions("803598E3")
    @ApiOperation(value = "create")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @PostMapping("/create")
    public ResponseDto create(HttpServletRequest request,
                              @ModelAttribute AdamBeneficiary param) {
        String logFx = "create beneficiary.";

        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            log.info(logFx + "comId=[{}],AdamBeneficiary=[{}]", currentUser.getComId(), JSON.toJSONString(param, SerializerFeature.WriteMapNullValue));
            param.setComId(currentUser.getComId());
            AdamResultDto adamResultDto = adamBeneficiaryService.create(param);
            ResponseDto responseDto = AdamResultDto.getResponseDto(adamResultDto);
            return responseDto;
        } catch (Exception e) {
            log.error(logFx + "error", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

    @RequiresPermissions("803598E3")
    @ApiOperation(value = "edit")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @PostMapping("/edit")
    public ResponseDto update(HttpServletRequest request,
                              @ModelAttribute AdamBeneficiary param) {
        String logFx = "edit beneficiary.";

        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            log.info(logFx + "comId=[{}],AdamBeneficiary=[{}]", currentUser.getComId(), JSON.toJSONString(param, SerializerFeature.WriteMapNullValue));
            param.setComId(currentUser.getComId());
            AdamResultDto adamResultDto = adamBeneficiaryService.update(param);
            ResponseDto responseDto = AdamResultDto.getResponseDto(adamResultDto);
            return responseDto;
        } catch (Exception e) {
            log.error(logFx + "error", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

    @RequiresPermissions("803598E3")
    @ApiOperation(value = "delete")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @PostMapping("/delete")
    public ResponseDto delete(HttpServletRequest request,
                              @RequestParam String id) {
        String logFx = "delete beneficiary.";
        try {
            AdamCurrentUser currentUser = CurrentUserUtil.getCurrentUser(request);
            log.info(logFx + "comId=[{}],id=[{}]", currentUser.getComId(), id);
            AdamResultDto adamResultDto = adamBeneficiaryService.delete(id, currentUser.getComId());
            ResponseDto responseDto = AdamResultDto.getResponseDto(adamResultDto);
            return responseDto;
        } catch (Exception e) {
            log.error(logFx + "error", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

    @NoAuth
    @ApiOperation(value = "required details")
    @SwaggerApiVersion(group = AdamSwaggerApiVersionConstant.WEB_1_1)
    @PostMapping("/required_details")
    public ResponseDto<List<Map<String, String>>> requiredDetails(HttpServletRequest request,
                                                                  @RequestParam("currency") String currency,
                                                                  @RequestParam("bankAccountCountry") String bankAccountCountry,
                                                                  @RequestParam("beneficiaryCountry") String beneficiaryCountry) {
        String logFx = "delete beneficiary.";
        try {
            AdamResultDto<List<Map<String, String>>> listAdamResultDto = adamFeignBankCcBeneficiaryService.requiredDetails(currency, bankAccountCountry, beneficiaryCountry);
            return AdamResultDto.getResponseDto(listAdamResultDto);
        } catch (Exception e) {
            log.error(logFx + "error", e);
            return ResponseDto.failure(ErrorCode.HTTP_SYSTEM_ERROR);
        }
    }

}
