package com.jeequan.jeepay.mch.ctrl.payment;

import com.alibaba.fastjson.JSONObject;
import com.jeequan.jeepay.JeepayClient;
import com.jeequan.jeepay.core.constants.CS;
import com.jeequan.jeepay.core.exception.BizException;
import com.jeequan.jeepay.core.jwt.JWTPayload;
import com.jeequan.jeepay.core.model.ApiRes;
import com.jeequan.jeepay.core.model.DBApplicationConfig;
import com.jeequan.jeepay.core.utils.SeqKit;
import com.jeequan.jeepay.db.entity.*;
import com.jeequan.jeepay.db.entity.MchAppEntity;
import com.jeequan.jeepay.db.entity.MchApplyment;
import com.jeequan.jeepay.db.entity.MchStoreDevice;
import com.jeequan.jeepay.db.entity.PayOrder;
import com.jeequan.jeepay.exception.JeepayException;
import com.jeequan.jeepay.mch.ctrl.CommonCtrl;
import com.jeequan.jeepay.mch.ctrl.paytest.PaytestController;
import com.jeequan.jeepay.model.DeviceInfo;
import com.jeequan.jeepay.request.PayOrderCreateRequest;
import com.jeequan.jeepay.response.PayOrderCreateResponse;
import com.jeequan.jeepay.service.impl.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/*
* 支付测试类
*
* @author zx
*
* @date 2021/6/22 9:43
*/
@RestController
@RequestMapping("/api/pay/app")
public class AppPaymentController extends CommonCtrl {

    @Autowired private MchAppService mchAppService;
    @Autowired private SysConfigService sysConfigService;
    @Autowired private MchStoreService mchStoreService;
    @Autowired private SysUserService sysUserService;
    @Autowired private MchApplymentService mchApplymentService;

    /** 商户APP、刷脸设备下单接口 **/
    @PostMapping
    public ApiRes doPay() {

        //获取请求参数
        Long amount = getRequiredAmountL("amount");
        String wayCode = getValStringRequired("wayCode");

        // 前端明确了支付参数的类型 payDataType
        String payDataType = getValString("payDataType");
        String authCode = getValString("authCode");

        // 收银员ID
        Long storeUserId = getCurrentUser().getSysUserId();

        PayOrderCreateRequest orderCreateRequest = new PayOrderCreateRequest();
        PaytestController.PayOrderCreateReqModelAddStoreId model = new PaytestController.PayOrderCreateReqModelAddStoreId();
        model.setPas(SysConfigService.PLATFORM_API_SECRET); // 通信秘钥
        orderCreateRequest.setBizModel(model);

        String storeId = getValString("storeId");
        String appId = getValString("appId");

        // 刷脸设备，设置其门店、应用、设备信息
        if (JWTPayload.LOGIN_PAGE_TYPE.FACE_APP.equals(getCurrentUser().getLoginType())) {
            MchStoreDevice mchStoreDevice = sysUserService.checkFaceApp(getCurrentUser().getSysUser(), request.getHeader(CS.FACE_DEVICE_NAME));

            DeviceInfo deviceInfo = new DeviceInfo();
            deviceInfo.setDeviceNo(mchStoreDevice.getDeviceNo());
            deviceInfo.setProvider(mchStoreDevice.getProvider());
            deviceInfo.setDeviceType(PayOrder.DEVICE_TYPE_FACE_APP);
            model.setDeviceInfo(deviceInfo); // 设备信息

            storeId = mchStoreDevice.getStoreId(); // 门店
        }
        MchStore store = mchStoreService.getById(storeId);
        Assert.notNull(store,"门店信息异常");
        MchApplyment mchApplyment = mchApplymentService.getById(store.getMchApplyId());
        Assert.notNull(mchApplyment,"商户信息异常");
        Assert.isTrue(mchApplyment.isPay(),"商户还未进件通过或状态不正确");
        MchAppEntity mchAppEntity = mchAppService.getById(mchApplyment.getAutoConfigMchAppId());
        if(mchAppEntity == null || mchAppEntity.getState() != CS.PUB_USABLE){
            throw new BizException("应用不存在或不可用");
        }
        if(CS.PAY_WAY_CODE.AUTO_BAR.equals(wayCode)){
            if(mchApplyment.getScanPayPerm() != CS.YES){
                throw new BizException("当前商户未开通反扫功能");
            }
        }

        model.setStoreId(storeId); // 门店ID
        model.setStoreUserId(storeUserId); // 收银员ID
        model.setMchNo(getCurrentMchNo()); // 商户号
        model.setAppId(mchAppEntity.getAppId());
        model.setMchOrderNo(SeqKit.genMhoOrderId());
        model.setWayCode(wayCode);
        model.setAmount(amount);
        model.setCurrency("CNY");
        model.setClientIp(getClientIp());
        model.setSubject( mchApplyment.getMchShortName()+ "商户APP收银");
        model.setBody( mchApplyment.getMchShortName()+ "商户APP收银");
        model.setSellerRemark(getValString("sellerRemark")); // 卖家备注

        DBApplicationConfig dbApplicationConfig = sysConfigService.getDBApplicationConfig();

        model.setNotifyUrl(dbApplicationConfig.getMchSiteUrl() + "/api/anon/paytestNotify/payOrder"); //回调地址

        //设置扩展参数
        JSONObject extParams = new JSONObject();
        if(StringUtils.isNotEmpty(payDataType)) {
            extParams.put("payDataType", payDataType.trim());
        }
        if(StringUtils.isNotEmpty(authCode)) {
            extParams.put("authCode", authCode.trim());
        }
        model.setChannelExtra(extParams.toString());
        String paySiteUrl = dbApplicationConfig.getPaySiteUrl();
//        String paySiteUrl = "http://192.168.1.24:9216";
        JeepayClient jeepayClient = new JeepayClient(paySiteUrl, mchAppEntity.getAppSecret());

        try {
            PayOrderCreateResponse response = jeepayClient.execute(orderCreateRequest);
            if(response.getCode() != 0){
                throw new BizException(response.getMsg());
            }
            return ApiRes.ok(response.get());
        } catch (JeepayException e) {
            throw new BizException(e.getMessage());
        }
    }

}
