<?php

namespace app\common\logic;

use think\facade\Db;
use think\facade\Log;

class Ticket
{

    protected $domain = "https://ilike-cloud-mapi.zmaxfilm.com";

    public function order_film_pay($order_info)
    {
        $url = $this->domain . '/pay/pay/orderFilmPay';
        $order_info = empty($order_info['data']) ? $order_info : $order_info['data'];
        
        $data                    = [];
        $data['account']         = 'bbfuli1117';
        $data['payType']         = 'bbflpay';
        $data['amount']          = $order_info['order_amount'];
        $data['outTradeNo']      = $order_info['order_sn'];
        $data['merchantOrderNo'] = $order_info['third_pay_order_id'];
        $data['sign']            = $this->makesign($data);
        $result                  = $this->curl($url, $data);
        Log::info('电影订单支付成功接口返回消息：' . $result);
        $result                  = json_decode($result, true);

        // var_dump($result);exit();
        if ($result['status'] != 0) {
            return false;
        }
        return true;
    }

    /**
     * 支付订单
     * @param array $order_info
     * @param string $role 操作角色 buyer、seller、admin、system 分别代表买家、商家、管理员、系统
     * @param string $post
     * @return array
     */
    public function changeOrderStatePay($order_info, $role, $post)
    {
        try {
            $TicketOrder = model('TicketOrder');
            Db::startTrans();
            $predeposit_model = model('predeposit');
            //下单，支付被冻结的充值卡
            $rcb_amount = floatval($order_info['rcb_amount']);
            if ($rcb_amount > 0) {
                $data_pd                = [];
                $data_pd['member_id']   = $order_info['buyer_id'];
                $data_pd['member_name'] = $order_info['buyer_name'];
                $data_pd['amount']      = $rcb_amount;
                $data_pd['order_sn']    = $order_info['order_sn'];
                $predeposit_model->changeRcb('order_comb_pay', $data_pd);
            }
            //下单，支付被冻结的预存款
            $pd_amount = floatval($order_info['pd_amount']);
            if ($pd_amount > 0) {
                $data_pd                = [];
                $data_pd['member_id']   = $order_info['buyer_id'];
                $data_pd['member_name'] = $order_info['buyer_name'];
                $data_pd['amount']      = $pd_amount;
                $data_pd['order_sn']    = $order_info['order_sn'];
                $predeposit_model->changePd('order_comb_pay', $data_pd);
            }

            //更新订单状态
            $update_order                 = [];
            $update_order['order_state']  = ORDER_STATE_PAY;
            $update_order['payment_time'] = isset($post['payment_time']) ? strtotime($post['payment_time']) : TIMESTAMP;
            $update_order['payment_code'] = $post['payment_code'];
            $update_order['trade_no']     = $post['trade_no'];
            $update                       = $TicketOrder->edit($update_order, ['order_id' => $order_info['order_id']]);
            if (!$update) {
                throw new \think\Exception(lang('ds_common_save_fail'), 10006);
            }

            Db::commit();
            return ds_callback(true, '更新成功');
        } catch (Exception $e) {
            Db::rollback();
            return ds_callback(false, $e->getMessage());
        }
    }

    /**
     * 取消订单
     */
    public function changeOrderStateCancel($order_info)
    {
        $expense = Db::name('sub_card_expense')->where('is_vir', 2)->where('order_id', $order_info['id'])->find();
        if (!empty($expense)) {
            //1.回滚卡片余额
            $cardInfo = Db::name('sub_card')->where('id', $expense['card_id'])->find();

            if (($cardInfo['balance'] + $order_info['deduction_amount']) == $cardInfo['worth']) {
                $cardStatus = 1;
            } else {
                $cardStatus = 2;
            }
            $cardUpdate = [
                'card_status' => $cardStatus,
                'balance'     => $cardInfo['balance'] + $order_info['deduction_amount'],
                'freeze'      => $cardInfo['freeze'] - $order_info['deduction_amount'],
                'update_time' => time(),
                'used_count'  => $cardInfo['used_count'] - 1,
            ];
            $cardRes    = Db::name('sub_card')->where('id', $expense['card_id'])->update($cardUpdate);

            if ($cardRes) {
                //如果卡的数据恢复成功了   删除卡的消费记录
                Db::name('sub_card_expense')->where('id', $expense['id'])->update(['expense_status' => 2]);
            }
        }

        //更改订单状态
        $TicketOrder = model('TicketOrder');
        $TicketOrder->where('id', $order_info['id'])->update(['order_state' => 0]);
        Log::info('电影票订单取消，id：' . $order_info['id'] . '，时间：' . date('Y-m-d H:i:s'));
    }

    private function makesign($data)
    {
        ksort($data);
        $string = $this->tourlparams($data);
        $string = $string . 'OiwYehcnkeflRjVN';
        $string = md5(sha1($string));
        return substr($string, 8, 16);
    }

    private function tourlparams($data)
    {
        $buff = "";
        foreach ($data as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . $v;
            }
        }
        return $buff;
    }

    private function curl($url, $data = '', $headers = [], $timeout = 60, $issplit = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        @curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        @curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

        if ($data) {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);

        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1");
        if (!empty($headers) && is_array($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        ob_start();
        $res        = curl_exec($ch);
        $headersize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $header     = substr($res, 0, $headersize);
        $body       = substr($res, $headersize);
        ob_end_clean();
        curl_close($ch);
        unset($ch);

        if ($issplit) {
            return ['header' => $header, 'body' => $body];
        }
        return $res;
    }
}