<?php

namespace app\command;

use app\extra\jhfPay\Pay;
use app\model\saas\SaasOrder;
use app\model\saas\SaasShop;
use app\model\saas\SaasUserBuy;
use app\model\system\SystemUserMoney;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class DayMoney extends Command
{

    protected static string $defaultName = 'day:money';
    protected static string $defaultDescription = '每日结算金额统计';


    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $nextPage = 1;$done = 0;
        $mode = (new SaasShop);
        $orderMode = (new SaasOrder);
        $moneyMode = (new SystemUserMoney);
        $cardMode = (new SaasUserBuy);
        $day = date("Y-m-d",strtotime("-1 day"));
//        $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"),
//        ]);
        while (is_numeric($nextPage)) {
            $total = $mode->count();
            $result = $mode->limit(($nextPage-1)*10,10)->with(['card'])->select();
            if ($result->isEmpty()) {
                $output->writeln('没有更多数据啦~==>'.getDateFull());
                $nextPage = null;
                return self::SUCCESS;
            }
            if ($done >= $total){
                $output->writeln('没有更多数据啦!~==>'.getDateFull());
                $nextPage = null;
                return self::SUCCESS;
            }
            $moneyData = [];
            foreach ($result as $key => $val)
            {
                ++$done;
                if (empty($val['cash_rate'])) {
                    $rate = 0.006;
                } else {
                    $rate = $val['cash_rate'] / 100;
                }
                $dayData = $moneyMode->where("agent_id",$val['shop_id'])->where("day",$day)->findOrEmpty();
                if ($dayData->isEmpty()) {
                    $dayMoney = $orderMode->where("shop_id",$val['shop_id'])->whereIn("status",[1,2,3])->whereDay("create_at","yesterday")->where("pay_type",1)->sum("money");
                    $cardMoney = $cardMode->where("shop_id",$val['shop_id'])->where("status",1)->whereDay("create_at","yesterday")->sum("money");
                    $status = 0;
                    $memberId = $val['card']['member_id']??'';
                    if ($dayMoney == 0) {
                        $status = 1;
                    }
                    $totalMoney = $dayMoney + $cardMoney;
                    $rateMoney = ($totalMoney==0)?0:round($totalMoney*$rate);
                    $endMoney = round($totalMoney - $rateMoney,0);
                    $moneyData[$key] = [
                        "order_sn"      => strtoupper(md5($day.$val['shop_id'])),
                        "agent_id"      => $val['shop_id'],
                        "money"         => $endMoney,
                        "re_money"      => $totalMoney, // 当日金额
                        "order_money"   => $dayMoney,
                        "user_money"    => $cardMoney, // 会员卡充值金额
                        "rate"          => $rateMoney,
                        "day"           => $day,
                        "status"        => $status,
                        "member_id"     => $memberId
                    ];
//                    if (!empty($memberId) && $totalMoney > 0) { // 发起余额分账
//                        $shopName = $val['shop_name']??'';
//                        $respJhf->createBalancePay([
//                            "app_id" => sConf("wechat.jhf_appid"),
//                            "order_no"  => strtoupper(md5($day.$val['shop_id'])),
//                            "member_id" => $memberId,
//                            "pay_amt"   => format_money($endMoney/100,2),
//                            "description"   => "{$day}-{$shopName}-结算"
//                        ]);
//                    }
                    echo getDateFull()."==={$val['shop_id']}=={$val['shop_name']}==当天营业额统计===￥{$totalMoney}====结算卡：{$memberId}==状态：{$status}===\n";
                } else {
                    echo getDateFull()."==={$val['shop_id']}=={$val['shop_name']}=={$day}==已完成统计===\n";
                }
            }
            if (!empty($moneyData)) {
                $moneyMode->insertAll(array_values($moneyData));
            }
            $nextPage = $nextPage+1;
            $output->writeln("当前页码{$nextPage}==>".getDateFull());
        }
        return self::SUCCESS;
    }

}