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

import com.github.microservice.net.ResultContent;
import com.github.microservice.pay.client.service.PayProductAccountService;
import com.github.microservice.pay.client.type.PayProductChannelType;
import com.github.microservice.types.payment.PaymentType;
import com.zhongshu.card.server.core.dao.org.OrganizationDao;
import com.zhongshu.card.server.core.dao.projectAbout.OrgPayAccountDao;
import com.zhongshu.card.server.core.domain.org.Organization;
import com.zhongshu.card.server.core.domain.paySetting.OrgPayAccount;
import com.zhongshu.card.server.core.service.base.SuperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 机构的支付类型账号管理
 *
 * @author TRX
 * @date 2024/10/9
 */
@Slf4j
@Service
public class OrgPayAccountService extends SuperService {

    @Autowired
    private OrgPayAccountDao orgPayAccountDao;

    @Autowired
    private PayProductAccountService payProductAccountService;

    @Autowired
    private OrganizationDao organizationDao;


    /**
     * 查询机构 支付账号
     *
     * @param oid         机构oid
     * @param paymentType 支付方式
     * @return
     */
    public String queryOgPayAccount(String oid, PaymentType paymentType) {
        return buildPayAccountName(oid, paymentType);
    }


    /**
     * 保存项目 微信支付账号
     *
     * @param projectOid
     * @param paymentType
     * @return
     */
    public ResultContent saveProjectAccount(String projectOid, PaymentType paymentType, PayProductChannelType productChannelType) {
        String payAccountId = buildPayAccountName(projectOid, paymentType);
        OrgPayAccount orgPayAccount = orgPayAccountDao.findTopByPayAccountId(payAccountId);
        if (ObjectUtils.isEmpty(orgPayAccount)) {
            orgPayAccount = new OrgPayAccount();
        }
        Organization organization = organizationDao.findTopByOid(projectOid);
        if (ObjectUtils.isNotEmpty(organization)) {
            orgPayAccount.setOrgName(organization.getName());
            orgPayAccount.setOid(organization.getOid());
        }
        orgPayAccount.setProjectOid(projectOid);
        orgPayAccount.setPayAccountId(payAccountId);
        orgPayAccount.setPaymentType(paymentType);
        orgPayAccount.setProductChannelType(productChannelType);
        orgPayAccount.setDisable(Boolean.FALSE);
        orgPayAccountDao.save(orgPayAccount);
        return ResultContent.buildSuccess();
    }

    /**
     * 得到项目的 微信小程序支付的账号
     *
     * @param projectOid
     * @return
     */
    public String getProjectWxAccount(String projectOid) {
        return buildPayAccountName(projectOid, PaymentType.WeChat);
    }

    public String buildPayAccountName(String projectOid, PaymentType paymentType) {
        return String.format("%s%s", projectOid, paymentType.name());
    }

}
