<?php

namespace App\Console\Commands;

use App\Modules\Welfare\Services\WelfareOrderService;
use App\Modules\Welfare\Services\WelfareRecordService;
use Illuminate\Console\Command;
use EasyWeChat\Foundation\Application;

class WelfarePrize extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'welfare:prize {--day=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '发红包';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->start();

    }

    //开始
    private function start(){
        $prices = $this->getAllPrizes();
        for ($i = 0;$i <2 ;$i++){
            if($prices[$i]){
                // 'welfare_records.id,welfare_records.amount,welfare_users.openid';
                foreach ($prices[$i] as $v){
                    $this->prize($v->id,$v->openid,$v->amount);
                }
            }
        }
    }

    //获取要发红包的列表
    private function getAllPrizes(){
        $day = $this->option('day');
        if($day){
            $now =  WelfareRecordService::getNow(true,1,$day);
            return [[],$now];
        }
        $zero = strtotime(date('Y-m-d 00:00:00'));
        $yesterday = [];
        if(time() - $zero <=60){
            $yesterday = WelfareRecordService::getNow(true,100);
        }
        $now =  WelfareRecordService::getNow();

        return [$yesterday,$now];
    }

    //发红包并记录
    private function prize($price_id,$openid,$amount){
        $params = [
            'mch_appid'=>'wxe559e68b007476f6',
            'mchid' =>'1493525602',
            'nonce_str'=>'',
            'openid'=>$openid,
            'check_name'=>'NO_CHECK',
            'amount'=>$amount*100,
            'desc'=>'福利',
            'spbill_create_ip'=>'47.97.120.133',
            'partner_trade_no'=>date("YmdHis").hexdec(uniqid()),
            'sign'=>''
        ];
        $create_info = WelfareOrderService::create($params);
        $options = [
            'app_id'=>'wxe559e68b007476f6',
            'payment'=>[
                'merchant_id'=>'1493525602',
                'key'=>'ee245088b93ba88008279d95f6d31223',
                'cert_path'=>public_path('wxpay/ydylm/apiclient_cert.pem'),
                'key_path'=>public_path('wxpay/ydylm/apiclient_key.pem')
            ]
        ];
        $app = new Application($options);
        $merchantPay = $app->merchant_pay;
        $result = $merchantPay->send([
            'partner_trade_no' => $params['partner_trade_no'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $openid,
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            'amount' => $amount*100, // 企业付款金额，单位为分
            'desc' => '福利', // 企业付款操作说明信息。必填
            'spbill_create_ip'=>'47.97.120.133'
        ]);
        $status = 'FAIL';
        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
            $status = 'SUCCESS';
        }
        WelfareOrderService::updateResult($create_info->id,['result'=>json_encode($result)]);
        WelfareRecordService::update($price_id,['status'=>$status]);
    }

}
