package com.liquidnet.service.adam.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSupport;
import com.liquidnet.commons.lang.util.CurrentUtil;
import com.liquidnet.commons.lang.util.HttpUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.adam.dto.AdamMemberOrderCallbackResult;
import com.liquidnet.service.adam.dto.AdamMemberOrderCodeParam;
import com.liquidnet.service.adam.dto.AdamMemberOrderParam;
import com.liquidnet.service.adam.dto.AdamMemberOrderResult;
import com.liquidnet.service.adam.dto.vo.AdamMemberOrderPreviewVo;
import com.liquidnet.service.adam.dto.vo.AdamMemberOrderVo;
import com.liquidnet.service.adam.dto.vo.AdamRealInfoVo;
import com.liquidnet.service.adam.dto.vo.AdamUserInfoVo;
import com.liquidnet.service.adam.service.IAdamMemberOrderService;
import com.liquidnet.service.adam.service.IAdamRdmService;
import com.liquidnet.service.adam.service.IAdamRealNameService;
import com.liquidnet.service.adam.service.IAdamUserService;
import com.liquidnet.service.adam.service.admin.IAdamMemberPriceService;
import com.liquidnet.service.base.ErrorMapping;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.kylin.dto.vo.PayResultVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

@ApiSupport(order = 10031)
@Api(tags = "购买会员")
@Slf4j
@RestController
@RequestMapping("member/order")
public class AdamMemberOrderController {
    @Autowired
    Environment env;
    @Autowired
    IAdamMemberOrderService adamMemberOrderService;
    @Autowired
    IAdamMemberPriceService adamMemberPriceService;
    @Autowired
    IAdamRealNameService adamRealNameService;
    @Autowired
    IAdamUserService adamUserService;
    @Autowired
    IAdamRdmService adamRdmService;

    @ApiOperationSupport(order = 0)
    @ApiOperation(value = "购买会员预览")
    @GetMapping("preview/{mno}/{id}")
    public ResponseDto<AdamMemberOrderPreviewVo> preview(@PathVariable String mno, @PathVariable String id) {
        AdamMemberOrderPreviewVo previewVo = AdamMemberOrderPreviewVo.getNew();
        previewVo.setMemberId(mno);
        previewVo.setMemberTitle("摩登天空会员");
        AdamRealInfoVo realInfoVo = adamRealNameService.queryByUid(CurrentUtil.getCurrentUid());
        previewVo.setRealInfoVo(realInfoVo);
        previewVo.setPriceVo(adamMemberPriceService.query(mno, id));

        AdamUserInfoVo userInfoVo = adamRdmService.getUserInfoVoByUid(CurrentUtil.getCurrentUid());
        previewVo.setBirthday(null == userInfoVo ? null : userInfoVo.getBirthday());
        return ResponseDto.success(previewVo);
    }

    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "购买会员或会员码")
    @PostMapping("buy")
    public ResponseDto<AdamMemberOrderResult> buyMemberOrCode(@RequestBody AdamMemberOrderParam param) {
        try {
            log.info("member/order/buy:param:{}", JsonUtils.toJson(param));

            AdamRealInfoVo realInfoVo = adamRealNameService.queryByUid(CurrentUtil.getCurrentUid());
            if (null == realInfoVo) {
                if (StringUtils.isBlank(param.getName()) || StringUtils.isBlank(param.getIdCard())) {
                    return ResponseDto.failure(ErrorMapping.get("10101"));
                }
                adamUserService.identity(CurrentUtil.getCurrentUid(), param.getName(), param.getIdCard());
            }

            return adamMemberOrderService.buyMemberOrMemberCode(param);
        } catch (Exception e) {
            log.error("系统异常:购买会员或会员码", e);
            return ResponseDto.failure();
        }
    }

    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "使用兑换码")
    @PostMapping("use/memberCode")
    public ResponseDto<AdamMemberOrderResult> useMemberCode(@RequestBody AdamMemberOrderCodeParam param) {
        try {
            AdamRealInfoVo realInfoVo = adamRealNameService.queryByUid(CurrentUtil.getCurrentUid());
            if (null == realInfoVo) {
                if (StringUtils.isBlank(param.getName()) || StringUtils.isBlank(param.getIdCard())) {
                    return ResponseDto.failure(ErrorMapping.get("10101"));
                }
                adamUserService.identity(CurrentUtil.getCurrentUid(), param.getName(), param.getIdCard());
            }

            return adamMemberOrderService.useMemberCode(param);
        } catch (Exception e) {
            log.error("系统异常:使用兑换码", e);
            return ResponseDto.failure();
        }
    }

    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "会员订单列表")
    @GetMapping("list")
    public ResponseDto<List<AdamMemberOrderVo>> getMemberOrderList() {
        String currentUid = CurrentUtil.getCurrentUid();
        List<AdamMemberOrderVo> memberOrderList = adamMemberOrderService.getMemberOrderList(currentUid);
        return ResponseDto.success(memberOrderList);
    }

    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "会员订单详情")
    @GetMapping("info/{orderNo}")
    public ResponseDto<AdamMemberOrderVo> getMemberOrderList(@PathVariable String orderNo) {
        AdamMemberOrderVo memberOrderInfo = adamMemberOrderService.getMemberOrderInfo(CurrentUtil.getCurrentUid(), orderNo);
        return ResponseDto.success(memberOrderInfo);
    }

    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "会员支付回调")
    @PostMapping("callback")
    public void memberOrderCallBack(@RequestBody AdamMemberOrderCallbackResult result){
        ResponseDto<Object> dto = adamMemberOrderService.memberNotifyCallBack(result);
        if (!dto.isSuccess()) {
            log.warn(JsonUtils.toJson(dto));
        }
    }

    @ApiOperation(value = "会员订单状态")
    @GetMapping("check")
    public ResponseDto<Integer> checkOrderResult(@RequestParam @NotNull String orderNo) {
        AdamMemberOrderVo memberOrderInfo = adamMemberOrderService.getMemberOrderInfo(CurrentUtil.getCurrentUid(), orderNo);
        if (null == memberOrderInfo) {
            return ResponseDto.failure(ErrorMapping.get("10210"));
        }
        try {
            String rst = HttpUtil.get(env.getProperty("liquidnet.url-pay.check") + "?code=" + memberOrderInfo.getPayNo(), null);

            JsonNode rstJNode = JsonUtils.fromJson(rst, JsonNode.class);

            int status = Integer.parseInt(rstJNode.get("status").asText("0"));

            return ResponseDto.success(status == 1 ? status : 0);
        } catch (Exception e) {
            log.error("支付中心:会员订单状态查询失败:{}", orderNo, e);
            return ResponseDto.failure(ErrorMapping.get("10211"));
        }
    }
}
