<?php

namespace app\command;

use app\extra\jhfPay\Pay;
use app\extra\tools\CodeExtend;
use app\model\system\SystemUserMoney;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class DayTotal extends Command
{

    protected static string $defaultName = 'day:total';
    protected static string $defaultDescription = '每日结算金额余额分账';


    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $day = date("Y-m-d",strtotime("-1 day"));
        $totalMoney = (new SystemUserMoney)->where("day",$day)->select();
        $moneyData = [];
        if ($totalMoney->isEmpty()) return self::SUCCESS;
        $respJhf = (new Pay)->config([
            "appid"  => sConf("wechat.jhf_appid"),
            "mch_id" => sConf("wechat.jhf_mch_id"),
            "aeskey" => sConf("wechat.jhf_aeskey"),
            "pubkey" => sConf("wechat.jhf_pubkey"),
            "prikey" => sConf("wechat.jhf_prikey"),
        ]);
        foreach ($totalMoney as $key=>$value) {
            if (!empty($value['member_id'])) {
//                echo "{$value['member_id']}==={$value['money']}\n";
                if (isset($moneyData[$value['member_id']])) {
                    $moneyData[$value['member_id']] += $value['money'];
                } else {
                    $moneyData[$value['member_id']] = $value['money'];
                }
            }
        }
        if (!empty($moneyData)) {
            foreach ($moneyData as  $memberId=>$val){
                $resp = $respJhf->createBalancePay([
                    "app_id" => sConf("wechat.jhf_appid"),
                    "order_no"  => CodeExtend::uniqidDate(18),
                    "member_id" => $memberId,
                    "pay_amt"   => format_money($val/100,2),
                    "description"   => "{$day}-结算"
                ]);
                echo getDateFull()."===余额分账===\n";
                echo json_encode($resp)."\n";
                sleep(1);
            }
        }
        return self::SUCCESS;
    }

}