<?php

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

class TpBokun_model extends CI_Model
{


    public function __construct()
    {
        parent::__construct();
        $this->HT = $this->load->database('HT', TRUE);
        $this->HT229Write = $this->load->database('HT229Write',TRUE); //本地,包含144本地执行。
       // $this->HT229Write = $this->load->database('HT', TRUE); //网前，主要是提交到CH服务器导致没有HT229Write的链接错误。网前也不执行这个页面的操作。
        $this->load->model("IContent_model");
        $this->load->model("IStructures_model");
        $CI = &get_instance();
    }

    /**
     *  获取信息平台的内容,所有信息，包含发布和没发布的
     */
    function getInfomationAll($guideurl)
    {
        //  $sql = "select top 1 * from infoContents a inner join infoStructures b on a.ic_id=b.is_ic_id where ic_URL='".$guideurl."'  and ic_status=1  and is_siteCode='ct'";
        $sql = "select top 1 * from infoContents a inner join infoStructures b on a.ic_id=b.is_ic_id where ic_URL='" . $guideurl . "' and is_siteCode='trippest'";
        $query = $this->HT->query($sql);
        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return null;
        }
    }

    /**
     * @description: 检查是否是新的bokun产品，根据infobokundata表的activityid记录
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function checkActivityId($activityid)
    {
        $sql = "select top 1 * from infobokundata  where ibd_itemname='ActivityID' and CONVERT(varchar(100),ibd_itemvalue)=?";
        $query = $this->HT->query($sql, array($activityid));
        if ($query->num_rows() > 0) {
            $result["return"] = "yes";
        } else {
            $result["return"] = "no";
        }
        return json_encode($result);
    }

    /**
     * @description:  通过链接标题判断CHT的产品是否已经导入
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function checkChtTours($ic_url_title)
    {
        $sql = "select top 1 * from infoContents where ic_url_title = ?";
        $query = $this->HT->query($sql, array($ic_url_title));
        if ($query->num_rows() > 0) {
            return true;
        } else {
            return false;
        }
    }



    /**
     * @description: 根据城市名称获取城市ID
     * @param string $cityname:城市名称
     * @return: 
     * @Date Changed: 
     */
    function getCityIdByName($cityname)
    {
        $sql = "select top 1 CII2_CII_SN from CItyInfo2 where CII2_Name = '" . $cityname . "' and CII2_LGC=1";
        $query = $this->HT->query($sql);
        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return null;
        }
    }

    /**-------------------抓取程序------------------------- */
    //var $is_topId = "278000665";  //本地产品的最高级父类
    var $is_topId = "278012793"; //网前产品的最高父类

    //ic_content表的字段
    var $ic_url = "";
    var $ic_url_title = "New Information";
    var $ic_type = "";
    var $ic_title = "";
    var $ic_content = "";
    var $ic_summary = "";
    var $ic_seo_title = "";
    var $ic_seo_description = "";
    var $ic_seo_keywords = "";
    var $ic_show_bread_crumbs = 0;
    var $ic_status = 0;
    var $ic_template = "";
    var $ic_photo = "";
    var $ic_photo_width = 0;
    var $ic_photo_height = 0;
    var $ic_recommend_tours = "";
    var $ic_recommend_packages = "";
    var $ic_ht_area_id = 0;
    var $ic_ht_area_type = "";
    var $ic_ht_product_id = 0;
    var $ic_ht_product_type = "";
    var $ic_author = "";

    /**
     * @description: 添加一条信息平台信息
     * @param string $PAG_Code 翰特产品的编码
     * @return: 
     * @Date Changed: 
     */
    public function addInfo($is_parent_id, $PAG_Code = "")
    {

        if ($is_parent_id == $this->is_topId) {
            //这个是城市级别的数据添加

        } else {
            //产品添加 
        }

        //添加.
        $this->IContent_model->Add(
            $this->ic_url,
            $this->ic_url_title,
            $this->ic_type,
            $this->ic_title,
            $this->ic_content,
            $this->ic_summary,
            $this->ic_seo_title,
            $this->ic_seo_description,
            $this->ic_seo_keywords,
            $this->ic_show_bread_crumbs,
            $this->ic_status,
            $this->ic_template,
            $this->ic_photo,
            $this->ic_photo_width,
            $this->ic_photo_height,
            $this->ic_recommend_tours,
            $this->ic_recommend_packages,
            $this->ic_ht_area_id,
            $this->ic_ht_area_type,
            $this->ic_ht_product_id,
            $this->ic_ht_product_type,
            $this->ic_author
        );
        $infocontent = $this->IContent_model->get_ic_contents($this->IContent_model->insert_id);
        if (!empty($infocontent) && $this->IStructures_model->Add($is_parent_id, $this->IContent_model->insert_id)) {
            $is_id = $this->IStructures_model->insert_id;
            $InfoStructures = $this->IStructures_model->Detail($is_id);
            $InfoStructures->is_id = $is_id;
            $InfoStructures->ic_id = $infocontent->ic_id;
            $data[] = array('name' => 'ok', 'value' => $InfoStructures);
        } else {
            $data[] = array('name' => 'no', 'value' => 'form_info_error');
        }
        return json_encode($data);
    }

    /**---------Meta表的操作----------- */
    function addMeta($im_ic_id, $im_key, $im_value)
    {
        $sql = "INSERT INTO infoMetas \n"
            . "  ( \n"
            . "	im_ic_id, im_key, im_value \n"
            . "  ) \n"
            . "VALUES \n"
            . "  (  \n"
            . "	?, ?, N? \n"
            . "  )";
        return $this->HT->query($sql, array($im_ic_id, $im_key, (string) $im_value));
    }


    /**----------翰特入库--------------- */
    var $pag_sn;
    var $PAG_CII_SN = 0;
    var $PAG_Code = "";
    var $PAG_Type = "35004";
    var $PAG_Scheme = "1,2,3,4,5,6,7";
    var $PAG_Title = "";
    var $PAG_DEI_SN = "34";
    var $PAG_PPI_SN = 0; //存放activityid

    var $PAG2_LGC = 1;
    var $PAG2_Name = "";
    var $PAG2_Title = "";


    /**
     * @description: 添加产品信息到翰特
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function AddProductToHT()
    {
        $sql = "
                INSERT INTO [BIZ_PackageInfo]
                ([PAG_CII_SN]
                ,[PAG_Code]
                ,[PAG_Type]
                ,[PAG_Scheme]
                ,[CreatTime]
                ,[PAG_Title]
                ,[PAG_DEI_SN]
                ,[PAG_PPI_SN]
                )
                VALUES
                ( ?,?,?,?,GETDATE(),?,?,?) 
                ";

        $query = $this->HT229Write->query($sql, array(
            $this->PAG_CII_SN,
            $this->PAG_Code,
            $this->PAG_Type,
            $this->PAG_Scheme,
            $this->PAG_Title,
            $this->PAG_DEI_SN,
            $this->PAG_PPI_SN
        ));
        $this->pag_sn = $this->HT229Write->query("select max(pag_sn) as pag_sn from BIZ_PackageInfo")->row("pag_sn");

        //插入语种表


        $sql2 = "
                INSERT INTO [BIZ_PackageInfo2]
                ([PAG2_PAG_SN]
                ,[PAG2_LGC]
                ,[PAG2_Name]
                ,[PAG2_Title]
                        )
                VALUES
                        (?,?,?,?)
                ";

        //录入中，英两个语种
        for ($i = 1; $i < 3; $i++) {
            $this->HT229Write->query($sql2, array(
                $this->pag_sn,
                $i,
                $this->PAG2_Name,
                $this->PAG2_Title
            ));
        }

        return $this->pag_sn;
    }

    /**
     * @description: 导入价格到翰特
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function AddPriceToHT()
    {
        $sql = "INSERT INTO [BIZ_PackagePrice]
        ([PKP_PAG_SN]
        ,[PKP_VEI_SN]
        ,[PKP_ARI_SN]
        ,[PKP_AdultPrice]
        ,[PKP_ChildPrice]
        ,[PKP_InfantPrice]
        ,[PKP_AdultNetPrice]
        ,[PKP_ChildNetPrice]
        ,[PKP_InfantNetPrice]
        ,[PKP_AdultSpecialPrice]
        ,[PKP_ChildSpecialPrice]
        ,[PKP_InfantSpecialPrice]
        ,[PKP_PriceGrade]
        ,[PKP_PersonStart]
        ,[PKP_PersonStop]
        ,[PKP_ValidDate]
        ,[PKP_InvalidDate]
        ,[LastEditTime]
        ,[LastEditor]
        ,[Checked]
        ,[CheckOperator]
        ,[CheckDate]
        ,[PKP_CustomPrice]
        ,[Caclrenshu]
        ,[CaclAssignDate]
        ,[PKP_AdultCost]
        ,[PKP_ChildCost]
        ,[PKP_BabyCost]
        ,[PKP_PriceType]
        ,[PKP_ChildRate]
        ,[PKP_BabyRate]
        ,[PKP_Currency]
        ,[PKP_RoomDif]
        ,[PKP_PAGS_SN])
  VALUES
        (
        '{$this->PKP_PAG_SN}'
        ,1343
        ,1
        ,'{$this->PKP_AdultPrice}'
        ,'{$this->PKP_ChildPrice}'
        ,'{$this->PKP_InfantPrice}'
        ,'{$this->PKP_AdultNetPrice}'
        ,'{$this->PKP_ChildNetPrice}'
        ,'{$this->PKP_InfantNetPrice}'
        ,0
        ,0
        ,0
        ,1
        ,'{$this->PKP_PersonStart}'
        ,'{$this->PKP_PersonStop}'
        ,'{$this->PKP_ValidDate}'
        ,'{$this->PKP_InvalidDate}'
        ,getdate()
        ,0
        ,2
        ,0
        ,getdate()
        ,2
        ,1
        ,getdate()
        ,0
        ,0
        ,0
        ,0
        ,1.000
        ,1.000
        ,'USD'
        ,0
        ,0)";

        return $this->HT229Write->query($sql);
    }


    /**
     * @description: 判断翰特是否已经存在
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function checkExitHT($PAG_Code)
    {
       // $sql = "select top 1 * from BIZ_PackageInfo where PAG_Code = ? and isnull(DeleteFlag,0)<>1   ";
        $sql = "select top 1 * from BIZ_PackageInfo where PAG_Code = ?  "; //删除的也判断
        $query = $this->HT229Write->query($sql, array($PAG_Code));
        if ($query->num_rows() > 0) {
            $result = true;
        } else {
            $result = false;
        }

        return $result;
    }

    /**
     * @description: 根据编号，获取线路的详细信息
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function getToursDetails($PAG_Code)
    {
        $sql = " SELECT top 1 P1.PAG_ExtendType, P1.PAG_NeedTime,p2.PAG2_Name,P1.PAG_SN,p2.PAG2_Attraction,
        P1.PAG_Code,P1.PAG_Title, CItyInfo2.CII2_Name
       ,P1.PAG_Type 
       ,PAG_Scheme 
       ,PAG_GuideLan 
       ,PAG2_TimeDetail 
       ,p1.PAG_SourceType
    FROM dbo.BIZ_PackageInfo P1 INNER JOIN
         dbo.BIZ_PackageInfo2 p2 ON P1.PAG_SN = p2.PAG2_PAG_SN INNER JOIN
         dbo.CItyInfo2 ON P1.PAG_CII_SN = dbo.CItyInfo2.CII2_CII_SN AND 
          dbo.CItyInfo2.CII2_LGC=1 
   WHERE (p1.pag_dei_sn=34) AND
         (p2.PAG2_LGC = 1)  
         AND (isnull(P1.DeleteFlag,0)<>1) 
       AND  (p1.PAG_Code = ?) ";

        // AND (p2.PAG2_Check = 2) 
        // AND (isnull(P1.DeleteFlag,0) <>1) ";
        $query = $this->HT229Write->query($sql, array($PAG_Code));
        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return null;
        }
    }


    /**
     * @description: 判断是否有价格
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function checkPrice($PagSn){
        $sql = "select * from BIZ_PackagePrice
        where PKP_PAG_SN = ? ";
        $qurey = $this->HT229Write->query($sql,array($PagSn));
        if ($qurey->num_rows()>0){
            return true;
        }else{
            return false;
        }
    }

    /** CHT 那边的操作 */
    function getChtTours($strcity)
    {
        $sql = "select (select ic_url_title from infoContents inner join infoStructures on is_ic_id=ic_id where is_id = tbs.is_parent_id) as city
        ,* from infoContents tbc
        inner join infoStructures tbs on tbs.is_ic_id=tbc.ic_id
        where ic_status = 1 
        and  is_parent_id in (
            select is_id from infoStructures
            inner join infoContents on is_ic_id=ic_id
            where 1=1
            and ic_url in (" . $strcity . ") 
            and is_sitecode='cht'
            
        )
        ";
        $query = $this->HT->query($sql);
        return $query->result();
    }

    /**
     * @description: 对应信息的meta
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function getChtToursMeta($ic_id)
    {
        $sql = "select * from infoMetas 
        where im_ic_id=? and im_key<>'AMP' and im_key<>'AMP_STATUS' and im_key<>'meta_construction_code' and im_key<>'meta_news_createdate'";
        $qurey = $this->HT->query($sql, array($ic_id));
        return $qurey->result();
    }


    /**------其它一些公用函数--- */

    /**
     * @description: 抓取页面程序
     * @param string $url 抓取地址
     * @param string $data 传递的参数
     * @return: 
     * @Date Changed: 
     */
    function getCrulData($url, $data = '', $method = 'GET')
    {
        $curl = curl_init(); // 启动一个CURL会话  
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址  
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查  
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在  
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器  
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转  
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer  
        if ($method == 'POST' && !empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求  
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
            curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 40); // 设置超时限制防止死循环  
        curl_setopt($curl, CURLOPT_TIMEOUT_MS, 40000); // 设置超时限制防止死循环  
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容  
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回  
        $tmpInfo = curl_exec($curl); // 执行操作  
        $errno = curl_errno($curl);
        if ($errno !== 0) {
            return false;
            echo $errno . curl_error($curl); //记录错误日志
        }
        curl_close($curl); //关闭CURL会话  
        return $tmpInfo; //返回数据
    }

    /**
     * @description: 过滤掉特殊字符
     * @param {type} 
     * @return: 
     * @Date Changed: 
     */
    function match_chinese($chars, $encoding = 'utf8')
    {
        $pattern = ($encoding == 'utf8') ? '/[\x{4e00}-\x{9fa5}a-zA-Z0-9]/u' : '/[\x80-\xFF]/';
        preg_match_all($pattern, $chars, $result);
        return join('', $result[0]);
    }
}

/* End of file TpBokun_model.php */
