<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
 * 个人房源增值套餐model
 */
class Package_model extends MY_Model
{
    private $packageTypeArr = array(
        '1' =>'首页推荐',
        '2' =>'优先排序',
        '3' =>'智能刷新',
        '4' =>'立即刷新'
    );
    private $table;
    private $memkey;
    public function __construct()
    {
        parent::__construct();

        $this->memkey = 'package'.GB_CITY;
        $this->table = 'personal_house_package';
    }
    /**
     * 按照规定的格式显示，不足的补0
     * @param int $value 值
     * @param int $length 长度
     * @return string
     */
    private static function formatValue($value, $length)
    {
        return sprintf("%0{$length}d", $value);
    }

    /**
     * 随机产生的订单号后四位数
     * 1-9999
     */
    private static function randValue()
    {
        return rand(1, 9999);
    }

    /**
     * 获取某个产品的交易号
     * @param int $type 产品类型 1代表首页推荐，2代表列表页推荐，3代表智能刷新，4代表普通刷新
     * @return string
     */
    public function getTransactionId($type)
    {
        //防止订单ID与租售宝重复，$type 定义为从50开始
        $type = 50 + $type;
        $formatType = self::formatValue($type, 2);
        //随机数
        $randValue = self::formatValue(self::randValue(), 4);
        //订单号
        return time() . $formatType . $randValue;
    }

    /**
     * 获取套餐详情
     * @param int $id 套餐ID
     * @return array
     */
    public function getDetailById($id)
    {
        $id = intval($id);
        $searchArr['form_name'] = $this->table;
        $searchArr['select'] = array('*');
        $searchArr['where'] = array('id' => $id);
        $searchArr['limit'] = 1;
        $data = $this->get_data($searchArr,'esfhousebak');
        return !empty($data[0]) ? $data[0] : array();
    }

    /**
     * 获取首页套餐的已冻结数量
     * @param int $type 套餐关键字类型
     * @param string $tbl
     * @return int
     */
    public function getPackageNum($type ,$tbl = 'sell')
    {
        $tblArr = array('sell' => 1 ,'rent' => 2);
        $tableId = $tblArr[$tbl];
        $time = time();
        //查询有效的已售订单
        $sql = "select count(*) as count from personal_house_promote where `status` = 1 and house_type = $tableId and package_keyword = $type and start_time <= $time and end_time >= $time";
        $data = $this->db_esfhousebak->query($sql)->result_array();
        $count = $data[0]['count'];
        //查询待支付的订单
        $sql = "select count(*) as count from personal_house_orders where pay_status = 0 and order_status = 1 and package_type = 1 and house_type = $tableId and package_keyword = ".$type;
        $data = $this->db_esfhousebak->query($sql)->result_array();
        $countNoPay = $data[0]['count'];
        return $count + $countNoPay;
    }

    /**
     * 获取房源已购买的套餐
     * @param int $houseId
     * @param string $tbl
     * @return array
     */
    public function getHousePackage($houseId ,$tbl = 'sell')
    {
        $tblArr = array('sell' => 1 ,'rent' => 2);
        $tableId = $tblArr[$tbl];
        $time = time();
        $sql = "select * from personal_house_promote where `status` = 1 and house_type = $tableId and house_id = $houseId  and start_time <= $time and end_time >= $time";
        $result = array();
        $data = $this->db_esfhousebak->query($sql)->result_array();
        foreach($data as $key => $value){
            $result[] = $value['package_type'];
        }
        return $result;
    }


    /**
     * 根据房源获取可购买的套餐详情
     * @param int $houseId
     * @param string $tbl
     * @return array
     */
    public function getPackageByHouseId($houseId,$tbl = 'sell')
    {
        //首先查询tbl下所有套餐
        $tblArr = array('sell' => 1 ,'rent' => 2);
        $tableId = $tblArr[$tbl];
        $searchArr['id'] = $houseId;
        $searchArr['uid'] = $this->user_id;
        $searchArr['infofrom'] = 1;
        $searchArr['esta'] = 1;
        //获取房源信息
        $houseData = $this->house_model->gethousebywhere($searchArr,$tbl,array('id,infotype'),1);
        if(empty($houseData)){
            return array();
        }
        //房源物业类型
        $type = $houseData[0]['infotype'] == 1 ? 1 : 2;
        $sql = "select * from $this->table where tbl = ". $tableId;
        $data = $this->db_esfhousebak->query($sql)->result_array();
        //获取该房源已有的套餐ID
        $housePackage = $this->getHousePackage($houseId,$tbl);
        //定义禁止的套餐数组
        $banHousePackage = array();
        if(!empty($housePackage)){
            foreach($housePackage as $k =>$v){
                if($v == 1 || $v == 2){
                    $banHousePackage[] = 1;
                    $banHousePackage[] = 2;
                }
                if($v == 3){
                    $banHousePackage[] = 3;
                }
            }
        }
        $newData = array();
        foreach($data as $key => $value){
            if(in_array($value['package_type'],$banHousePackage)){
                continue;
            }
            $value['package_desc'] = unserialize($value['package_desc']);
            $value['package_desc'] = !empty($value['package_desc']) ? $value['package_desc'] : array();
            if($value['package_type'] != 4){
                foreach($value['package_desc'] as $k => $v){
                    if(empty($v['property_type']) || $v['property_type'] != $type){
                        unset($value['package_desc'][$k]);
                    }
                }
            }
            if(empty($value['package_desc'])){
                continue;
            }
            //首页推荐需要限制购买数量
            if($value['package_type'] == 1){
                if(empty($value['package_keyword'])){
                    continue;
                }
                $buyCount = $this->getPackageNum($value['package_keyword'],$tbl);
                if($buyCount >= $value['package_num']){
                    continue;
                }
            }
            $newData[] = $value;
        }
        return $newData;
    }
    /**
     * 创建订单
     * @param array $data
     * @return int
     */
    public function createOrder($data = array())
    {
        $this->set_table('personal_house_orders');
        $insert_id = $this->add( $data , 'esfhouse' );
        return intval($insert_id);
    }

    /**
     * 更新订单
     * @param array $data
     * @param array $where
     * @return int
     */
    public function updateOrder($data = array(),$where = array())
    {
        $this->set_table('personal_house_orders');
        $result = $this->save( $where , $data ,'esfhouse' );
        return $result;
    }
    /**
     * 创建订单发票
     * @param array $data
     * @return int
     */
    public function createOrderInvoice($data = array())
    {
        $this->set_table('personal_house_order_invoice');
        $insert_id = $this->add( $data , 'esfhouse' );
        return intval($insert_id);
    }

    /**
     * 根据 orderId 获取发票信息
     * @param int $orderId orderId
     * @return array
     */
    public function getOrderInvoice($orderId)
    {

        $searchArr['form_name'] = 'personal_house_order_invoice';
        $searchArr['select'] = array('*');
        $searchArr['where'] = array('order_id' => $orderId);
        $searchArr['limit'] = 1;
        $data = $this->get_data($searchArr,'esfhousebak');
        return !empty($data[0]) ? $data[0] : array();
    }

    /**
     * 根据 orderId 获取发票信息
     * @param int $userId userId
     * @return array
     */
    public function getOrderInvoiceByUserId($userId)
    {

        $sql = "SELECT a.* FROM personal_house_order_invoice a LEFT JOIN  personal_house_orders b on a.order_id = b.id WHERE b.user_id = ". intval($userId). " AND b.pay_status = 1 ORDER BY a.id desc LIMIT 1";
        $query = $this->db_esfhousebak->query($sql);
        $data = $query->result_array();
        return !empty($data[0]) ? $data[0] : array();
    }
    /**
     * 根据 orderId 获取订单信息
     * @param int $id orderId
     * @return array
     */
    public function getOrderInfoById($id)
    {

        $searchArr['form_name'] = 'personal_house_orders';
        $searchArr['select'] = array('*');
        $searchArr['where'] = array('id' => $id);
        $searchArr['limit'] = 1;
        //此处查询主库，防止同步慢导致的订单错误
        $data = $this->get_data($searchArr,'esfhouse');
        return !empty($data[0]) ? $data[0] : array();
    }

    /**
     * 根据 getOrderInfoByTransactionId 获取订单信息
     * @param int $transactionId
     * @return array
     */
    public function getOrderInfoByTransactionId($transactionId)
    {

        $searchArr['form_name'] = 'personal_house_orders';
        $searchArr['select'] = array('*');
        $searchArr['where'] = array('transaction_id' => $transactionId);
        $searchArr['limit'] = 1;
        $data = $this->get_data($searchArr,'esfhousebak');
        return !empty($data[0]) ? $data[0] : array();
    }

    /**
     * 获取套餐名称
     * @param int $typeId
     * @return string
     */
    public function getPackageTypeName($typeId = 1){
        return $this->packageTypeArr[$typeId];
    }

    /**
     * 签名
     * @param $data
     * @return string
     */
    public function makeSign($data)
    {
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string = $this->toUrlParams($data);
        //签名步骤二：在string后加入KEY
        $string = $string. "&key=".GB_HOUSE365_PAY_KEY;
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 参数格式转换
     * @param $data
     * @return string
     */
    public function toUrlParams($data)
    {
        $buff = "";
        foreach ($data as $k => $v)
        {
            if($k != "sign"  && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 创建房源促销
     * @param array $data
     * @return int
     */
    public function createPromote($data = array())
    {
        $this->set_table('personal_house_promote');
        $insert_id = $this->add( $data , 'esfhouse' );
        return intval($insert_id);
    }

    /**
     * 更新房源促销表数据
     * @param array $data
     * @param array $where
     * @return int
     */
    public function updatePromote($data = array(),$where = array())
    {
        $this->set_table('personal_house_promote');
        $result = $this->save( $where , $data ,'esfhouse' );
        return $result;
    }

    /**
     * 获取推广详情
     * @param int $orderId 订单
     * @return array
     */
    public function getPromoteByOrderId($orderId)
    {
        $orderId = intval($orderId);
        $searchArr['form_name'] = 'personal_house_promote';
        $searchArr['select'] = array('*');
        $searchArr['where'] = array('order_id' => $orderId);
        $searchArr['limit'] = 1;
        $data = $this->get_data($searchArr,'esfhousebak');
        return !empty($data[0]) ? $data[0] : array();
    }

    /**
     * 支付完成更新订单状态
     * @param array $orderInfo
     * @param array $payResult
     * @return bool
     */
    public function payFinish($orderInfo,$payResult = array()){
        //更新订单状态
        $updateOrderData = array();
        $updateOrderData['pay_status'] = 1;
        $time = time();
        $updateOrderData['pay_time'] = $time;
        $updateOrderData['payment_order_id'] = $payResult['transaction_id'];
        $result = $this->updateOrder($updateOrderData,array('id' => $orderInfo['id']));
        if($result){
            $data = array();
            $tableArray = array( 1 => 'sell' , 2 => 'rent');
            $tbl = $tableArray[$orderInfo['house_type']];
            $data['order_id'] = $orderInfo['id'];
            $data['house_type'] = $orderInfo['house_type'];
            $data['house_id'] = $orderInfo['house_id'];
            $data['price'] = $orderInfo['price'];
            $data['package_type'] = $orderInfo['package_type'];
            $data['package_keyword'] = $orderInfo['package_keyword'];
            $data['confirm_time'] = $time;
            $data['status'] = 1;
            //获取结束时间
            $endTime = $time + $orderInfo['package_days'] * 86400;
            $data['start_time'] = $time;
            $data['end_time'] = $endTime;
            $data['order_start_time'] = $time;
            $data['order_end_time'] = $endTime;
            if($orderInfo['package_type'] == 3){
                $data['package_refresh_num'] = $orderInfo['package_days'] * 6;
            }
            if($orderInfo['package_type'] == 1){
                $data['refresh_num'] = 4;
            }
            $result = $this->createPromote($data);
            if($orderInfo['package_type'] != 4){
                //更新房源状态为收费，并且更新房源过期时间
                $this->house_model->updateHouseCharge($orderInfo['house_type'],$orderInfo['house_id']);
                if($result > 0){
                    if($orderInfo['package_type'] == 1){
                        //更新房源刷新次数
                        $this->updateRefreshNum($orderInfo['user_id'],$orderInfo['house_id'], $tbl, 4 , $time , $endTime);
                    }
                    if($orderInfo['package_type'] == 3){
                        //更新只能刷新次数
                        $this->refreshOne($orderInfo);
                    }
                    //插入数据到job表
                    $this->insertOrderJob($orderInfo['id']);
                    return true;
                }
            }else{
                //调用周大师接口
                $result = $this->house_statistic_model->sub_house_refresh( $tbl , $orderInfo['house_id'] , $orderInfo['price'] , $orderInfo['id'] );
                //插入数据到job表
                $this->insertOrderJob($orderInfo['id']);
                return true;
            }

        }
        return false;
    }


    /**
     * 更新房源刷新次数
     * @param int $uid
     * @param int $houseId
     * @param string $tbl
     * @param int $refreshNum
     * @param int $startTime
     * @param int $endTime
     * @return bool
     */
    private function updateRefreshNum($uid = 0,$houseId = 0 , $tbl = 'sell' , $refreshNum = 4 , $startTime = 0 , $endTime = 0){
        //查询是否刷新次数表是否存在相关数据
        $where['uid'] = $uid;
        $where['rowid'] = $houseId;
        $where['tbl'] = $tbl;
        $where['flag'] = 2;
        $where['cityname'] = GB_CITY;
        $searchData['form_name'] = 'personal_refresh';
        $searchData['where'] = $where;
        $searchData['select'] = array('id,refresh_num');
        $refreshData = $this->get_data($searchData,'esfbak');
        if(!empty($refreshData[0])){
            //更新数据
            $updateData = array();
            //判断之前的刷新次数是否有效
            if($refreshData[0]['end_time'] < $startTime || $refreshData[0]['esta'] != 1){
                $updateData['refresh_num'] = $refreshNum;
            }else{
                $updateData['refresh_num'] = $refreshData[0]['refresh_num'] + $refreshNum;
            }
            $updateData['begin_time'] = $startTime;
            $updateData['end_time'] = $endTime;
            $updateData['creat_time'] = $startTime;
            $updateData['esta'] = 1;
            $this->updatePersonalRefresh($updateData,array('id' => $refreshData[0]['id']));
        }else{
            $insertData = array();
            $insertData['uid'] = $uid;
            $insertData['tbl'] = $tbl;
            $insertData['rowid'] = $houseId;
            $insertData['refresh_num'] = $refreshNum;
            $insertData['cityname'] = GB_CITY;
            $insertData['begin_time'] = $startTime;
            $insertData['end_time'] = $endTime;
            $insertData['creat_time'] = $startTime;
            $insertData['flag'] = 2;
            $insertData['esta'] = 1;
            $this->createPersonalRefresh($insertData);
        }
        return true;
    }

    /**
     * 创建个人刷新次数表数据
     * @param array $data
     * @return int
     */
    private function createPersonalRefresh($data = array())
    {
        $this->set_table('personal_refresh');
        $insert_id = $this->add( $data , 'esf' );
        return intval($insert_id);
    }

    /**
     * 更新个人刷新次数表数据
     * @param array $data
     * @param array $where
     * @return int
     */
    private function updatePersonalRefresh($data = array(),$where = array())
    {
        $this->set_table('personal_refresh');
        $result = $this->save( $where , $data ,'esf' );
        return $result;
    }

    /**
     * 订单支付成功将数据插入job同步合同信息
     * @param $orderId 订单ID
     * @return int
     */
    private function insertOrderJob($orderId){
        $data['order_id'] = $orderId;
        $this->set_table('personal_house_order_job');
        $insert_id = $this->add( $data , 'esfhouse' );
        return intval($insert_id);
    }

    public function getInvoiceByContractNo($contractNo){

        $sql = 'select a.contract_no,a.transaction_id,b.* from personal_house_orders a left join personal_house_order_invoice b on a.id = b.order_id where b.`status` = 1 and a.contract_no in (' . $contractNo . ')';
        $data = $this->db_esfhousebak->query($sql)->result_array();
        return !empty($data) ? $data : array();
    }

    public function refreshOne($orderInfo)
    {
        $order_id          =$orderInfo['id'];
        $sql_promote       ="select * from personal_house_promote where order_id=$order_id  order by id desc limit 1";
        $data_promote	   =$this->db_esfhouse->query($sql_promote);
        $data_promote_arr  =$data_promote->result_array();

        $promote_id        =$data_promote_arr['0']['id'];
        $price             =$data_promote_arr['0']['price'];
        $package_type      =$data_promote_arr['0']['package_type'];
        $tbl               =$data_promote_arr['0']['house_type'];
        $house_id          =$data_promote_arr['0']['house_id'];
        $ctime             =time();

        $sql = "INSERT INTO personal_house_increment (promote_id,price,order_id,package_type,tbl,rowid,ctime) values ('$promote_id','$price','$order_id','$package_type','$tbl','$house_id','$ctime')";

        $this->db_esfhouse->query($sql);

        if($tbl=='1' || $tbl=='sell')
        {
            $tableName='sell';
        }
        else
        {
            $tableName='rent';
        }
        $sql = "UPDATE $tableName SET updatetime=". time() ." WHERE id = $house_id";
        $this->db_esfhouse->query($sql);

        //2018.5.23增加，往操作日志表加一条记录
        $city = GB_CITY;
        $sql = "select user_id from personal_house_orders where id =".$order_id;
        $where['id'] = $order_id;
        $searchData['form_name'] = 'personal_house_orders';
        $searchData['where'] = $where;
        $searchData['select'] = array('user_id');
        $uidinfo = $this->get_data($searchData,'esfbak');
        $uid = $uidinfo[0]['uid'];
        $tbl = $tableName;
        $rowid = $house_id;
        $type = 7; //7代表智能刷新套餐下自动刷新；8代表智能刷新套餐下用户手动刷新
        $datetime = date('Y-m-d H:i:s',time());
        $host = gethostname();
        $ip = gethostbyname($host);
        $device = 1; //pc
        $sql = "insert into log_house_operate (city,uid,tbl,rowid,type,datetime,ip,device) values ('$city','$uid','$tbl','$rowid','$type','$datetime','$ip','$device')";
        $this->db_esfhouse->query($sql);


    }
}