package com.bweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.hfkj.common.exception.ErrorCode;
import com.hfkj.common.exception.ErrorHelp;
import com.hfkj.common.exception.SysCode;
import com.hfkj.common.security.UserCenter;
import com.hfkj.common.utils.ResponseMsgUtil;
import com.hfkj.entity.BsOrderSettle;
import com.hfkj.model.ResponseData;
import com.hfkj.service.order.BsOrderSettleLedgerService;
import com.hfkj.service.order.BsOrderSettleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="/orderSettle")
@Api(value="订单退款业务")
public class BsOrderSettleController {

    Logger log = LoggerFactory.getLogger(BsOrderSettleController.class);
    @Resource
    private BsOrderSettleService orderSettleService;
    @Resource
    private BsOrderSettleLedgerService orderSettleLedgerService;

    @RequestMapping(value="/getDetailByOrderNo",method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "查询交易详情")
    public ResponseData getDetailByOrderNo(@RequestParam(name = "orderNo", required = true) String orderNo) {
        try {
            // 查询结算信息
            BsOrderSettle orderSettle = orderSettleService.getData(orderNo);
            if (orderSettle == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到数据");
            }
            Map<String,Object> map = new HashMap<>();
            map.put("orderSettle", orderSettle);
            map.put("orderSettleLedger", orderSettleLedgerService.getListBySettleId(orderSettle.getId()));
            return ResponseMsgUtil.success(map);

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

    @RequestMapping(value="/revokeLedger",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "撤销分账")
    public ResponseData revokeLedger(@RequestBody JSONObject body) {
        try {
            if (body == null || StringUtils.isBlank(body.getString("orderNo"))) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.REQ_PARAMS_ERROR, "");
            }
            // 查询结算信息
            BsOrderSettle orderSettle = orderSettleService.getData(body.getString("orderNo"));
            if (orderSettle == null) {
                throw ErrorHelp.genException(SysCode.System, ErrorCode.COMMON_ERROR, "未找到数据");
            }
            orderSettleService.revokeLedger(orderSettle);

            return ResponseMsgUtil.success("操作成功");

        } catch (Exception e) {
            log.error("error!",e);
            return ResponseMsgUtil.exception(e);
        }
    }

}
