package com.iformall.controller;

import com.github.pagehelper.PageInfo;
import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.*;
import com.iformall.enums.EnumCreditLockedStatus;
import com.iformall.enums.EnumPayStatus;
import com.iformall.enums.EnumPayWay;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxCUserBasicInfoService;
import com.iformall.service.WxOrderService;
import com.iformall.service.WxPayOrderService;
import com.iformall.utils.IPUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

@RestController
@RequestMapping("/api/pay")
@Api(description = "支付相关接口")
public class WxPayOrderController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxPayOrderService wxPayOrderService;

    @Autowired
    private WxOrderService wxOrderService;

    @Autowired
    private WxCUserBasicInfoService wxCUserBasicInfoService;

    @ApiOperation(value = "发起微信小程序支付订单", notes = "{\"orderId\":\"string\"}")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ResultData _create(@RequestBody Map<String, String> paramMap, HttpServletRequest request) throws Exception {
        logger.info("/api/pay/create" + paramMap.toString());
        String orderIdStr = paramMap.get("orderId");
        if (StringUtils.isBlank(orderIdStr)) {
            logger.info("orderId不能为空: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "orderId不能为空");
        }

        WxCUser user = getUser();
        WxCUserBasicInfo wxCUserBasicInfo = wxCUserBasicInfoService.getById(user.getId());
        if (null != wxCUserBasicInfo && EnumCreditLockedStatus.CLOSE.getCode().equals(wxCUserBasicInfo.getStatus())) {
            return new ResultData(ErrorCode.MEMBER_IS_LOCKED);
        }
        WxAppinfo appInfo = getAppInfo(user.getAppId());
        if(appInfo == null) {
            return new ResultData(ErrorCode.APP_ID_NOT_FOUND);
        }

        Long orderId = 0L;
        try {
            orderId = Long.valueOf(orderIdStr);
        } catch (NumberFormatException e) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "orderId参数不正确");
        }
        WxPayOrder record = new WxPayOrder();
        record.setOrderId(orderId);

        try {
            record.setIp(IPUtil.getIpAddr(request));
            return wxPayOrderService.createPayOrder(appInfo, user, record, EnumPayWay.PAY_WAY_WECHAT);
        } catch (MallinkException e) {
            logger.error("payment wechat, order create error, req 2: " + record.toString() + ", e:" + e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("payment wechat, order create error, req 3: " + record.toString() + ", e:" + e.getMessage());
            return new ResultData(ErrorCode.PAY_ORDER_ERROR, e.getMessage());
        }
    }

    @ApiOperation(value = "更新支付订单状态", notes = "{\"payOrderId\":\"string\",\"orderId\":\"string\",\"status\":integer,\"reason\":\"string\"}")
    @PostMapping("/updatePayOrder")
    public ResultData updatePayOrder(@RequestBody Map<String, Object> paramMap) {
        logger.info("/api/pay/updatePayOrder" + paramMap.toString());
        String payOrderIdStr = (String) paramMap.get("payOrderId");
        String orderIdStr = (String) paramMap.get("orderId");
        String reasonStr = (String) paramMap.get("reason");
        Integer status = (Integer) paramMap.get("status");
        if (StringUtils.isBlank(orderIdStr)) {
            logger.info("orderId不能为空: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "orderId不能为空");
        }
        Long payOrderId = 0L, orderId = 0L;
        try {
            orderId = Long.valueOf(orderIdStr);
        } catch (NumberFormatException e) {
            logger.error("orderId参数不正确: " + paramMap.toString() + ", e:" + e.getMessage());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "orderId参数不正确");
        }
        if (!StringUtils.isBlank(payOrderIdStr)) {
            try {
                payOrderId = Long.valueOf(payOrderIdStr);
            } catch (NumberFormatException e) {
                logger.error("payOrderId参数不正确: " + paramMap.toString() + ", e:" + e.getMessage());
                return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "payOrderId参数不正确");
            }
        }

        if(payOrderIdStr.equalsIgnoreCase("0")) {
            // 免费券直接返回成功
            return new ResultData(Result.SUCCESS, "免费券支付状态更新成功");
        }

        WxPayOrder payOrder = new WxPayOrder();
        payOrder.setId(payOrderId);
        payOrder.setOrderId(orderId);
        payOrder.setPayOrderStatus(status);
        payOrder.setFailReason(reasonStr);

        WxOrder order = null;

        try {
            //有价券支付成功
            if (status.equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
                // 前端提示支付成功, 不作为支付成功标志，只检查支付订单状态
                // 有价券不走update， callback更新
                payOrder = wxPayOrderService.getById(payOrderId);
                if (payOrder.getPayOrderStatus().equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
                    order = wxOrderService.getById(orderId);
                    return new ResultData(Result.SUCCESS, "支付状态更新成功", order);
                } else {
                    return new ResultData(ErrorCode.PAY_ORDER_ERROR, "支付未状态，请等待！！");
                }
            } else if (status.equals(EnumPayStatus.PAY_STATUS_FAIL.getCode())) {
                // 有价券支付失败
                wxPayOrderService.handlePayOrderFail(payOrder, EnumPayStatus.PAY_STATUS_FAIL.getCode());
            }
            return new ResultData(Result.SUCCESS, "支付状态更新成功");
        } catch (MallinkException e) {
            logger.error("支付状态更新失败2: " + payOrder.toString() + ", e:" + e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("支付状态更新失败3: " + payOrder.toString() + ", e:" + e.getMessage());
            return new ResultData(ErrorCode.PAY_ORDER_ERROR, "支付状态更新失败3: " + payOrder.toString() + ", e:" + e.getMessage());
        }
    }

    @ApiOperation("分页列表接口")
    @GetMapping("/list")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "页数", dataType = "int", paramType = "query", required = true),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "int", paramType = "query", required = true)})
    public ResultData list(@ModelAttribute WxPayOrder wxPayOrder, Integer pageNum, Integer pageSize) {
        if (null == wxPayOrder) {
            wxPayOrder = new WxPayOrder();
        }
        final PageInfo<WxPayOrder> page = wxPayOrderService.listAsPage(wxPayOrder, pageNum, pageSize);
        return new ResultData(page);
    }

    @ApiOperation("新增接口")
    @PostMapping("/add")
    public ResultData add(@RequestBody WxPayOrder wxPayOrder) {
        //Assert.notNull(wxPayOrder.getName(), "角色名不能为空");
        //Assert.isTrue(!checkUnique(sysRole.getName(), null), "重复的角色名");
        wxPayOrderService.saveOrUpdate(wxPayOrder);
        return new ResultData();
    }

    @ApiOperation("根据id更新接口")
    @PostMapping("/update")
    public ResultData update(@RequestBody WxPayOrder wxPayOrder) {
        wxPayOrderService.saveOrUpdate(wxPayOrder);
        return new ResultData();
    }

    @ApiOperation("根据id删除接口")
    @GetMapping("/del")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    public ResultData delete(Long id) {
        wxPayOrderService.deleteById(id);
        return new ResultData(Result.SUCCESS, "删除成功", null);
    }

    @ApiOperation("根据id查询接口")
    @GetMapping("/findById")
    @ApiImplicitParam(name = "id", value = "id", dataType = "Long", paramType = "query", required = true)
    public ResultData findById(Long id) {
        return new ResultData(Result.SUCCESS, "查询成功", wxPayOrderService.getById(id));
    }


}
