<?php

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

class Wechat_mp extends CI_Controller
{
    // 服务号主体 'trippest'
    private $wechat_host;
    // 服务号的配置信息
    private $wechat_config;
    // 服务号账户
    private $wechat_operator;

    public function __construct()
    {
        parent::__construct();
        $this->load->helper('url_helper');
        $this->load->helper('device_helper');

        $this->config->load("wechat", true);
        $this->load->library('Wechat_lib');
        $this->load->library('Bokun_lib');
        $this->load->model('Order_model');
        $this->load->model('Wechat_service_model');
        header('Access-Control-Allow-Origin:*');
    }

    public function notice($wechat_host)
    {
        error_reporting(0);
        $this->wechat_config = $this->config->item($wechat_host, 'wechat');
        $this->wechat_host = $wechat_host;

        $get_input = $this->input->get();
        $raw_post_data = file_get_contents('php://input');
        // empty POST data
        if (empty($raw_post_data)) {
            return $this->wechat_lib->auth_signature($get_input, $this->wechat_config['token']);
        }
        $raw_arr = $this->wechat_lib->from_xml($raw_post_data);
        $this->wechat_operator = $raw_arr['ToUserName'];
        $user_info = $this->Wechat_service_model->get_user(null, $this->wechat_config['app_id'], $raw_arr['FromUserName']);
        $insert_db = array(
            "wn_hostappid"    => $this->wechat_config['app_id'], "wn_useropenid"  => $raw_arr['FromUserName'], "wn_wu_id"       => $user_info['wu_id'], "wn_msgtype"     => $raw_arr['MsgType'], "wn_eventtype"   => isset($raw_arr['Event']) ? $raw_arr['Event'] : null, "wn_msgid"       => isset($raw_arr['MsgId']) ? $raw_arr['MsgId'] : null, "wn_eventkey"    => isset($raw_arr['EventKey']) ? (is_array($raw_arr['EventKey']) ? json_encode($raw_arr['EventKey']) : $raw_arr['EventKey'])  : null, "wn_createtime"  => date("Y-m-d H:i:s", $raw_arr['CreateTime']), "wn_rawcontent"  => json_encode($raw_arr, JSON_UNESCAPED_UNICODE)
        );
        $this->Wechat_service_model->insert_wechat_notify($insert_db);
        // Handle MsgType
        switch (strtolower($raw_arr['MsgType'])) {
            case 'text':
                $this->text_handle($raw_arr);
                break;
            case 'event':
                $this->event_handles($raw_arr);
                break;

            default:
                break;
        }
        // 确保返回空字符串
        return $this->wechat_lib->response_text(null, $raw_arr['FromUserName'], $this->wechat_operator);
    }

    /**
     * 生成带参数的公众号二维码
     * @deprecated Move to Wechat_order.php
     * @param str 订单主表key
     * @param str 公众号的名字, 默认是Trippest.
     * @return str 二维码图片地址
     */
    public function order_qrcode($coli_sn, $wechat_host)
    {
        $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']);
        return $this->output->set_output($qrcode_src_url);
    }

    /**
     * @deprecated 0.1 通过带参数二维码关注的直接绑定,不再需要验证码绑定
     * 发送验证码
     */
    public function captcha_send()
    {
        $captcha = rand(100000, 999999);
        $mobile = $this->input->get_post('mobile');
        $nation = $this->input->get_post('nation');
        $openid = $this->input->get_post('openid');
        $user_id = $this->input->get_post('userid');
        $captcha_column = array(
            "wcc_value" => $captcha, "wcc_verifytype" => 'mobile', "wcc_wu_id" => $user_id, "wcc_mobileno" => $mobile, "wcc_nation" => $nation, "wcc_email" => null, "wcc_status" => 0, "wcc_expireseconds" => 300
        );
        $ret = array("captcha_value" => $captcha);
        $this->Wechat_service_model->insert_captcha($captcha_column);
        return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
    }

    /**
     * @deprecated 0.1 通过带参数二维码关注的直接绑定,不再需要验证码绑定
     * 验证码校验
     * @param mixed captcha
     * @param mixed $userid
     */
    public function captcha_verify()
    {
        $ret = array(
            "verify" => "failed", "failed_reason" => ""
        );
        $captcha = $this->input->get_post('captcha');
        $user_id = $this->input->get_post('userid');
        // $order_id = $this->input->get_post('order_id');
        // $order_type = $this->input->get_post('order_type');
        // verify captcha
        $captcha_data = $this->Wechat_service_model->get_verify($user_id, $captcha);
        if (empty($captcha_data)) {
            $ret['failed_reason'] = "Wrong captcha.";
        }
        if ($captcha_data['expire_time'] < date("Y-m-d H:i:s")) {
            $ret['failed_reason'] = "Captcha expired.";
        }
        if (strval($captcha_data['wcc_status']) !== '0') {
            $ret['failed_reason'] = "Captcha has been used.";
        }
        if ($ret['failed_reason'] !== '') {
            return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
        }
        // set verify status
        $this->Wechat_service_model->set_captcha_pass($captcha_data['wcc_id']);
        // new wechat customer
        $user_info = $this->Wechat_service_model->get_user($user_id);
        $customer_column = array(
            "wc_wu_id" => $user_id, "wc_coli_sn" => $user_info['wu_coli_sn'], "wc_htordertype" => $user_info['wu_htordertype']
        );
        $this->Wechat_service_model->insert_wechat_customer($customer_column);
        $ret['verify'] = "success";
        unset($ret['failed_reason']);
        return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
    }

    /**
     * 页面需要用户授权
     * 入口: https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect
     * 如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE
     * * redirect_uri: 授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
     * * scope: 应用授权作用域，snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且， 即使在未关注的情况下，只要用户授权，也能获取其信息 ）
     * * state: 重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节
     */
    /**
     * 页面授权, 获取用户openid, userid
     * @param mixed code code作为换取access_token的票据，每次用户授权带上的code将不一样，code只能使用一次，5分钟未被使用自动过期。
     * 获取access token的返回值:
     * * {
     * *     "access_token":"ACCESS_TOKEN",
     * *     "expires_in":7200,
     * *     "refresh_token":"REFRESH_TOKEN", // 用于刷新access_token
     * *     "openid":"OPENID",
     * *     "scope":"SCOPE"
     * * }
     * 刷新access token: https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
     */
    /**
     * 进入页面后静默登录
     * @link `/tours/{city}`
     */
    public function page_login($wechat_host)
    {
        $login_info = $this->get_page_access_token($wechat_host);
        return $this->output->set_content_type('application/json')->set_output(json_encode($login_info));
    }
    /**
     * 公众号菜单入口, 直接登录跳转
     * @link `My Itinerary`
     * 跳转顺序:
     * 1. 公众号菜单设置的地址: 页面授权入口[跳转页面参数=page_login | login_now, login_now?state参数区分不同的目标页面]
     * 2. 到达login_now, 通过state参数跳转到目标页面
     * * * state: [orders:My Itinerary; ]
     * ?user_id={id}
     * * https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx7e605820faf98a05&redirect_uri=http%3A%2F%2Ftrippest.mycht.cn%2Fapi%2Findex.php%2Fwechat-mp%2Flogin-now%2Ftrippest&response_type=code&scope=snsapi_base&state=Beijing#wechat_redirect
     */
    public function login_now($wechat_host)
    {
        // $login_info = array (
        //     'access_token' => '33_0XjLimrEnWdSb-cUVowwnQo7vxo-yB4-KWo1qOWLPx5ukXMUA-Bw5WZEzfXuayCEDWfQxQlJTzIMqZ79CTAeOg',
        //     'expires_in' => 7200,
        //     'refresh_token' => '33_mONKlYbwDcF7ixg0-P31NAcKAYwWNEhjLewwyn09NHOjcFUq-Bu-xHbYEvaRjnaAE4ZGkgYLJe7mgILbsjskNw',
        //     'openid' => 'oe2BW1C9G-gmtDyOqwIvOMg8L_FA',
        //     'scope' => 'snsapi_userinfo',
        //     'user_id' => NULL,
        //     'order_id' => NULL,
        //     'order_type' => NULL,
        //     'head_img' => 'http://thirdwx.qlogo.cn/mmopen/lXEiaQibaXvee79ia4mg0eP0ia0YHLtxNRs1JKpKnkxib7WPvFZtqQbHn7icmVoB90Up0x7A3qiaomovwKOf4lBcPbOmAsGBAOTPeyS/132',
        //     'nickname' => 'Lei、OT',
        //     'tourdata_v' => '201909111900'); // test:
        $login_info = $this->get_page_access_token($wechat_host);
        $state_target = $this->input->get_post('state');
        switch (strtolower($state_target)) {
            case 'orders':
                redirect(HOST . "account?userid=" . $login_info['user_id']);
                break;
            case 'detail':
                $path = $this->input->get_post('l'); // l=/order/{coli_sn}/{coli_id}
                redirect(HOST  . substr($path, 1) . "?userid=" . $login_info['user_id']);
                break;

            case 'guest':
                $path = $this->input->get_post('l');
                unset($login_info['access_token']);
                unset($login_info['refresh_token']);
                // remove first '/'
                $redirect_url = HOST . substr($path, 1) . "?userid=" . $login_info['user_id'];
                redirect($redirect_url);
                break;

            default: // cityname=pathname
                redirect(HOST . "tours/" . $state_target . "?userid=" . $login_info['user_id']);
                break;
        }
        return;
    }
    private function get_page_access_token($wechat_host)
    {
        $this->wechat_config = $this->config->item($wechat_host, 'wechat');
        $this->wechat_host = $wechat_host;
        $page_access = array("openid" => null);
        $userid = $this->input->get_post('userid');
        if ($userid === false || $userid === null) {
            $userid = null;
            $code = $this->input->get_post('code');
            $page_access_url = "/sns/oauth2/access_token";
            $query = array(
                "appid" => $this->wechat_config['app_id'],
                "secret" => $this->wechat_config['app_secret'],
                "code" => $code,
                "grant_type" => 'authorization_code',
            );
            // $page_access = array (
            //     'access_token' => '33_0XjLimrEnWdSb-cUVowwnQo7vxo-yB4-KWo1qOWLPx5ukXMUA-Bw5WZEzfXuayCEDWfQxQlJTzIMqZ79CTAeOg',
            //     'expires_in' => 7200,
            //     'refresh_token' => '33_mONKlYbwDcF7ixg0-P31NAcKAYwWNEhjLewwyn09NHOjcFUq-Bu-xHbYEvaRjnaAE4ZGkgYLJe7mgILbsjskNw',
            //     'openid' => 'oe2BW1C9G-gmtDyOqwIvOMg8L_FA',
            //     'scope' => 'snsapi_userinfo');
            // test:
            $page_access = json_decode($this->wechat_lib->call_wechat($wechat_host, $page_access_url, $query), true);
        }
        $user_info = $this->Wechat_service_model->get_user($userid, $this->wechat_config['app_id'], $page_access['openid']);
        if (empty($user_info) && strval($userid) !== '0') {
            $user_info = $this->subscribe_handle(array('FromUserName' => $page_access['openid']), false);
        }

        $page_access['openid'] = $user_info['wu_useropenid'];
        $page_access['user_id'] = $user_info['wu_id'] === null ? 0 : $user_info['wu_id'];
        $page_access['order_id'] = $user_info['wu_coli_sn'];
        $page_access['order_type'] = $user_info['wu_htordertype'];
        $page_access['head_img'] = $user_info['wu_headimg'];
        $page_access['nickname'] = $user_info['wu_nickname'];
        return $page_access;
    }

    private function get_user_info($openid)
    {
        // $access_token = $this->get_access_token();
        $url = "/cgi-bin/user/info";
        $query = array(
            'openid' => $openid,
            'lang' => 'en'
        );
        $user_info_response = json_decode($this->wechat_lib->call_wechat($this->wechat_host, $url, $query), true);
        return $user_info_response;
    }

    private function get_access_token()
    {
        $url = $this->config->item('url_domain', 'wechat') . "/cgi-bin/token?grant_type=client_credential&appid=" . $this->wechat_config['app_id'] . "&secret=" . $this->wechat_config['app_secret'];
        $access_token_arr = json_decode($this->wechat_lib->call_wechat($url), true);
        return $access_token_arr['access_token'];
    }

    private function event_handles($input)
    {
        switch (strtolower($input['Event'])) {
            case 'scan':
                $this->scan_handle($input);
                break;
            case 'subscribe':
                $this->subscribe_handle($input);
                break;
            case 'click':
                $this->click_handle($input);
                break;

            default:
                # code...
                break;
        }
        return;
    }

    private function click_handle($input)
    {
        $event_key = $input['EventKey'];
        $click_memu = $this->wechat_config['auto_reply']['menu'];
        if (isset($click_memu[$event_key])) {
            $reply_content = $click_memu[$event_key];
            return $this->wechat_lib->response_text($reply_content, $input['FromUserName'], $this->wechat_operator);
        }
        return $this->wechat_lib->response_text();
    }

    private function subscribe_handle($input, $response = true)
    {
        if ($response === true) {
            $reply_content = $this->wechat_config['auto_reply']['reply_follow'];
            $this->wechat_lib->response_text($reply_content, $input['FromUserName'], $this->wechat_operator);
        }
        $user_info = $this->get_user_info($input['FromUserName']);
        $from_order = explode("_", $user_info['qr_scene_str']); // ordersn_ordertype:435021757_27002
        $coli_sn = $from_order[0] ? $from_order[0] : null;
        $order_type = isset($from_order[1]) ? $from_order[1] : 27002;
        $mobile = null;
        $email = null;
        $nation = null;
        /**
         * 已绑定过的二维码不能再次绑定其他用户
         */
        if ($coli_sn !== null && false === $this->Wechat_service_model->if_order_bound($coli_sn, $order_type)) {
            $this->load->model('Order_model');
            $contact = $this->Order_model->get_order_contact($coli_sn, strval($order_type));
            !empty($contact) ? $mobile = $contact['phone_no'] : null;
            !empty($contact) ? $email = $contact['email'] : null;
            !empty($contact) ? $nation = $contact['nation'] : null;
        } else {
            $coli_sn = null;
            $order_type = null;
        }
        $user_column = array(
            "wu_mobileno"       => $mobile,
            "wu_email"          => $email,
            "wu_nation"         => $nation,
            "wu_coli_sn"        => $coli_sn,
            "wu_htordertype"    => $order_type,
            "wu_hostappid"      => $this->wechat_config['app_id'],
            "wu_useropenid"     => $user_info['openid'],
            "wu_subcribetime"   => date("Y-m-d H:i:s", $user_info['subscribe_time']),
            "wu_subscribescene" => $user_info['subscribe_scene'],
            "wu_nickname"       => $user_info['nickname'],
            "wu_sex"            => $user_info['sex'],
            "wu_language"       => $user_info['language'],
            "wu_country"        => $user_info['country'],
            "wu_province"       => $user_info['province'],
            "wu_city"           => $user_info['city'],
            "wu_headimg"        => $user_info['headimgurl'],
            "wu_unionid"        => ($user_info['unionid'] ? $user_info['unionid'] : null)
        );
        $user_id = $this->Wechat_service_model->insert_wechat_user($user_column);
        $user_column['wu_id'] = $user_id;
        // new wechat customer
        /**
         * * 扫描带参数二维码关注的直接绑定
         * * 给微信用户添加标签
         */
        if ($coli_sn !== null) {
            $customer_column = array(
                "wc_wu_id" => $user_id, "wc_coli_sn" => $coli_sn, "wc_htordertype" => $order_type
            );
            $wc_id = $this->Wechat_service_model->insert_wechat_customer($customer_column);
            // $access_token = $this->get_access_token(); // oe2BW1C9G-gmtDyOqwIvOMg8L_FA
            $url = "/cgi-bin/tags/members/batchtagging";
            $tag = array(
                "openid_list" => array($user_info['openid']),
                "tagid" => 101
            );
            $this->wechat_lib->call_wechat($this->wechat_host, $url, [], json_encode($tag, JSON_UNESCAPED_UNICODE));
            // 推送已下单未支付
            $pay_detail = $this->Order_model->order_info_to_pay($coli_sn);
            $order = $this->Order_model->order_detail($coli_sn);
            $order['wechat'] = array("wc_id" => $wc_id, "wu_id" => $user_id);
            $this->wechat_lib->push_book_ok('trippest', $pay_detail['openid'], $order);
        }
        return $user_column;
    }

    private function scan_handle($input)
    {
        // 记录已关注扫描事件, 未绑定的增加绑定
        $parse_source = explode('_', $input['EventKey']);
        if (is_numeric($parse_source[0]) === true) {
            $user_info = $this->Wechat_service_model->get_user(null, $this->wechat_config['app_id'], $input['FromUserName']);
            $customer_column = array(
                "wc_wu_id" => $user_info['wu_id'],
                "wc_coli_sn" => $parse_source[0],
                "wc_htordertype" => isset($parse_source[1]) ? $parse_source[1] : 27002
            );
            $wc_id = $this->Wechat_service_model->insert_wechat_customer($customer_column);
            // 推送已下单未支付
            $pay_detail = $this->Order_model->order_info_to_pay($parse_source[0]);
            $order = $this->Order_model->order_detail($parse_source[0]);
            if ( ! empty($order['orderTour'])) {
                $order['wechat'] = array("wc_id" => $wc_id, "wu_id" => $user_info['wu_id']);
                $this->wechat_lib->push_book_ok('trippest', $pay_detail['openid'], $order);
            }
        }
        $this->wechat_lib->response_text();
        return true;
    }

    private function text_handle($input)
    {
        $reply_content = $this->wechat_config['auto_reply']['reply_text'];
        $this->wechat_lib->response_customer_service($reply_content, $input['FromUserName'], $this->wechat_operator);
        $this->wechat_lib->send_text_customer($this->wechat_host, $input['FromUserName'], $reply_content);
        // to customer service
        $operator_mailbody = "<p> Dear : </p>" .
            "<p>收到客人微信问询：<br /></p>" .
            "<p>" . $input['Content'] ."</p>" .
            "<p>发送时间:" . date("Y-m-d H:i:s", $input['CreateTime']) ."</p>";
        $operator_mailbody .= "<p> 此邮件由系统自动发送, 请勿回复.</p>";
        $this->Order_model->SendMail(
            "chinahighlights",
            "webform@chinahighlights.net",
            "Niko",
            "niko@trippest.com",
            '#微信客人问询# TP公众号来客人啦，快去看看哦 ' ,
            $operator_mailbody);
        return true;
    }

    public function convert_json_to_php()
    {
        $folder = FCPATH . 'bokun-product';
        if (!is_dir($folder)) {
            log_message('error', 'not found data dir');
            echo "not found.";
            return;
        }
        $files = array_values(array_diff(scandir($folder), array('.', '..')));
        if (empty($files)) {
            echo "none.";
            return;
        }
        foreach ($files as $key => $json_file) {
            $extension = strstr($json_file, ".");
            if (strtolower($extension) !== ".json") {
                continue;
            }
            $json = json_decode(file_get_contents($folder . "\\" . $json_file), true);
            $this_file = fopen($folder . "\\" . strstr($json_file, ".", true) . ".php", "w+");
            fwrite($this_file, "<?php\r\n" . '$data=' . var_export_min($json, 1) . ";");
            fclose($this_file);
            $json = null;
        }
        echo ("success");
        return;
    }

    public function tour_data($city_name)
    {
        $data = null;
        if ($city_name==='city-list') {
            return $this->city_list();
        }
        include FCPATH . 'bokun-product' . "\\" . $city_name . ".php";
        if (isset($data['items'])) {
            array_walk($data['items'], function (&$item) {
                $item['pricesByDateRange'] = $this->get_bokun_price($item['activity']['id']);
            });
        }
        return $this->output->set_content_type('application/json')->set_output(json_encode($data));;
    }
    private function city_list()
    {
        $data = null;
        include FCPATH . 'bokun-product\summary.php';
        foreach ($data['top_list'] as $key => &$top) {
            foreach ($top as $kt => &$vt) {
                if ( ! empty($vt['sublist'])) {
                    foreach ($vt['sublist'] as $ks => &$vs) {
                        if (isset($data[$vs['id'] . '_code'])) {
                            $vs['items'] = $data[$vs['id'] . '_code'];
                        }
                    }
                }
            }
        }
        $ret = $data['top_list'];
        // $ret['version'] = $data['version'];
        return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
    }

    public function get_bokun_price($bokun_activity_id = null)
    {
        $ret = null;
        $today = time();
        $folder = FCPATH . 'bokun-product\price';
        $bokun_activity_id = $bokun_activity_id ? $bokun_activity_id : $this->input->get_post('activityId');
        if (file_exists($folder . "\\" . $bokun_activity_id . ".php")) {
            $data = null;
            include FCPATH . 'bokun-product\price' . "\\" . $bokun_activity_id . ".php";
            usort($data['pricesByDateRange'], function ($a, $b) {
                return strtotime($a['from']) - strtotime($b['from']);
            });
            foreach ($data['pricesByDateRange'] as $key => $price_date) {
                if (!isset($price_date['to'])) {
                    $price_date['to'] = strtotime("+10 days");
                }
                if ($today >= strtotime($price_date['from']) && $today <= strtotime($price_date['to'])) {
                    $ret = $price_date;
                    break;
                }
            }
        }
        if ($ret !== null) {
            return $ret;
        }
        log_message('error', 'not found price data file. ' . $bokun_activity_id);
        $price_list_arr = $this->get_product_price($bokun_activity_id);
        foreach ($price_list_arr['pricesByDateRange'] as $key => $price_date) {
            if (!isset($price_date['to'])) {
                $price_date['to'] = strtotime("+10 days");
            }
            if ($today >= strtotime($price_date['from']) && $today <= strtotime($price_date['to'])) {
                $ret = $price_date;
                break;
            }
        }
        return $ret;
    }

    /*!
     * @Author: LYT: lyt@hainatravel.com
     * @Date: 2019-11-07 14:11:52
     * @Desc: 接收Bokun的推送
     * * 推送请求示例:
     * * GET
            array (
            'trigger' => 'PRODUCT_AVAILABILITY_UPDATE', // PRODUCT_INFO_UPDATE
            'productCategory' => 'ACTIVITIES',
            'productId' => '75348',
            )
            array (
            'trigger' => 'PRODUCT_LIST_UPDATE',
            'productListId' => '9880',
            )
     */
    public function bokun_notify()
    {
        $folder = FCPATH . 'bokun-product';
        $input = $this->input->post() ? $this->input->post() : $this->input->get();
        log_message('debug', 'bokun_notify' . PHP_EOL . var_export($input, 1));
        $data = array();
        include $folder . "\\" . "summary.php";
        $data_summary = $data;
        switch ($input['trigger']) {
            case 'PRODUCT_LIST_UPDATE':
                $list_id = $input['productListId'];
                $data_summary = $data;
                // 所有 product list 本身的信息, logo,cover等
                $product_list = $this->bokun_lib->get_all_product_list();
                $product_list_arr = json_decode($product_list, true);
                $pick_flags = array_unique_fb(array_column($product_list_arr, 'flags'));
                $list_flags = [];
                foreach ($pick_flags as $key => $flag_arr) {
                    $list_flags = array_merge($list_flags, array_values($flag_arr));
                }
                $list_flags = array_filter(array_unique($list_flags));
                $city_list_file = fopen($folder . "\\" . "city-list.php", "w+");
                fwrite($city_list_file, "<?php\r\n" . '$data=' . var_export_min($product_list_arr, 1) . ";");
                fclose($city_list_file);
                // 生成摘要信息, 方便后续查询用
                $list_id_title = array();
                $data_summary['top_list'] = array();
                $data_summary['version'] = date('YmdHi');
                foreach ($list_flags as $key => $flag) {
                    foreach ($product_list_arr as $key => $list) {
                        $list_id_title[$list['id']] = mb_ereg_replace('[^a-zA-Z]', '',  strtolower($list['title']));
                        if (in_array($flag,$list['flags']) ||
                            ($flag==='Popular China Destinations' && empty($list['flags']))
                        ) {
                            $temp = [];
                            foreach ($list['children'] as $kc => $vs) {
                                $temp[] = [ 'id' => $vs['id'], 'title' => $vs['title'], 'size'=>$vs['size'] ];
                                // sublist
                                $list_id_title[$vs['id']] = $vs['title'];
                            }
                            usort($temp, "Wechat_mp::sublists_order");
                            $data_summary['top_list'][$flag][] = [ 'id' => $list['id'], 'title' => $list_id_title[$list['id']], 'sublist' => $temp ];
                        }
                    }
                }
                $data_summary['list'] = $list_id_title;
                // product list 包含的 product
                $product_detail_arr = $this->save_product_list($list_id, $data_summary['list'][$list_id]);
                // 生成摘要信息, 方便后续查询用
                $this_list_items_id = array_map(function ($ele) {
                    return $ele['activity']['id'];
                }, $product_detail_arr['items']);
                $this_list_items_code = array_map(function ($ele) {
                    return $ele['activity']['externalId'];
                }, $product_detail_arr['items']);
                $data_summary[$list_id] = $this_list_items_id;
                $data_summary[$list_id.'_code'] = $this_list_items_code;
                $summary_file = fopen($folder . "\\" . "summary.php", "w+");
                fwrite($summary_file, "<?php\r\n" . '$data=' . var_export_min($data_summary, 1) . ";");
                fclose($summary_file);
                break;

            case 'PRODUCT_INFO_UPDATE':
                $product_id = $input['productId'];
                $product_list_id = null;
                foreach ($data_summary as $ks => $vs) {
                    if ($ks === 'list') {
                        continue;
                    }
                    if (in_array($product_id, $vs)) {
                        $product_list_id = $ks;
                        break;
                    }
                }
                if ($product_list_id) {
                    $this->save_product_list($product_list_id, $data_summary['list'][$product_list_id]);
                } else {
                    log_message('debug', 'no_found_product_list' . PHP_EOL . var_export($product_id, 1));
                }
                break;

            case 'PRODUCT_AVAILABILITY_UPDATE':
                $product_id = $input['productId'];
                $this->get_product_price($product_id);
                break;

            default:
                break;
        }
        return $this->output->set_content_type('application/json')->set_output(json_encode("OK"));
    }
    /**
     * 自定义的排序sublists
     */
    private function sublists_order($a, $b)
    {
        $orders = array(
            'Day Trips',
            'Day Tours',
            'Great Wall Experience',
            'Interesting Activities',
            'Walking & Hiking Tours',
            'Airport Transfer',
            'Railway Station Transfer',
            'Cruise Port Transfer',
            'Shore Excursion',
            'Shore Excursions',
            'Multi Day Tours'
        );
        $a_index = array_search($a['title'], $orders);
        $b_index = array_search($b['title'], $orders);
        if ($a_index === $b_index) {
            return 0;
        }
        return ($a_index < $b_index) ? -1 : 1;
    }

    private function save_product_list($list_id, $list_title)
    {
        if (!$this->bokun_lib) {
            $this->load->library('Bokun_lib');
        }
        $folder = FCPATH . 'bokun-product';
        $product_detail = $this->bokun_lib->get_product_list_detail($list_id);
        $product_detail_arr = json_decode($product_detail, true);
        $list_detail_file = fopen($folder . "\\" . $list_title . ".php", "w+");
        fwrite($list_detail_file, "<?php\r\n" . '$data=' . var_export_min($product_detail_arr, 1) . ";");
        fclose($list_detail_file);
        return $product_detail_arr;
    }

    private function get_product_price($product_id)
    {
        $folder = FCPATH . 'bokun-product\price';
        $price_list = $this->bokun_lib->get_activity_price($product_id);
        $price_list_arr = json_decode($price_list, true);
        if ($price_list_arr===null) {
            $price_list_arr['pricesByDateRange'] = array();
            return $price_list_arr;
        }
        usort($price_list_arr['pricesByDateRange'], function ($a, $b) {
            return strtotime($a['from']) - strtotime($b['from']);
        });
        // if (isset($price_list_arr['pricesByDateRange'][0]['rates'][0]['passengers'][0]['tieredPrices'])) {
        //     array_walk_recursive($price_list_arr['pricesByDateRange'], function ()
        //     {
        //     });
        // }
        $this_file = fopen($folder . "\\" . $product_id . ".php", "w+");
        fwrite($this_file, "<?php\r\n" . '$data=' . var_export_min($price_list_arr, 1) . ";");
        fclose($this_file);
        return $price_list_arr;
    }

    public function search_activity()
    {
        $text = $this->input->get_post('search');
        $ret = $this->bokun_lib->search_by_text($text);
        $data = array();
        include FCPATH . 'bokun-product\summary.php';
        array_walk($ret, 'Wechat_mp::get_tour_list_name', $data);
        $ret = array_values(array_filter($ret, function ($ele)
        {
            return $ele->list_name !== '';
        }));
        return $this->output->set_content_type('application/json')->set_output(json_encode($ret));
    }
    private function get_tour_list_name(&$activity, $k, $data)
    {
        $list_ids = 0;
        $activity->list_name = '';
        foreach ($data as $key => $list) {
            if ( ! is_array($list)) {
                continue;
            }
            $search_id = array_search($activity->id, $list);
            if ($search_id !== false) {
                $list_ids = $key;
                break;
            }
        }
        if ($list_ids!==0) {
            $activity->list_name = $data['list'][$list_ids];
        }
    }
}

/* End of file Wechat_mp.php */
