<?php

namespace App\Admin\Forms;

use App\Models\OrderDivideRecord;
use App\Command\Log;
use App\Models\OrderInfo;
use App\Models\Adapay;
use App\Models\User;
use App\Models\PaymentRecord;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use App\Models\HfPayconfirm;
use Exception;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class TransferBillsPlatForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $payment_confirm = new \NwVVVS\AdapaySdk\PaymentConfirm(); //支付确认
        $id = $this->payload['id'];
        DB::beginTransaction();
        try {
            $remark = trim($input['remark']);
            $recordObj = OrderDivideRecord::find($id);
            if (!$recordObj && $recordObj->is_div == 1) {
                throw new Exception('数据不存在或该用户已分账!');
            }

            $divide_price = $recordObj->divide_price; //分账佣金
            $um_id = $recordObj->um_id; //推荐分享人
            $userObj = User::find($um_id);
            Log::add('推荐人信息', $userObj->toArray());

            //交易记录
            $order_no = OrderInfo::where('id', $recordObj->order_id)->value('order_sn');
            $prObj = PaymentRecord::where('order_sn', $order_no)->first();
            # 支付确认参数设置
            $payment_params = array(
                "payment_id" => $prObj->payment_id,
                "order_no" => 'payconfirm_' . date("YmdHis") . rand(100000, 999999),
                "confirm_amt" => $divide_price,
                "description" => "",
                "div_members" => "" //分账参数列表 默认是数组List
            );

            $userObj->total_revenue -= $divide_price;
            $userObj->save();

            Log::add('推荐人账户更新信息', $userObj->toArray());
            # 发起支付确认创建
            $payment_params['div_members'] = ['member_id' => 0, 'amount' => sprintf("%.2f", $divide_price), 'fee_flag' => 'Y'];

            $result = (new Adapay())->createPaymentConfirm($payment_params);
            # 对支付确认创建结果进行处理
            if ($result['status'] == 'succeeded') {
                //成功处理
                Log::add('分账给平台成功', ['recond_id' => $recordObj->id,'um_id' => $recordObj->um_id,'sh_type' => $recordObj->sh_type]);
                $recordObj->remark = $remark;
                $recordObj->payconfirm_no = $result['order_no'];
                $recordObj->is_div = 1;
                $recordObj->um_id = 0;
                $recordObj->sh_type = 0;
                $recordObj->save();
                //写入支付确认信息
                (new HfPayconfirm())->add($payment_params, $result['fee_amt']);
            }

            DB::commit();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error($exception->getMessage())->refresh();
        }
        return $this->response()->success('提交成功')->refresh();
    }


    /**
     * Build a form here.
     */
    public function form()
    {
        $this->text('remark', '备注')->required();
    }

    /**
     * The data of the form.
     *
     * @return array
     */
    public function default()
    {
        // 获取外部传递参数
        return [];
    }
}