package com.zhongshu.card.server.core.service.payment;

import com.github.microservice.types.deviceUse.OrderFromType;
import com.github.microservice.net.ResultContent;
import com.github.microservice.types.payment.ChargeableType;
import com.github.microservice.types.payment.PaymentType;
import com.zhongshu.card.client.model.devices.order.DeviceQrCodeParam;
import com.zhongshu.card.client.model.payment.CreateOrderParam;
import com.zhongshu.card.server.core.dao.devices.DeviceInfoDao;
import com.zhongshu.card.server.core.domain.devices.DeviceInfo;
import com.zhongshu.card.server.core.domain.devices.DeviceProduct;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.org.UserAccount;
import com.zhongshu.card.server.core.domain.payment.ExpenseFlow;
import com.zhongshu.card.server.core.service.base.SuperService;
import com.zhongshu.card.server.core.service.devices.DeviceInfoServiceImpl;
import com.zhongshu.card.server.core.service.devices.deviceProduct.DeviceProductBindDeviceService;
import com.zhongshu.card.server.core.service.paySetting.ProjectPaySettingServiceImpl;
import com.zhongshu.card.server.core.util.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 设备--创建订单 扫码 -- 指纹  扫脸 等方式
 *
 * @author TRX
 * @date 2025/1/15
 */
@Slf4j
@Service
public class OrderService extends SuperService {

    @Autowired
    private DeviceProductBindDeviceService deviceProductBindDeviceService;

    @Autowired
    private DeviceInfoDao deviceInfoDao;

    @Autowired
    private ExpenseFlowServiceImpl expenseFlowService;

    @Autowired
    private DeviceInfoServiceImpl deviceInfoService;

    @Autowired
    private ProjectPaySettingServiceImpl projectPaySettingService;

    /**
     * 小程序扫 设备码 下单 (微信)
     *
     * @return
     */
    public ResultContent wxCToBQrCodeCreateOrder(DeviceQrCodeParam param) {
        if (StringUtils.isEmpty(param.getDeviceId())) {
            return ResultContent.buildFail("deviceId不能为空");
        }
        UserAccount userAccount = getCurrentUserAccount();
        DeviceInfo deviceInfo = deviceInfoDao.findTopByDeviceId(param.getDeviceId());
        if (ObjectUtils.isEmpty(deviceInfo)) {
            return ResultContent.buildFail("设备不存在");
        }

        // 检查设备是否绑定产品
        ResultContent<DeviceProduct> deviceProductResultContent = deviceProductBindDeviceService.checkAndGetDeviceProduct(deviceInfo.getDeviceId());
        if (deviceProductResultContent.isFailed()) {
            return ResultContent.buildFail(deviceProductResultContent.getMsg());
        }
        DeviceProduct deviceProduct = deviceProductResultContent.getContent();
        if (ObjectUtils.isEmpty(deviceProduct)) {
            return ResultContent.buildFail("设备未绑定产品信息不存在");
        }
        if (StringUtils.isEmpty(param.getProductProvideId()) && CommonUtil.bigDecimalIsEmpty(param.getAmount())) {
            return ResultContent.buildFail("消费金额不能为空");
        }

        // 判断设备关联的机构是配置微信支付
        Organization organization = deviceInfoService.getDeviceReceiveOrganization(deviceInfo);
        if (ObjectUtils.isEmpty(organization)) {
            return ResultContent.buildFail("设备未绑定收款机构，下单失败");
        }
        // 判断机构是否支持 该支付类型
        ResultContent resultContent = projectPaySettingService.judgeOrgSupport(deviceInfo.getProjectOid(), organization.getOid(), PaymentType.WeChatPay);
        if (resultContent.isFailed()) {
            return ResultContent.buildFail(resultContent.getMsg());
        }

        String mqttDataId = CommonUtil.UUID();
        ExpenseFlow expenseFlow = expenseFlowService.init(mqttDataId);
        if (ObjectUtils.isEmpty(expenseFlow)) {
            return ResultContent.buildFail("订单生成失败，请稍后再试");
        }
        String openId = getOpenId();
        String amount = param.getAmount().toPlainString();
        CreateOrderParam orderParam = new CreateOrderParam();
        orderParam.setDeviceId(deviceInfo.getDeviceId());
        if (userAccount != null) {
            orderParam.setUserId(userAccount.getUserId());
        }
        orderParam.setOrderNo(CommonUtil.UUID());
        orderParam.setAmount(amount);
        orderParam.setProductProvideId(param.getProductProvideId());
        // 扫码下单
        orderParam.setOrderFromType(OrderFromType.C2BQrCode);
        // 是否可以匿名消费
        orderParam.setIsAnonymous(Boolean.FALSE);
        // 是否是浮动计费 计费方式
        orderParam.setChargeableType(ChargeableType.Specified);

        // 指定支付方式 而且是微信渠道
        orderParam.setAppointPaymentType(Boolean.TRUE);
        orderParam.setPaymentType(PaymentType.WeChatPay);
        orderParam.setOpenId(openId);

        // 创建订单 （判断是否创建成功）
        ResultContent<ExpenseFlow> content = expenseFlowService.createOrder(orderParam, expenseFlow);
        expenseFlow = expenseFlowService.saveInfo(expenseFlow);
        if (!expenseFlow.getVerifyParamIsSuccess()) {
            return ResultContent.buildFail(expenseFlow.getVerifyParamMsg());
        }

        return expenseFlowService.getOrderPayDetail(expenseFlow.getId());
    }

}
