<?php

namespace App\Admin\Forms;

use App\Command\Log;
use App\Models\OrderInfo;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Traits\LazyWidget;
use App\Handlers\MpAaccessToken;
use App\Models\PaymentRecord;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use DateTime;
use DateTimeZone;
use Exception;

//发货
class ShippingForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        $mpTokenObj = new MpAaccessToken();
        $dateTime = new DateTime();
        $dateTime->setTimezone(new DateTimeZone('Asia/Shanghai'));
        $upload_time = $dateTime->format('Y-m-d\TH:i:s.vP');

        $shipping_type = intval($input['shipping_type']);
        $shipping_name = trim($input['shipping_name']);
        $shipping_code = trim($input['shipping_code']);
        $shipping_goods = trim($input['shipping_goods']);

        $order_id = $this->payload['id'];
        $order = OrderInfo::find($order_id);

        $order->shipping_type = $shipping_type;
        $order->shipping_code = $shipping_code;
        $order->shipping_name = $shipping_name;
        $order->shipping_goods = $shipping_goods;
        $order->shipping_at = date("Y-m-d H:i:s");
        try {
            //接入微信小程序发货管理
            if (1) {
                //付款记录
                $recordObj = PaymentRecord::where('order_sn', $order->order_sn)->first();
                $transaction_id = $recordObj->other_order;
                $payerOpenid = User::where('id', $recordObj->uid)->value('openid');

                $access_token = $mpTokenObj->getAccessToken();
                $url = "https://api.weixin.qq.com/wxa/sec/order/upload_shipping_info?access_token=" . $access_token;
                $data = [
                    "order_key" => [
                        "order_number_type" => 2,
                        "transaction_id" => $transaction_id,
                    ],
                    "logistics_type" => 4,
                    "delivery_mode" => 1,
                    "shipping_list" => [
                        ["item_desc" => $order->shipping_goods]
                    ],
                    "upload_time" => $upload_time,
                    "payer" => [
                        "openid" => $payerOpenid,
                    ]
                ];
                $headers = array("Content-type: application/json;charset=UTF-8");

                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, $url);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
                // 设置HTTP头部
                curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data, JSON_UNESCAPED_UNICODE));
                $response = curl_exec($curl);

                $result = json_decode($response, true);
                // 关闭cURL会话
                curl_close($curl);
                Log::add('发货录入', $result);
                if ($result['errcode'] != 0) {
                    throw new Exception($result['errmsg']);
                }
            }
            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->radio('shipping_type', '发货方式')
            ->when([1, 2], function (Form $form) {
                $form->text('shipping_name', '快递公司');
                $form->text('shipping_code', '快递单号');
            })
            ->options([
                1 => '物流快递',
                2 => '同城配送',
                3 => '用户自提',
                4 => '虚拟发货',
            ])
            ->default(1);
        $this->text('shipping_goods', '商品信息')->required();
    }

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