<?php

require_once(PLUGIN_DIR . 'lib/PHPExcel.php');
require_once(PLUGIN_DIR . 'lib/PHPExcel/IOFactory.php');
require_once(PLUGIN_DIR . 'lib/PHPExcel/Reader/Excel5.php');
set_time_limit(0);
class upload
{
    public static function function_upload()
    {
        $upload = wp_upload_dir();
        $file = $upload['basedir'] . '/' . $_FILES['file']['name'];
        $to = $upload['basedir'] . '/zip/';

        if ($_FILES['file']['name']) {
            @rename($_FILES['file']['tmp_name'], $file);
            WP_Filesystem();
            $unzipfile = unzip_file($file, $to);
            if ($unzipfile) {
                $dir = upload::getDir($to);
                echo '<script>alert("解压文件成功");</script>';
            } else {
                echo '<script>alert("解压文件失败");</script>';
            }
            @unlink($file);
            upload::delDir($to);
        }

        Timber::render('upload.html');
    }

    public static function delDir($dir)
    {
        //先删除目录下的文件
        $dh = opendir($dir);
        while ($file = readdir($dh)) {
            if ($file != "." && $file != "..") {
                $fullpath = $dir . "/" . $file;
                if (!is_dir($fullpath)) {
                    unlink($fullpath);
                } else {
                    upload::delDir($fullpath);
                }
            }
        }
        closedir($dh);
        //删除当前文件夹
        if (rmdir($dir)) {
            return true;
        } else {
            return false;
        }
    }

    public static $houseType;
    public static function searchDir($path, &$data)
    {
        global $wpdb;
        $upload = wp_upload_dir();
        if (is_dir($path)) {
            $dp = dir($path);
            while ($file = $dp->read()) {
                if ($file != '.' && $file != '..') {
                    $string = mb_convert_encoding($file, "UTF-8", "GBK");
                    switch ($string) {
                        case "一手房":
                            upload::$houseType = 0;
                            break;
                        case "二手房":
                            upload::$houseType = 1;
                            break;
                        case "租房":
                            upload::$houseType = 2;
                            break;
                    }
                    $dot_position = strrpos($string, ".");
                    if ($dot_position) {
                        $suffix = substr($string, $dot_position + 1);
                        if ($suffix == 'xls' || $suffix == 'xlsx') {
                            $house_id = upload::excelReader($path, $file, upload::$houseType);
                            if ($house_id) {
                                $images = upload::getDirImage($path);
                                $update_cover_flag = false;
                                foreach ($images as $value) {
                                    $name = substr($value, strrpos($value, "/") + 1);
                                    $image_dot_position = strrpos($name, ".");
                                    $image_prefix = md5(substr($name, 0, $image_dot_position));
                                    $image_suffix = substr($name, $image_dot_position + 1);
                                    $image_name = $house_id . '_' . $image_prefix . '.' . $image_suffix;
                                    $image_path = Date('Y') . '/' . Date('m') . '/' . $image_name;
                                    $destination = $upload['basedir'] . '/' . $image_path;
                                    copy(mb_convert_encoding($value, "GBK", "UTF-8"), $destination);
                                    $insert_image_array = array(
                                        'name' => $image_name,
                                        'path' => '/wp-content/uploads/' . $image_path,
                                        'creattime' => current_time('Y-m-d H:i:s'),
                                        'alt' => "",
                                        'image_type' => 0
                                    );
                                    Image::makeImage($image_name, $destination);
                                    //图片 insert tospur_image表
                                    DBManager::insert(Config::TOSPUR_IMAGE_TABLE, $insert_image_array);
                                    $image_id = $wpdb->insert_id;
                                    //房源id tospur_image表中的图片id insert a_house_image表
                                    DBManager::insert(Config::A_HOUSE_IMAGE_TABLE, array(
                                        'house_id' => $house_id,
                                        'image_id' => $image_id
                                    ));
                                    //第一张image 作为封面图片
                                    if (!$update_cover_flag) {
                                        DBManager::update(Config::TOSPUR_HOUSE_TABLE, array(
                                            'frontCover_id' => $image_id
                                        ), array(
                                            'id' => $house_id
                                        ));
                                        $update_cover_flag = true;
                                    }
                                }
                            }
                        }
                    }
                    upload::searchDir($path . '/' . $file, $data);
                }
            }
            $dp->close();
        }
        if (is_file($path)) {
            $string = mb_convert_encoding($path, "UTF-8", "GBK");
            $data[] = $string;
        }
    }

    public static function getDir($dir)
    {
        $data = array();
        upload::searchDir($dir, $data);
        return $data;
    }

    public static function searchDirImage($path, &$images)
    {
        if (is_dir($path)) {
            $dp = dir($path);
            while ($file = $dp->read()) {
                if ($file != '.' && $file != '..') {
                    upload::searchDirImage($path . '/' . $file, $images);
                }
            }
            $dp->close();
        }

        if (is_file($path)) {
            $string = mb_convert_encoding($path, "UTF-8", "GBK");
            $dot_position = strrpos($string, ".");
            if ($dot_position) {
                $suffix = substr($string, $dot_position + 1);
                if ($suffix == 'jpg' || $suffix == 'png') {
                    $images[] = $string;
                }
            }
        }
    }

    public static function getDirImage($dir)
    {
        $images = array();
        upload::searchDirImage($dir, $images);
        return $images;
    }

    public static function excelReader($path, $file, $houseType)
    {
        set_time_limit(0);
        $excel_file = $path . '/' . $file;
        //实例化PHPExcel类
        $PHPExcel = new PHPExcel();
        //默认用excel2007读取excel，若格式不对，则用之前的版本进行读取
        $PHPReader = new PHPExcel_Reader_Excel2007();
        if (!$PHPReader->canRead($excel_file)) {
            $PHPReader = new PHPExcel_Reader_Excel5();
            if (!$PHPReader->canRead($excel_file)) {
                echo 'no Excel';
                return false;
            }
        }
        //读取Excel文件
        $PHPExcel = $PHPReader->load($excel_file);
        //读取excel文件中的第一个工作表
        $sheet = $PHPExcel->getSheet(0);
        //取得最大的列号
        $allColumn = $sheet->getHighestColumn();
        //取得最大的行号
        $allRow = $sheet->getHighestRow();

        $sheet = $PHPExcel->getActiveSheet();
        $matches = array();
        $age = (preg_match("/\d{4}/", $sheet->getCell('B16')->getValue(), $matches)) ? $matches[0] : null;
        $property_age = (preg_match("/\d+/", $sheet->getCell('B24')->getValue(), $matches)) ? $matches[0] : null;


        $city_id = upload::search_city_id($sheet->getCell('B8')->getValue());
        $district_id = upload::search_district_id($sheet->getCell('B9')->getValue());
        $plate_id = upload::search_plate_id($sheet->getCell('B10')->getValue());
        $room_id = upload::search_room_id($sheet->getCell('B23')->getValue());
        $organization_id = upload::search_organization_id($sheet->getCell('B7')->getValue());

        $data = array(
            'name' => $sheet->getCell('B1')->getValue(),
            'latest_news' => $sheet->getCell('B39')->getValue(),
            'address' => $sheet->getCell('B34')->getValue(),
            'traffic' => $sheet->getCell('B32')->getValue(),
            'periphery' => $sheet->getCell('B33')->getValue(),
            'developer' => $sheet->getCell('B40')->getValue(),
            'check_in_time' => $sheet->getCell('B41')->getValue(),
            'property_age' => $property_age,
            'decoration' => $sheet->getCell('B22')->getValue(),
            'covered_area' => (preg_match("/(\d+)\.(\d+)|(\d+)/", $sheet->getCell('B25')->getValue(), $matches)) ? $matches[0] : 0,
            'volume_rate' => $sheet->getCell('B43')->getValue(),
            'greening_rate' => $sheet->getCell('B42')->getValue(),
            'households' => $sheet->getCell('B44')->getValue(),
            'parking_spaces' => $sheet->getCell('B30')->getValue(),
            'property_management' => $sheet->getCell('B46')->getValue(),
            'overview' => $sheet->getCell('B36')->getValue(),
            'floor' => (preg_match("/\d+/", $sheet->getCell('B13')->getValue(), $matches)) ? $matches[0] : 0,
            'faceto' => $sheet->getCell('B15')->getValue(),
            'age' => $age,
            'matching_facilities' => $sheet->getCell('B35')->getValue(),
            'house_type' => $houseType,
            'status' => 0,
            'city_id' => $city_id,
            'district_id' => $district_id,
            'plate_id' => $plate_id,
            'room_id' => $room_id,
            'organizationId' => $organization_id,
            'community_name' => $sheet->getCell('B11')->getValue(),
            'suite' => $sheet->getCell('B12')->getValue(),
            'buildproperty_id' => $sheet->getCell('B17')->getValue(),
            'owner_name' => $sheet->getCell('B5')->getValue(),
            'owner_phone' => $sheet->getCell('B6')->getValue(),
            'totalFloor' => (preg_match("/\d+/", $sheet->getCell('B14')->getValue(), $matches)) ? $matches[0] : 0,
            'useArea' => (preg_match("/(\d+)\.(\d+)|(\d+)/", $sheet->getCell('B26')->getValue(), $matches)) ? $matches[0] : 0,
            'street' => $sheet->getCell('B31')->getValue(),
            'propertyProof' => $sheet->getCell('B27')->getValue(),
            'roomNum' => $sheet->getCell('B17')->getValue(),
            'livingRoom' => $sheet->getCell('B18')->getValue(),
            'bathRoom' => $sheet->getCell('B19')->getValue(),
            'kitchen' => $sheet->getCell('B20')->getValue(),
            'balcony' => $sheet->getCell('B21')->getValue(),
            'structure' => $sheet->getCell('B28')->getValue(),
            'key' => $sheet->getCell('B29')->getValue(),
            'garage' => $sheet->getCell('B30')->getValue(),
            'entrustDay' => $sheet->getCell('B47')->getValue(),
            'deadLine' => $sheet->getCell('B48')->getValue(),
            'mortgage' => $sheet->getCell('B49')->getValue(),
            'approval' => 1
        );

        $sql = null;
        if ($houseType == 0) {
            $data['average_price'] = (preg_match("/(\d+)\.(\d+)|(\d+)/", $sheet->getCell('B38')->getValue(), $matches)) ? $matches[0] : 0;
            $sql = "select id from " . Config::TOSPUR_HOUSE_TABLE . " where name = '" . $data['name'] . "' and address = '" . $data['address'] . "' and house_type = " . $houseType;
        } else if ($houseType == 1) {
            $data['total_price'] = (preg_match("/(\d+)\.(\d+)|(\d+)/", $sheet->getCell('B3')->getValue(), $matches)) ? $matches[0] : 0;
            $data['average_price'] = (preg_match("/(\d+)\.(\d+)|(\d+)/", $sheet->getCell('B4')->getValue(), $matches)) ? $matches[0] : 0;
            $sql = "select id from " . Config::TOSPUR_HOUSE_TABLE . " where address = '" . $data['address'] . "' and owner_name = '" . $data['owner_name'] . "' and owner_phone = '" . $data['owner_phone'] . "' and house_type = " . $houseType;
        } else if ($houseType == 2) {
            $data['total_price'] = (preg_match("/(\d+)\.(\d+)|(\d+)/", $sheet->getCell('B3')->getValue(), $matches)) ? $matches[0] : 0;
            $data['rent'] = (preg_match("/(\d+)\.(\d+)|(\d+)/", $sheet->getCell('B4')->getValue(), $matches)) ? $matches[0] : 0;
            $sql = "select id from " . Config::TOSPUR_HOUSE_TABLE . " where address = '" . $data['address'] . "' and owner_name = '" . $data['owner_name'] . "' and owner_phone = '" . $data['owner_phone'] . "' and house_type = " . $houseType;
        }
        $res = DBManager::get_var($sql);
        if (!$res) {
            $house_id = InsertDao::insert_tospur_house($data);
            return $house_id;
        }
        return false;
    }

    public static function search_city_id($city_name)
    {
        $city_id = DBManager::get_var('select cityId from dic_city where cityName = "' . $city_name . '"');
        if ($city_id) {
            return $city_id;
        } else {
            return -1;
        }
    }

    public static function search_district_id($district_name)
    {
        $district_id = DBManager::get_var('select districtId from dic_city where districtName = "' . $district_name . '"');
        if ($district_id) {
            return $district_id;
        } else {
            return -1;
        }
    }

    public static function search_plate_id($plate_name)
    {
        $plate_id = DBManager::get_var('select plateId from dic_city where plateName = "' . $plate_name . '"');
        if ($plate_id) {
            return $plate_id;
        } else {
            return -1;
        }
    }

    public static function search_room_id($literal)
    {
        $room_id = DBManager::get_var('select id from dic_room where literal = "' . $literal . '"');
        if ($room_id) {
            return $room_id;
        } else {
            return 0;
        }
    }

    public static function search_organization_id($consultant_name)
    {
        $organization_id = DBManager::get_var('select subsidiaryId from tospur_consultant where name = "' . $consultant_name . '"');
        if ($organization_id) {
            return $organization_id;
        } else {
            return 0;
        }
    }
}

?>