<?php

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

class getbokun extends CI_Controller
{

    //var $webUrl = "http://localhost:105"; //本地调用地址
    var $webUrl = "https://ct.mycht.cn/";  //网前调用地址
    public function __construct()
    {
        parent::__construct();
        $this->permission->is_admin();
        $this->load->library("Bokun_lib");
        $this->load->model("tpBokun_model");
    }

    public function index()
    {
        //echo "bokun数据导入页面！";
        $this->load->view('bootstrap3/header');
        $this->load->view('getindex');
        $this->load->view('bootstrap3/footer');
    }

    /*
    "activity":{
        "readme":"这个json数据用来记录从bokun接口中获取的数据项",
        "id": 75363, //产品activity的ID
        "published": false,  //不确定是否需要用这个来判断发布
        "title": "Mini Group: 2-Day Beijing Boutique Tour: Forbidden City, Mutianyu Great Wall, Summer Palace and Temple of Heaven",
        "description": "",
        "excerpt": "", 
        "requiredCustomerFields": [
            "firstName",
            "lastName",
            "email",
            "phoneNumber",
            "nationality",
            "passportId"
        ],  //这个主要是判断passportId在预订表单是否需要录入
        "keyPhoto": {
            "id": 343309,
            "originalUrl": "https://bokun.s3.amazonaws.com/ddaf9b4b-72b0-4062-9978-7a060bda32d4.jpg",
            "description": "Temple of Heaven",
            "alternateText": "Temple of Heaven",
            "height": null,
            "width": null,
            "flags": [],
            "derived": [
            {
                "name": "large",
                "url": "https://bokunprod.imgix.net/ddaf9b4b-72b0-4062-9978-7a060bda32d4.jpg?w=660&h=660",
                "cleanUrl": "https://bokunprod.imgix.net/ddaf9b4b-72b0-4062-9978-7a060bda32d4.jpg?w=660&h=660"
            },
            {
                "name": "preview",
                "url": "https://bokunprod.imgix.net/ddaf9b4b-72b0-4062-9978-7a060bda32d4.jpg?w=300&h=300",
                "cleanUrl": "https://bokunprod.imgix.net/ddaf9b4b-72b0-4062-9978-7a060bda32d4.jpg?w=300&h=300"
            },
            {
                "name": "thumbnail",
                "url": "https://bokunprod.imgix.net/ddaf9b4b-72b0-4062-9978-7a060bda32d4.jpg?w=80&h=80&fit=crop",
                "cleanUrl": "https://bokunprod.imgix.net/ddaf9b4b-72b0-4062-9978-7a060bda32d4.jpg?w=80&h=80&fit=crop"
            }
            ],
            "fileName": "/ddaf9b4b-72b0-4062-9978-7a060bda32d4.jpg"
        },  //产品主要图片
        "photos": [
            {
            "id": 343297,
            "originalUrl": "https://bokun.s3.amazonaws.com/8b40e352-6410-4e43-a150-21ad918188d3.jpg",
            "description": "Bird view of Forbidden City from Jingshan Park",
            "alternateText": "Bird view of Forbidden City from Jingshan Park",
            "height": null,
            "width": null,
            "flags": [],
            "derived": [
                {
                "name": "large",
                "url": "https://bokunprod.imgix.net/8b40e352-6410-4e43-a150-21ad918188d3.jpg?w=660&h=660",
                "cleanUrl": "https://bokunprod.imgix.net/8b40e352-6410-4e43-a150-21ad918188d3.jpg?w=660&h=660"
                },
                {
                "name": "preview",
                "url": "https://bokunprod.imgix.net/8b40e352-6410-4e43-a150-21ad918188d3.jpg?w=300&h=300",
                "cleanUrl": "https://bokunprod.imgix.net/8b40e352-6410-4e43-a150-21ad918188d3.jpg?w=300&h=300"
                },
                {
                "name": "thumbnail",
                "url": "https://bokunprod.imgix.net/8b40e352-6410-4e43-a150-21ad918188d3.jpg?w=80&h=80&fit=crop",
                "cleanUrl": "https://bokunprod.imgix.net/8b40e352-6410-4e43-a150-21ad918188d3.jpg?w=80&h=80&fit=crop"
                }
            ],
            "fileName": "/8b40e352-6410-4e43-a150-21ad918188d3.jpg"
            }
        ],  //产品其它图片
        "included": "<ul><li></li></ul> ", //包含
        "excluded": "<ul><li></li></ul> ",//不包含
        "requirements": "<ul><li></li></ul> ", //需求
        "attention": "<ul><li></li></ul> ", //景点，条例，与上面4个合并到
        "country": "China",
        "city": "Beijing",
        "durationText": "2 days",
        "agendaItems": [{
            "title": "",
            "excerpt": "",
            "body": "",
            "day": 1,  
            "keyPhoto":{}，
            "photos":[{}]
        }
        ],  //行程描述，合并后放信息平台的详细内容里面,其中行程图片和整个产品图片一样，放头部

        }
    }
     
    */


    /**
     * @description: 获取bokunapi的所有产品数据，按城市,类别，产品一步步的循环录入
     * @param string $city 城市名称
     * @return: 
     */
    function getAll_Bokun($city = "")
    {

        //先进行对应城市的更新
        // $this->checkAllCity();

        //循环接口开始
        $result = $this->bokun_lib->get_all_product_list();
        //print_r($result);
        $result = json_decode($result);
        if (is_array($result) && count($result) > 0) {
            //productlist是所有产品，按城市分类，然后child里面是类别分类
            foreach ($result as $pItem) {
                $cityName = str_replace("'", "", $pItem->title); //城市名称，用来判断信息平台是否有该城市
                if (isset($cityName)) {
                    if ($city != "" && strtolower($city) != strtolower($cityName)) {
                        continue;  //如果设置了指定抓取城市
                    } else {

                        $list_id = $pItem->id;
                        $pchild_Detail = $this->bokun_lib->get_product_list_detail($list_id);
                        $data_pchild_Detail = json_decode($pchild_Detail); //类别详细
                        foreach ($data_pchild_Detail->items as $pcdItem) { //循环类别
                            $activityData = $pcdItem->activity; //产品详细内容
                            $this->doActivity($activityData, $cityName);
                        }
                    }
                }
            }
            echo ("抓取完成！\r\n");
        } else {
            echo "无接口数据！";
        }
    }

    /**
     * @description: 处理每个产品（activity),分析及入库
     * @param {type} $ActivityData: 产品的JSON数据
     * @param string $CityName:因为activity里面的城市名称和总分类的名称可能不一样，比如bagan,详细里面是old bagan。直接传递
     * @param bool $OverWrive:是否覆盖已导入的产品
     * @return: 
     * @Date Changed: 
     */
    function doActivity($ActivityData, $CityName = "", $OverWrive = false)
    {

        // print_r($ActivityData);
        // die();

        //解析后获取需要的参数
        $activityId = $ActivityData->id; //产品的activityId，可以获取对应的产品详细内容。
        $PAGCode = "bk_" . $activityId;

        //先判断是否是新产品
        // $checkNewUrl = $this->webUrl . "/info.php/thirdparty/tpmanage/webgetbokun/checkActivityId/$activityId/";
        // $checkNew = json_decode($this->tpBokun_model->getCrulData($checkNewUrl));
        // if ($checkNew->return == "yes" && $OverWrive == false) {
        //     return;
        // }

        $checkNew = $this->tpBokun_model->checkExitHT($PAGCode);
        if ($checkNew) {
            return;  //直接判断本地翰特，这样快很多
        }

        //提交网前接口

        $checkCode = "cits"; //用来防止参数被破解
        $PassParam["activityid"] = $activityId;
        $PassParam["PAG_Code"] = $PAGCode;
        $PassParam["CityName"] = $CityName;
        $PassParam["checkCode"] = $checkCode;
        $strPass = base64_encode(json_encode($PassParam));
        $AddUrl = $this->webUrl . "/info.php/thirdparty/tpmanage/webgetbokun/addActivity/$strPass/";
        $addInfo = json_decode($this->tpBokun_model->getCrulData($AddUrl));
        //echo($addInfo);

        if ($addInfo->status == "ok") {

            //先判断是否是新产品
            $checkNew = $this->tpBokun_model->checkExitHT($PAGCode);
            if ($checkNew) {
                continue;
            }
            //提交本地翰特保存
            if ($CityName == "") {
                $CityName = $ActivityData->googlePlace->city; //如果没有传递城市名称参数，就获取activity数据中的
            }

            $PAG_CII_SN = $this->tpBokun_model->getCityIdByName($CityName);
            if ($PAG_CII_SN != null) {
                $this->tpBokun_model->PAG_CII_SN = $PAG_CII_SN->CII2_CII_SN;
            }
            $this->tpBokun_model->PAG_Code = $PAGCode;
            $this->tpBokun_model->PAG_Title = $ActivityData->title;
            $this->tpBokun_model->PAG_PPI_SN = $ActivityData->id;
            $this->tpBokun_model->PAG2_Name = $ActivityData->title;
            $this->tpBokun_model->PAG2_Title = $ActivityData->description;
            $pagsn = $this->tpBokun_model->AddProductToHT();
        }
        echo ("产品:" . $PAGCode . "," . $pagsn . " 完成.");
    }

    /**
     * @description: 提交到前端接口，执行更新所有城市的操作
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function checkAllCity()
    {
        $url = "/info.php/thirdparty/tpmanage/webgetbokun/checkAllCity/";
        $str =  $this->tpBokun_model->getCrulData($url);
        echo $str;
    }

    /**
     * @description: 只更新翰特的产品信息
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function onlyUpdateHT($city = "")
    {
        //循环接口开始
        $result = $this->bokun_lib->get_all_product_list();
        //print_r($result);
        $result = json_decode($result);
        if (is_array($result) && count($result) > 0) {
            //productlist是所有产品，按城市分类，然后child里面是类别分类
            foreach ($result as $pItem) {
                $cityName = str_replace("'", "", $pItem->title); //城市名称，用来判断信息平台是否有该城市
                if (isset($cityName)) {
                    if ($city != "" && strtolower($city) != strtolower($cityName)) {
                        continue;  //如果设置了指定抓取城市
                    } else {

                        $list_id = $pItem->id;
                        $pchild_Detail = $this->bokun_lib->get_product_list_detail($list_id);
                        $data_pchild_Detail = json_decode($pchild_Detail); //类别详细
                        foreach ($data_pchild_Detail->items as $pcdItem) { //循环类别
                            $activityData = $pcdItem->activity; //产品详细内容
                            //提交本地翰特保存
                            if ($cityName == "") {
                                $cityName = $activityData->googlePlace->city; //如果没有传递城市名称参数，就获取activity数据中的
                            }

                            $PAG_CII_SN = $this->tpBokun_model->getCityIdByName($cityName);
                            if ($PAG_CII_SN != null) {
                                $this->tpBokun_model->PAG_CII_SN = $PAG_CII_SN->CII2_CII_SN;
                            }
                            //解析后获取需要的参数
                            $activityId = $activityData->id; //产品的activityId，可以获取对应的产品详细内容。
                            $PAGCode = "bk_" . $activityId;
                            //先判断是否是新产品
                            $checkNew = $this->tpBokun_model->checkExitHT($PAGCode);
                            if ($checkNew) {
                                //判断是否有价格，没有就导入
                                $pag_row = $this->tpBokun_model->getToursDetails($PAGCode);
                                if ($pag_row != null) {
                                    $PAG_SN = $pag_row->PAG_SN;
                                    if ($PAG_SN > 0) {
                                        //有产品ID才能获取对应的价格
                                        if ($this->tpBokun_model->checkPrice($PAG_SN) == false) {
                                            //没价格开始导入
                                            $this->doPrice($PAG_SN,$activityId);
                                        }
                                    }
                                }
                                //跳过不再保存主数据
                                continue;
                            }
                            $this->tpBokun_model->PAG_Code = $PAGCode;
                            $this->tpBokun_model->PAG_Title = $activityData->title;
                            $this->tpBokun_model->PAG_PPI_SN = $activityData->id;
                            $this->tpBokun_model->PAG2_Name = $activityData->title;
                            $this->tpBokun_model->PAG2_Title = $activityData->description;
                            $pagsn = $this->tpBokun_model->AddProductToHT();
                            echo ("添加：" . $PAGCode . "," . $pagsn . "\r\n");
                            //价格开始导入
                            $this->doPrice($pagsn,$activityId);
                        }
                    }
                }
            }
            echo ("抓取完成 \r\n");
        } else {
            echo "无接口数据！";
        }
    }

    /**
     * @description: 导入价格列表
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function doPrice($PAG_SN, $activityId)
    {

        if ($PAG_SN > 0) {
            //价格接口数据
            $result = $this->bokun_lib->get_activity_price($activityId);
            $result = json_decode($result);
            if (is_array($result->pricesByDateRange)) {
                foreach ($result->pricesByDateRange as $PriceItem) {
                    //每个时间段的价格循环
                    //开始时间
                    if (isset($PriceItem->from)) {
                        $starDate = $PriceItem->from;
                    } else {
                        $starDate = date('Y-m-d');
                    }

                    //结束时间
                    if (isset($PriceItem->to)) {
                        $endDate = $PriceItem->to;
                    } else {
                        $endDate = date('Y-m-d', strtotime('+1 year',strtotime($starDate)));
                    }

                    if (isset($PriceItem->rates) && is_array($PriceItem->rates)) {
                        foreach ($PriceItem->rates as $PriceItem_rates) {
                            //rates层
                            if (isset($PriceItem_rates->passengers) && is_array($PriceItem_rates->passengers)) {

                                $arrAdultPrice = array(); //存放成人价格列表
                                $arrOhterPrice = array(); //存放儿童和婴儿价格列表
                                foreach ($PriceItem_rates->passengers as $PriceItem_rates_passengers) {
                                    $AdultPriceClass = new stdClass;
                                    $OtherPriceClass = new stdClass;
                                    $ticketCategory = $PriceItem_rates_passengers->ticketCategory; //判断是大人，小孩
                                    if ($ticketCategory == "ADULT" || $ticketCategory == "CHILD" || $ticketCategory == "INFANT") {
                                        $priceType = $ticketCategory;
                                    } else {
                                        $priceType = "ADULT";
                                    }
                                    //passengers层
                                    if (isset($PriceItem_rates_passengers->tieredPrices) && is_array($PriceItem_rates_passengers->tieredPrices)) {
                                        //这个是有多个人等价格
                                        foreach ($PriceItem_rates_passengers->tieredPrices as $tieredPricesItem) {
                                            $AdultPriceClass = new stdClass;
                                            $OtherPriceClass = new stdClass;
                                            $minPassengersRequired = $tieredPricesItem->minPassengersRequired;
                                            if (isset($tieredPricesItem->maxPassengersRequired)){
                                                $maxPassengersRequired = $tieredPricesItem->maxPassengersRequired;
                                            }else{
                                                $maxPassengersRequired = $minPassengersRequired;
                                            }
                                            if (isset($tieredPricesItem->amount)){
                                                $amount = $tieredPricesItem->amount;
                                            }else{
                                                $amount = 0;
                                            }
                                            if ($priceType == "ADULT") {
                                                $AdultPriceClass->PersonStart = $maxPassengersRequired;
                                                $AdultPriceClass->PersonStop = $maxPassengersRequired;
                                                $AdultPriceClass->type = "ADULT";
                                                $AdultPriceClass->price = $amount;
                                                $arrAdultPrice[] = $AdultPriceClass;
                                            } elseif ($priceType == "CHILD") {
                                                $OtherPriceClass->PersonStart = $maxPassengersRequired;
                                                $OtherPriceClass->PersonStop = $maxPassengersRequired;
                                                $OtherPriceClass->type = "CHILD";
                                                $OtherPriceClass->price = $amount;
                                                $arrOhterPrice[] = $OtherPriceClass;
                                            } elseif ($priceType == "INFANT") {
                                                $OtherPriceClass->PersonStart = $maxPassengersRequired;
                                                $OtherPriceClass->PersonStop = $maxPassengersRequired;
                                                $OtherPriceClass->type = "INFANT";
                                                $OtherPriceClass->price = $amount;
                                                $arrOhterPrice[] = $OtherPriceClass;
                                            }
                                        }
                                    } elseif (isset($PriceItem_rates_passengers->price)) {
                                        //这个是无人等价格
                                        if ($priceType == "ADULT") {
                                            $AdultPriceClass->PersonStart = 1;
                                            $AdultPriceClass->PersonStop = 100;
                                            $AdultPriceClass->type = "ADULT";
                                            $AdultPriceClass->price = $PriceItem_rates_passengers->price->amount;
                                            $arrAdultPrice[] = $AdultPriceClass;
                                        } elseif ($priceType == "CHILD") {
                                            $OtherPriceClass->PersonStart = 1;
                                            $OtherPriceClass->PersonStop = 100;
                                            $OtherPriceClass->type = "CHILD";
                                            $OtherPriceClass->price = $PriceItem_rates_passengers->price->amount;
                                            $arrOhterPrice[] = $OtherPriceClass;
                                        } elseif ($priceType == "INFANT") {
                                            $OtherPriceClass->PersonStart = 1;
                                            $OtherPriceClass->PersonStop = 100;
                                            $OtherPriceClass->type = "INFANT";
                                            $OtherPriceClass->price = $PriceItem_rates_passengers->price->amount;
                                            $arrOhterPrice[] = $OtherPriceClass;
                                        }
                                    }
                                }

                                //分析生存的数组$arrAdultPrice与$arrOhterPrice ,构建可以入库的数据
                                $arrPackagePrice = array();
                                foreach ($arrAdultPrice as $aAPItem) {
                                    $PackagePriceClass = new stdClass;

                                    $PersonStart = $aAPItem->PersonStart;
                                    $PersonStop = $aAPItem->PersonStop;
                                    $AdultPrice = $aAPItem->price;
                                    $ChildPrice = $AdultPrice;
                                    $InfantPrice = 0;
                                    foreach ($arrOhterPrice as $aOPItem) {
                                        //循环查找对应的儿童及婴儿价
                                        if ($aOPItem->PersonStart == $PersonStart && $aOPItem->PersonStop == $PersonStop) {
                                            //人数限制范围相同时
                                            if ($aOPItem->type == "CHILD") {
                                                $ChildPrice = $aOPItem->price;
                                            } elseif ($aOPItem->type == "INFANT") {
                                                $InfantPrice = $aOPItem->price;
                                            }
                                        } elseif ($aOPItem->PersonStart == $PersonStart) {
                                            //有时候限制范围不一样，只能去开始的人数来判断
                                            if ($aOPItem->type == "CHILD") {
                                                $ChildPrice = $aOPItem->price;
                                            } elseif ($aOPItem->type == "INFANT") {
                                                $InfantPrice = $aOPItem->price;
                                            }
                                        }
                                    }
                                    //组建人数限制，成人价，儿童价，婴儿价的class
                                    $PackagePriceClass->PKP_PersonStart = $PersonStart;
                                    $PackagePriceClass->PKP_PersonStop = $PersonStop;
                                    $PackagePriceClass->PKP_AdultPrice = $AdultPrice;
                                    $PackagePriceClass->PKP_ChildPrice = $ChildPrice;
                                    $PackagePriceClass->PKP_InfantPrice = $InfantPrice;
                                    $arrPackagePrice[] = $PackagePriceClass;
                                }

                                //数据入库
                                if (count($arrPackagePrice) > 0) {
                                    foreach ($arrPackagePrice as $aPPItem) {
                                        //循环入库
                                        $this->tpBokun_model->PKP_PAG_SN = $PAG_SN;
                                        $this->tpBokun_model->PKP_AdultPrice = $aPPItem->PKP_AdultPrice;
                                        $this->tpBokun_model->PKP_ChildPrice = $aPPItem->PKP_ChildPrice;
                                        $this->tpBokun_model->PKP_InfantPrice = $aPPItem->PKP_InfantPrice;
                                        $this->tpBokun_model->PKP_AdultNetPrice = $aPPItem->PKP_AdultPrice;
                                        $this->tpBokun_model->PKP_ChildNetPrice = $aPPItem->PKP_ChildPrice;
                                        $this->tpBokun_model->PKP_InfantNetPrice = $aPPItem->PKP_InfantPrice;
                                        $this->tpBokun_model->PKP_PersonStart = $aPPItem->PKP_PersonStart;
                                        $this->tpBokun_model->PKP_PersonStop = $aPPItem->PKP_PersonStop;
                                        $this->tpBokun_model->PKP_ValidDate = $starDate;
                                        $this->tpBokun_model->PKP_InvalidDate = $endDate;
                                        $this->tpBokun_model->AddPriceToHT();
                                        echo "添加价格:".$PAG_SN."(".$aPPItem->PKP_PersonStart." - ".$aPPItem->PKP_PersonStop.")". "\r\n";
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

/* End of file getbokun.php */
