package com.iformall.controller;

import com.iformall.common.ErrorCode;
import com.iformall.common.Result;
import com.iformall.common.ResultData;
import com.iformall.domain.po.WxAppinfo;
import com.iformall.domain.po.WxPayBill;
import com.iformall.enums.EnumPayStatus;
import com.iformall.enums.EnumPayWay;
import com.iformall.exception.MallinkException;
import com.iformall.service.WxPayBillService;
import com.iformall.utils.IPUtil;
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.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author gongbiao
 */
@RestController
@RequestMapping("/api/pay")
@Api(description = "账单支付接口")
public class WxPayBillController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private WxPayBillService wxPayBillService;

    @ApiOperation(value = "发起微信小程序支付订单", notes = "{\"billId\":\"string\",\"appId\":\"string\",\"openId\":\"string\",\"bUserId\":\"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());
        //bill参数不能为空
        String billIdStr = paramMap.get("billId");
        if (StringUtils.isEmpty(billIdStr)) {
            logger.info("billId不能为空: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "billId不能为空");
        }
        //bill参数要为Long
        Long billId;
        try {
            billId = Long.valueOf(billIdStr);
        } catch (NumberFormatException e) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "billId参数不正确");
        }

        //b_user_id
        String bUserIdStr = paramMap.get("bUserId");
        if (StringUtils.isEmpty(bUserIdStr)) {
            logger.info("bUserId不能为空: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "bUserId不能为空");
        }

        //b_user_id参数要为Long
        Long bUserId;
        try {
            bUserId = Long.valueOf(bUserIdStr);
        } catch (NumberFormatException e) {
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "bUserId参数不正确");
        }
        //appid
        String appid = paramMap.get("appId");
        //openid
        String openid = paramMap.get("openId");
        //获取小程序配置信息
        WxAppinfo appInfo = getAppInfo(appid);
        //支付账单参数
        WxPayBill record = new WxPayBill();
        record.setBillId(billId);
        record.setOpenId(openid);
        record.setbUserId(bUserId);
        record.setTenantId(appInfo.getTenantId());
        try {
            record.setIp(IPUtil.getIpAddr(request));
            return wxPayBillService.createPayBill(appInfo, 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 = "{\"payBillId\":\"string\",\"billId\":\"string\",\"status\":integer,\"reason\":\"string\"}")
    @PostMapping("/updatePayBill")
    public ResultData updatePayBill(@RequestBody Map<String, Object> paramMap) {
        logger.info("/api/pay/updatePayBill" + paramMap.toString());
        String billIdStr = (String) paramMap.get("billId");
        String reasonStr = (String) paramMap.get("reason");
        Integer status = (Integer) paramMap.get("status");
        if (StringUtils.isEmpty(billIdStr)) {
            logger.info("billId不能为空: " + paramMap.toString());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "billId不能为空");
        }
        Long billId = 0L;
        try {
            billId = Long.valueOf(billIdStr);
        } catch (NumberFormatException e) {
            logger.error("billId参数不正确: " + paramMap.toString() + ", e:" + e.getMessage());
            return new ResultData(ErrorCode.SYS_PARAMETER_NOT_NULL.getCode(), "billId参数不正确");
        }


        WxPayBill payBill = new WxPayBill();
        payBill.setBillId(billId);
        payBill = wxPayBillService.queryPayBill(payBill);
        if(payBill==null){
            return new ResultData(ErrorCode.BILL_ROUTINE_IS_NOT_FOUND);
        }
        try {
            //前端返回状态成功时
            if(status.equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
                //查询数据是否已经通过回调修改成功，成功什么也不做，因为已经通过回调修改了数据
                if(payBill.getPayBillStatus().equals(EnumPayStatus.PAY_STATUS_SUCCESS.getCode())) {
                    return new ResultData(Result.SUCCESS, "支付状态更新成功");
                }
            }
            //前端返回状态失败时，修改数据状态为支付失败,
            if(!billId.equals(payBill.getBillId())){
               logger.info("传入的账单ID与数据表中账单ID不匹配");
            }
            payBill.setPayBillStatus(status);
            payBill.setFailReason(reasonStr);
            wxPayBillService.updatePayBillStatus(payBill);
            return new ResultData(Result.SUCCESS, "支付状态更新成功");
        } catch (MallinkException e) {
            logger.error("支付状态更新失败2: " + payBill.toString() + ", e:" + e.getMessage());
            return new ResultData(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("支付状态更新失败3: " + payBill.toString() + ", e:" + e.getMessage());
            return new ResultData(ErrorCode.PAY_ORDER_ERROR, "支付状态更新失败3: " + payBill.toString() + ", e:" + e.getMessage());
        }
    }



}
