<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
 * 个人房源增值套餐model
 */
class Packagez_model extends MY_Model
{
    private $packageTypeArr = array(
        '1' =>'首页推荐',
        '2' =>'优先排序',
        '3' =>'智能刷新',
        '4' =>'立即刷新',
        '5' =>'vr实勘',
        '6' =>'普通刷新'
    );
    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 $type 套餐类型
     * @param string $tbl
     * @return int
     */
    public function getPackageOrderNumByType($type ,$tbl = 'sell')
    {
        $tblArr = array('sell' => 1 ,'rent' => 2);
        $tableId = $tblArr[$tbl];
        $sql = "select count(*) as count from personal_house_orders where pay_status = 0 and order_status = 1 and package_type = {$type} and house_type = $tableId ";
        $data = $this->db_esfhousebak->query($sql)->result_array();
        $countNoPay = $data[0]['count'];
        return $countNoPay;
    }

    /**
     * 已经生效的套餐数量
     * @param $type
     * @param string $tbl
     * @return mixed
     */
    public function  getPackageActiveOrderNumByType($type ,$tbl = 'sell'){
        $tblArr = array('sell' => 1 ,'rent' => 2);
        $time = time();
        $tableId = $tblArr[$tbl];
        $sql = "select count(*) as count from personal_house_promote where `status` = 1 and house_type = $tableId and package_type = {$type} and start_time <= $time and end_time >= $time";
        $data = $this->db_esfhousebak->query($sql)->result_array();
        $countActive = $data[0]['count'];
        return $countActive;
    }

    /**
     * 获取套餐
     */
    public function getPackageByType($tbl,$type){
        $tblArr = array('sell' => 1 ,'rent' => 2);
        $tableId = $tblArr[$tbl];
        $sql = "select * from $this->table where tbl = ". $tableId . ' and package_type = ' . $type;
        $data = $this->db_esfhousebak->query($sql)->result_array();
        return $data;
    }

    /**
     * 获取套餐剩余数量
     * @param $tbl
     * @param $type
     */
    public function getPackageLeftNumByType($tbl,$type){
        $data = $this->getPackageByType($tbl,$type);
        $left = 0;
        if(!$data) return $left;
        $left = $data[0]['package_num'];
        $orderNoPayNum = $this->getPackageOrderNumByType($type,$tbl);

        if($type == 5){
            //wh的实勘数量
            $this->load->model('vr_model');
            $activeNum  = $this->vr_model->getVrApplyNowNum(1,3); //sell 个人房源
        }else{
            $activeNum = $this->getPackageActiveOrderNumByType($type,$tbl);

        }
        return $left - $orderNoPayNum - $activeNum;
    }


    /**
     * 获取房源已购买的套餐
     * @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_esfhouse->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 getHousePackageNew($houseId ,$tbl = 'sell')
    {
        $tblArr = array('sell' => 1 ,'rent' => 2);
        $tableId = $tblArr[$tbl];
        $time = time();
        $sql = "select end_time,start_time,package_type  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(
            'package_types' => array()
        );
        $data = $this->db_esfhouse->query($sql)->result_array();
        if($data){
            $result['data'] = $data;
            $result['leftTime'] = $this->leftTime($data[0]['end_time']);
            foreach($data as $key => $value){
                $result['package_types'][] = $value['package_type'];
            }
        }
        return $result;
    }


    /**
     * @param int $unixEndTime
     * @return string
     */
    private function leftTime($unixEndTime=0)
    {
        if ($unixEndTime <= time()) { // 如果过了活动终止日期
            return '0天0小时';
        }

        // 使用当前日期时间到活动截至日期时间的毫秒数来计算剩余天时分
        $time = $unixEndTime - time();

        $timeStr = '';
        $days = 0;
        if ($time >= 86400) { // 如果大于1天
            $days = (int)($time / 86400);
            $time = $time % 86400; // 计算天后剩余的毫秒数
        }

        //剩下时间大于23小时的 算一天
        if($time >(23*3600)){
            $days++;
            return  $days.'天0小时';
        }else{
            $hours = ceil($time/3600);
            return  $days.'天'.$hours.'小时';
        }
    }


    /**
     * 根据房源获取可购买的套餐详情
     * @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();

        $isLimitGtZero = true;
        if(GB_CITY == 'wh'){
            $isLimitGtZero = $this->getPackageLeftNumByType($tbl,2) > 0;
        }


        //获取该房源已有的套餐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;
                }
            }

            //wh列表推荐限制购买数量
            if($value['package_type'] == 2){
                if(!$isLimitGtZero) continue;
            }

            //wh实勘限制购买数量
            if($value['package_type'] == 5){
                $this->load->model('vr_model');
                $countVr  = $this->vr_model->getVrApplyNowNum(1,3); //sell 个人房源
                $countOrder = $this->getPackageOrderNumByType($value['package_type'],$tbl); //未支付有效订单
                if( $countVr+$countOrder >= $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,'esfhouse');
        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()){
        //读取缓存值验证回调是否已经更新订单成功
        $cacheKey = $this->memkey.'getPersonalHouseOrdersNotifyNum'.'-'.$orderInfo['user_id'].'-'.$orderInfo['id'].'-'.GB_CITY;
        $notifyNum = $this->memcached_class->get( $cacheKey );
        if ( isset( $notifyNum ) && $notifyNum >= 1 ) {//订单状态更新成功，不再继续更新
            return false;
        }

        //更新订单状态
        $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){
            //订单状态更新成功，设置缓存5分钟内不再允许更新
            $this->memcached_class->add( $cacheKey, 1, 300 );

            $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;
            //获取结束时间

            if($orderInfo['package_type'] == 5) {
                $endTime = $time;
            }else{
                $endTime = $time + ($orderInfo['package_days']) * 86400;
            }
            if($orderInfo['package_type'] == 3) {
                $endTime = $endTime + 14400;
            }
            $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;
                //TODO 测试阶段给测试用
                if($orderInfo['house_tel'] == '18851729266' || $orderInfo['user_id'] == '3468379'){
                    $data['package_refresh_num'] = $orderInfo['package_days'] * 8; //原来是乘以6，现在改为8；2018/11/6 by 娄凯
                }else{
                    $data['package_refresh_num'] = $orderInfo['package_days'] * 8; //原来是乘以6，现在改为8；2018/11/6 by 娄凯
                }

            }
            if($orderInfo['package_type'] == 1){
                $data['refresh_num'] = 4;
            } else if($orderInfo['package_type'] == 6){
                $data['refresh_num'] = $orderInfo['refresh_num'];
            }
            $result = $this->createPromote($data);
            //如果是wh实勘
            if($orderInfo['package_type'] == 5 ){
                if(!$result>0) return false;
                $this->load->model('vr_model');
                return $this->vr_model->whServey($orderInfo);
            }

            if($orderInfo['package_type'] != 4){
                //更新房源状态为收费，并且更新房源过期时间

                $housedetail = array();
                if($orderInfo['house_type'] == 2) {
                    $housedetail = $this->house_model->getHouse($orderInfo['house_id']);
                }
                if(!empty($housedetail) && $housedetail['infofrom'] == 1 && in_array($orderInfo['package_type'],array(1,2))){
                    $this->house_model->updatePersonalHouseCharge($orderInfo['house_id'],$orderInfo['package_days']);
                } else {
                    $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){
                        //更新只能刷新次数
                        $h =date('H');
                        if($h>=7 && $h<=21)
                        {
                            $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'] ,4);
                //插入数据到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);
    }

    /**
     * Notes:刷新手动修复
     * User: zhangkg
     */
    public function getHouseOrders(){

        $out_trade_no = array('12018111614362442548664','12018111612390974548644','12018111614392458548667','12018111612393971148645','12018111617110189048693','12018111614462082548668','12018111614565593948671','12018111614384536048666','12018111615075212748673','12018112017042191249137','12018112011375504449087','12018112017053885249138','12018112011360716749086','12018112011453767249088','12018112017063642949139');

        $transactionId_array = array('4200000210201811160252775744','4200000211201811160593996689','4200000215201811168267451607','4200000219201811164094020314','4200000220201811162730849461','4200000223201811163917656804','4200000225201811169395231587','4200000226201811163735592907','4200000233201811163781326525','4200000211201811208423122889','4200000216201811209460886267','4200000221201811201156126427','4200000226201811202635037777','4200000226201811209472854147','4200000234201811208566662331'
        );

        $orders = $this->db_esfhousebak->from('personal_house_orders')->where(array('create_time >'=>1542334609,'pay_status'=>0))->get()->result_array();

        $i=0;
        foreach ($orders as $key=>$value){

            $transactionId = $value['transaction_id'];

            $id = $value['id'];
            $data['status'] = 0;
            $curlData['serviceCode'] = 'pay';
            $curlData['serviceName'] = 'queryOrder';
            $curlData['actId'] = '57';
            $curlData['tradeNo'] = $transactionId;
            $curlData['sign'] = $this->makeSign($curlData);
            $url = 'https://pay.house365.com/house365-pay-web/rest/interface';
            $result = SendDataByCurl($url,$curlData);
            $result = json_decode($result,true);
            if($result){
                $result['status'] = iconv('utf-8','gbk',$result['status']);
            }
            if(!empty($result) && $result['result'] == 'SUCCESS'){
                $tradeNo = $result['tradeNo'];
                $key = array_search($tradeNo,$out_trade_no);

                if($key !== false){
                    $transactionId_wx = $transactionId_array[$key];
                    $newre['tradeNo'] = $transactionId_wx;
                    //支付成功，此时修复数据
                    $this->successOrder($transactionId,$newre);
                    ++$i;
                }else{
                    var_dump($tradeNo);
                }


            }/*else{
                $updateOrderData['pay_status'] = 0;
                $updateOrderData['pay_time'] = '';
                $updateOrderData['order_status'] = 0;
                $updateOrderData['payment_order_id'] = '';
                $this->updateOrder($updateOrderData,array('id' => $id));
                $this->db_esfhouse->where(array('order_id'=>$id))->delete('personal_house_promote');
            }*/
        }
        die('修复成功'.$i);
    }

    public function successOrder($transactionId,$resultpay){
        //获取订单信息
        $orderInfo = $this->getOrderInfoByTransactionId($transactionId);

        //判断订单状态
        /*   if($orderInfo['order_status'] != 1){
               $result['msg'] = 'order close';
               echo json_encode($result);exit;
           }*/
        if($orderInfo['pay_status'] != 0){
            $result['msg'] = 'order paid';
            echo json_encode($result);exit;
        }
        //支付成功后的操作

        $payResult['tradeNo'] = $resultpay['tradeNo'];

        $result = $this->payFinishNew($orderInfo,$payResult);

    }


    public function payFinishNew($orderInfo,$payResult = array()){
        //更新订单状态
        $updateOrderData = array();
        $updateOrderData['pay_status'] = 1;
        $time = time();
        $updateOrderData['pay_time'] = $orderInfo['create_time'];
        $updateOrderData['order_status'] = 1;
        $updateOrderData['payment_order_id'] = $payResult['tradeNo'];
        $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;
            if($orderInfo['package_type'] == 3) {
                $endTime = $endTime + 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'] * 8;
            }
            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'],4);
                //插入数据到job表
                $this->insertOrderJob($orderInfo['id']);
                return true;
            }

        }
        return false;
    }


    /**
     * 获取套餐数量限制
     * @param string $tbl  sell rent
     * @param int $type 套餐类型
     */
    public function getLimitNumGtZero(){
        //暂时就 套餐 2 和 套餐 5   wh限制  以后需要在扩展
        $limit = array(
            2 => array(
                'sell' => true,
                'rent' => true,
            ),
            5 => array(
                'sell' => true,
            )
        );

        if(GB_CITY == 'wh'){
            $limit[2]['sell'] = $this->package_model->getPackageLeftNumByType('sell',2) > 0;
            $limit[2]['rent'] = $this->package_model->getPackageLeftNumByType('rent',2) > 0;
            $limit[5]['sell'] = $this->package_model->getPackageLeftNumByType('sell',5) > 0;
        }
        return $limit;
    }


    /**
     * 批量获取推广时间
     */
    public function getPromoteTime(&$arr){

    }

    /**
     * 远程获取
     * @author zj
     * @date 2020-09-08
     *
     * @param string $t_url url地址
     * @return bool|string
     */
    public function get_api($t_url)
    {
        $ch = curl_init();
        $t_url = $t_url ? $t_url : "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];

        curl_setopt($ch, CURLOPT_URL, $t_url);
        curl_setopt($ch, CURLOPT_REFERER, $t_url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        $str = curl_exec($ch);
        curl_close($ch);
        return $str;
    }
}