<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Wechat_order extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('device');
        $this->config->load("wechat", true);
        $this->load->library('Wechat_lib');
        $this->load->library('Paycenter_lib');
        $this->load->model('Order_model');
        $this->load->model('Wechat_service_model');

        header('Access-Control-Allow-Origin:*');
        // header('Access-Control-Allow-Origin:*');
        // header('Access-Control-Allow-Methods:POST, GET');
        // header('Access-Control-Max-Age:0');
        // header('Access-Control-Allow-Headers:x-requested-with, Content-Type');
        // header('Access-Control-Allow-Credentials:true');
    }

    public function index()
    { }

    /**
     * 生成带参数的公众号二维码
     * @param str 订单主表key
     * @param str 公众号的名字, 默认是Trippest.
     * @return str 二维码图片地址
     */
    public function order_qrcode($coli_sn, $wechat_host='trippest', $output=true)
    {
        $this->wechat_config = $this->config->item($wechat_host, 'wechat');
        $this->wechat_host = $wechat_host;

        $url = "/cgi-bin/qrcode/create";
        $qrcode_request_info = array(
            "action_name" => "QR_STR_SCENE",
            "expire_seconds" => 604800,
            "action_info" => array("scene" => array("scene_str" => strval($coli_sn)))
        );
        $qrcode_response_info = json_decode($this->wechat_lib->call_wechat($wechat_host, $url, [], json_encode($qrcode_request_info, JSON_UNESCAPED_UNICODE)), true);
        $qrcode_src_url = $this->config->item('qrcode_src_prefix', 'wechat') . urlencode($qrcode_response_info['ticket']);
        if ($output !== true) {
            return $qrcode_src_url;
        }
        return $this->output->set_output($qrcode_src_url);
    }

    public function save()
    {
        $input = $this->input->post() ? $this->input->post() : $this->input->get();
        // detect date if valid date
        $input['start_date'] = true===validate_date($input['start_date']) ? $input['start_date'] : null;
        $passenger = json_decode($input['passenger'], true);
        $order_insert = array();    // BIZ_ConfirmLineInfo
        $guest  = array();    // BIZ_guest
        $BPE_SN = array();
        $book_detail = array(); // BIZ_ConfirmLineDetail
        $pag_order = array(); // BIZ_PackageOrderInfo
        $ht_pag_info = $this->Order_model->get_pag_tour_info($input['tour_external_id']);
        /** BIZ_guest */
        $guest['GUT_FirstName'] = $input['fullname'];
        $guest['GUT_Email'] = $input['email'];
        $guest['GUT_NationalityID'] = $input['country_id'];
        $guest['GUT_Passport'] = $passenger[0]['idNumber'];
        $guest['GUT_TEL'] = $guest['GUT_MoveTel'] = $input['mobile'];
        $guest['GUT_POST'] = $input['country_code'];
        $order_insert['COLI_GUT_SN'] = $this->Order_model->guest_save($guest);
        /** BIZ_BookPeople */
        foreach ($passenger as $kp => $passg) {
            if ($passg['fullname'] === '' && $passg['idNumber'] === '') {
                continue;
            }
            $book_people = array();
            $book_people['BPE_FirstName'] = $passg['fullname'];
            $book_people['BPE_GuestType'] = $passg['ageType'];
            $book_people['BPE_Passport'] = $passg['idNumber'];
            $book_people['BPE_PassportType'] = $passg['idType'];
            $BPE_SN[] = $this->Order_model->book_people_save($book_people);
        }
        /** BIZ_ConfirmLineInfo */
        $travelers = json_decode($input['travelers'], true);
        $adult = $travelers['ADULT'] ? $travelers['ADULT'] : array_values($travelers[0]);
        $child = isset($travelers['CHILD']) ? $travelers['CHILD'] : 0;
        $baby = isset($travelers['INFANT']) ? $travelers['INFANT'] : 0;
        $order_insert['COLI_State'] = 1;
        $orderid_obj = $this->Order_model->biz_make_order_number();
        $order_insert['COLI_ID'] = $orderid_obj->coli_id;
        $order_insert['COLI_ApplyDate'] = date('Y-m-d H:i:s');
        $order_insert['COLI_ConfirmType'] = '52002'; // 邮件
        $order_insert['COLI_servicetype'] = 'D';
        $order_insert['COLI_Currency'] = 'USD';
        $order_insert['COLI_Department'] = $ht_pag_info['PAG_DEI_SN'];
        $order_insert['COLI_SenderIP'] = $this->input->ip_address();
        $order_insert['COLI_OrderDetailText'] = $this->parse_detail($input);
        $order_insert['COLI_Price'] = $input['total_price'];
        // $order_insert['COLI_Cost']
        $order_insert['COLI_WebCode'] = $input['web_code'];
        $order_insert['COLI_OriginalText'] = json_encode($input);
        $order_insert['COLI_sourcetype'] = $ht_pag_info['sourcetype32'];
        $order_insert['COLI_OrderSource'] = $this->device_code();
        $coli_sn = $this->Order_model->order_save($order_insert);
        $input['coli_sn'] = $coli_sn;
        /** BIZ_ConfirmLineDetail */
        $book_detail['COLD_COLI_SN'] = $coli_sn;
        $book_detail['COLD_PlanVEI_SN'] = $ht_pag_info['PAG_DefaultVEI_SN'];
        $book_detail['COLD_StartDate'] = date('Y-m-d', strtotime($input['start_date']));
        // $book_detail['COLD_EndDate']
        $book_detail['COLD_ServiceCity'] = $ht_pag_info['PAG_CII_SN'];
        $book_detail['COLD_ServiceType'] = 'D';
        $book_detail['COLD_ServiceSN'] = $ht_pag_info['PAG_SN'];
        // $book_detail['COLD_ServiceSN2']
        // $book_detail['COLD_TotalCost']
        $book_detail['COLD_TotalPrice'] = $order_insert['COLI_Price'];
        $book_detail['COLD_Count'] = 1;
        $book_detail['COLD_PersonNum'] = $adult;
        $book_detail['COLD_ChildNum'] = $child;
        $book_detail['COLD_BabyNum'] = $baby;
        $book_detail['COLD_State'] = 1;
        // $book_detail['COLD_Memo']
        // $book_detail['COLD_MemoText']
        $cold_sn = $this->Order_model->book_detail_save($book_detail);
        //订单客人列表
        foreach ($BPE_SN as $bpe_item) {
            $new_arr = array();
            $new_arr = array("BPL_COLD_SN" => $cold_sn, "BPL_BPE_SN" => $bpe_item);
            $this->Order_model->biz_bookpeople_List_save($new_arr);
        }
        /** BIZ_PackageOrderInfo */
        $pickup = json_decode($input['pickup'], true);
        $pag_order['POI_COLD_SN'] = $cold_sn;
        // $pag_order['POI_FlightsNo']
        // $pag_order['POI_AirPort']
        // $pag_order['POI_Time']
        $pag_order['POI_Hotel'] = $pickup['hotelName'];
        $pag_order['POI_HotelAddress'] = $pickup['hotelAddress'] ? $pickup['hotelAddress'] : $pickup['pickupAddress'];
        // $pag_order['POI_HotelPhone']
        $pag_order['POI_HotelCheckInName'] = $pickup['checkInName'];
        // $pag_order['POI_HotelCheckIn']
        // $pag_order['POI_HotelCheckOut']
        // $pag_order['POI_EndTime']
        // $pag_order['POI_SelectOption']
        $this->Order_model->pag_order_save($pag_order);
        $input['coli_id'] = $order_insert['COLI_ID'];
        $input['payment_now'] = 'true';
        $input['paid'] = 'false';
        $input['show_wxpay'] = $this->wechat_ua()===TRUE ? 'true' : 'false';
        $input['order_qrcode'] = $this->order_qrcode($coli_sn, 'trippest', false);

        $pay_param = array(
            "order_id" => $order_insert['COLI_ID'] . "_B",
            "lg" => "en_US",
            "currency" => "USD",
            "subject" => "Trippest-" . $order_insert['COLI_ID'],
            "body" => "Trippest-" . $order_insert['COLI_ID'],
            "total_amount" => $order_insert['COLI_Price'],
            // "rmb_amount" => $order_insert['COLI_Price'],
            "wx_account" => "trippest",
            "return_url" => "https://www.trippest.com",
        );
        $input['payment_link'] = $this->paycenter_lib->create($pay_param);
        $this->output->set_content_type('application/json')->set_output(json_encode($input));
        // WeChat user
        if (strval($input['userid']) !== '0') {
            $customer_column = array(
                "wc_wu_id" => $input['userid']
                ,"wc_coli_sn" => $coli_sn
                ,"wc_htordertype" => 27002
            );
            $wc_id = $this->Wechat_service_model->insert_wechat_customer($customer_column);
            $input['wechat'] = array("wc_id" => $wc_id, "wu_id" => $input['userid']);
            $this->push_order_book($input);
        }
        return false;
    }

    /*!
     * @param array $order
     */
    private function push_order_book($input)
    {
        $pay_detail = $this->Order_model->order_info_to_pay($input['coli_sn']);
        $order = $this->Order_model->order_detail($input['coli_sn']);
        $order['wechat'] = $input['wechat'];
        $this->wechat_lib->push_book_ok('trippest', $pay_detail['openid'], $order);
        return false;
    }

    /**
     * 前端支付成功后, 查询支付结果
     * * 确认成功: 推送
     * * 失败: 无操作
     */
    public function paid()
    {
        $input = $this->input->post() ? $this->input->post() : $this->input->get();
        $coli_id = strstr($input['outTradeNo'], '_', true);
        $payment = $this->wxpay_query($input['outTradeNo']);
        if (empty($payment)) {
            return $this->output->set_content_type('application/json')->set_output('{}');
        }
        $order = $this->Order_model->order_detail(0, $coli_id);
        $wechat_order = $this->Wechat_service_model->get_customer($order['orderTour'][0]['coli']);
        $order['wechat'] = array("wc_id" => $wechat_order['wc_id'], "wu_id" => $wechat_order['wc_wu_id']);
        $this->wechat_lib->push_wechat_paid('trippest', $payment, $order);
        $payment['paidQuote'] = $order['paidQuote'];
        return $this->output->set_content_type('application/json')->set_output(json_encode($payment));
    }

    private function device_code()
    {
        $code = '62001';
        switch (check_device()) {
            case 'mobile':
                $code = '62003';
                break;
            case 'tablet':
                $code = '62002';
                break;
            default:
                $code = '62001';
        }
        return $code;
    }

    private function parse_detail($input)
    {
        $orderdetail_text = '';
        foreach ($input as $key => $value) {
            switch ($key) {
                case 'pickup':
                    $pickup_obj = json_decode($value, true);
                    $orderdetail_text .= "pickup option: " . $pickup_obj['value'] . PHP_EOL;
                    // $orderdetail_text .= "pickup option text: " . $pickup_obj['label'] . PHP_EOL;
                    $orderdetail_text .= "pickup address: " . $pickup_obj['pickupAddress'] . PHP_EOL;
                    break;

                case 'passenger':
                case 'web_code':
                case 'country':
                case 'country_id':
                case 'country_code':
                case 'travelers':
                case 'adult_num':
                case 'child_num':
                case 'fullname':
                case 'email':
                case 'mobile':
                case 'total_price':
                    break;

                default:
                    $orderdetail_text .= str_replace("_", " ", $key) . ": " . $value . PHP_EOL;
                    break;
            }
        }
        return $orderdetail_text;
    }

    /*!
     * @Author: LYT: lyt@hainatravel.com
     * @Date: 2019-11-13 16:48:27
     * @Desc: 我的所有订单
     */
    public function itinerary()
    {
        $ret = array("itineraryList" => array());
        $wu_id = $this->input->get_post('userid');
        if (!is_numeric($wu_id)) {
            return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
        }
        // $ret['userinfo'] = $this->Wechat_service_model->get_user($wu_id);
        $ret['itineraryList'] = $this->Order_model->orders($wu_id);
        array_walk($ret['itineraryList'], function (&$ele){$ele['startDate'] = date('M d, Y', strtotime($ele['startDate']));});
        return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
    }

    /*!
     * @Author: LYT: lyt@hainatravel.com
     * @Date: 2019-11-13 16:49:02
     * @Desc: 订单预订详情
     */
    public function detail($coli_sn=null)
    {
        $coli_sn = $coli_sn!==null ? $coli_sn : $this->input->get_post('coli');
        $ret = $this->Order_model->order_detail($coli_sn);
        return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
    }

    /*!
     * @Author: LYT: lyt@hainatravel.com
     * @Date: 2019-11-13 16:49:11
     * @Desc: 请求微信支付JSAPI所需的参数签名, 再次签名后返回前端发起支付
     */
    public function wxpay_sign($wechat_host='trippest')
    {
        $GLOBALS['__WX_SITE_NAME__'] = $wechat_host;
        bcscale(0);
        $this->config->load('wechat', true);
        $input = $this->input->post() ? $this->input->post() : $this->input->get();
        if (false === $this->wechat_ua()) {
            return $this->output->set_content_type('application/json')->set_output(json_encode(array()));
        }
        $pay_detail = $this->Order_model->order_info_to_pay($input['order_id']);
        $this->load->library('wxpay/NativePay');
        $wxfun = new WxPayUnifiedOrder();
        $wxfun->SetBody("Trippest-" . $pay_detail['COLI_ID']);
        $out_trade_no = $pay_detail['COLI_ID'] . "_B". rand(1000,9999);
        $wxfun->SetOut_trade_no($out_trade_no);
        // $wxfun->SetAttach(bcmul($pay_detail['cny_price'], $this->config->item('currency_unit', 'wechat'))); // test:
        $wxfun->SetTotal_fee(bcmul($pay_detail['cny_price'], $this->config->item('currency_unit', 'wechat')));
        // $wxfun->SetTotal_fee(1); // test:
        $wxfun->SetTime_start(date("YmdHis"));
        $wxfun->SetTime_expire(date("YmdHis", time() + 600));
        // $wxfun->SetGoods_tag("test");
        $wxfun->SetTrade_type("JSAPI");
        $wxfun->SetOpenid($pay_detail['openid']);
        // $wxfun->SetOpenid('oe2BW1C9G-gmtDyOqwIvOMg8L_FA'); // test:
        $config = new WxPayConfig();
        $order = WxPayApi::unifiedOrder($config, $wxfun);
        // 生成预支付成功返回: $order
        /*
        {
            "appid": "wx7e605820faf98a05",
            "mch_id": "1528541381",
            "nonce_str": "kD7nlZ1rsSvFzvM3",
            "prepay_id": "wx08163228081581bac9a0e0ad1787454800",
            "result_code": "SUCCESS",
            "return_code": "SUCCESS",
            "return_msg": "OK",
            "sign": "11118EA80C2069F654B83991F682BD92423EFABA6064A82FF4A2763474B0FE3F",
            "trade_type": "JSAPI"
        }
        */
        // 再次签名生成H5支付的参数
        /*
        $ret = array(
            "appId" => "wx7e605820faf98a05",
            "timeStamp" => time(),
            "nonceStr" => $str,
            "package" => "prepay_id=u802345jgfjsdfgsdg888",
            "signType" => "MD5",
            "paySign" => "C380BEC2BFD727A4B6845133519F3AD6"
        );
        */
        $tools = new JsApiPay();
        $jsApiParameters = $tools->GetJsApiParameters($order);
        $ret = array('param' => json_decode($jsApiParameters, true), 'order_no' => $out_trade_no);
        return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
    }

    private function wxpay_query($out_trade_no)
    {
        $GLOBALS['__WX_SITE_NAME__'] = 'trippest';
        $this->load->library('wxpay/NativePay');
        $input = new WxPayOrderQuery();
        // $input->SetTransaction_id($transaction_id);
        $input->SetOut_trade_no($out_trade_no);
        $config = new WxPayConfig();
        $ret = (WxPayApi::orderQuery($config, $input));
        $ret = $ret['result_code']==='SUCCESS' ? $ret : array();
        return $ret;
    }

    private function wechat_ua()
    {
        $ua = '';
        if (isset($_SERVER['HTTP_USER_AGENT'])) {
            $ua = $_SERVER['HTTP_USER_AGENT'];
        }
        if (false === strstr(strtolower($ua), 'micromessenger')) {
            return FALSE;
        }
        return TRUE;
    }

}

/* End of file Wechat_order.php */
