<?php
//require_once(dirname(__FILE__) . '/Config.php');
class InsertDao{
    public static function insert_tospur_house($params){
        global $wpdb;
        $houseRes =  $wpdb->insert(Config::TOSPUR_HOUSE_TABLE, $params);
        $houseId = $wpdb->insert_id;
        if(!InsertDao::setHouseNumber($houseId,$params['house_type'],$params['city_id'])){
            return 510;
        }
        if($houseRes){
            return $houseId;
        }else{
            return 500;
        }
    }

    public static function setHouseNumber($houseId,$houseType,$cityId){
        global $wpdb;
        switch($houseType){
            case 0:
                $prefix = "xf";
                break;
            case 1:
                $prefix = "CS";
                break;
            case 2:
                $prefix = "CZ";
                break;
        }
        $house_number = $prefix.str_pad($cityId,4,'0',STR_PAD_LEFT).str_pad($houseId,8,'0',STR_PAD_LEFT);
        return $wpdb->update(Config::TOSPUR_HOUSE_TABLE,
            array(
                'house_number' => $house_number
            ),
            array(
                "id" => $houseId
            )
        );
    }

    public static function insert_tospur_image($params){
        global $wpdb;
        $imgRes = $wpdb->insert(Config::TOSPUR_IMAGE_TABLE, $params);
        $imgId = $wpdb->insert_id;
        if($imgRes){
            return $imgId;
        }else{
            return 501;
        }
    }
    public static function insert_a_district_area($params){
        global $wpdb;
        $districtAreaRes = $wpdb->insert(Config::A_DISTRICT_AREA_TABLE, $params);
        if($districtAreaRes){
            return $districtAreaRes;
        }else{
            return 502;
        }
    }

    public static function insert_a_house_image($params){
        global $wpdb;
        $houseImageRes = $wpdb->insert(Config::A_HOUSE_IMAGE_TABLE, $params);
        if($houseImageRes){
            return $houseImageRes;
        }else{
            return 503;
        }
    }

    public static function  insert_a_house_recommend($params){
        global $wpdb;
        $houseImageRes = $wpdb->insert(Config::A_HOUSE_RECOMMEND_TABLE, $params);
        if($houseImageRes){
            return $houseImageRes;
        }else{
            return 504;
        }
    }

    public static function  insert_a_house_user($params){
        global $wpdb;
        $houseUserRes = $wpdb->insert(Config::A_HOUSE_USER_TABLE, $params);
        if($houseUserRes){
            return $houseUserRes;
        }else{
            return 505;
        }
    }

    public static function addMainImage($houseId,$data){
        global $wpdb;
        //图片信息
        $uploadedfile = $_FILES['files'];
        $frontCover = $_POST["frontCover"];
        //主力房源的图片与房子信息关联插入数据库
        if(isset($uploadedfile["name"])){
            foreach($uploadedfile["name"] as $key=> $value) {
                $uploadParam = array(
                    "name" => $uploadedfile["name"][$key],
                    "type" => $uploadedfile["type"][$key],
                    "tmp_name" => $uploadedfile["tmp_name"][$key],
                    "error" => $uploadedfile["error"][$key],
                    "size" => $uploadedfile["size"][$key]
                );
                //因为file提交过来有一个空的数组，所以这里判断在filename不为空的情况下，再做后续操作
                if ($uploadParam["name"] != "") {
                    //上传图片
                    if (!function_exists('wp_handle_upload')) {
                        require_once(ABSPATH . 'wp-admin/includes/file.php');
                    }
                    $overrides = array('test_form' => false);
                    $movefile = wp_handle_upload($uploadParam, $overrides);
                    $str = preg_replace('#^https?://#', '', $movefile["url"]);
                    $length = strpos($str, "/",strpos($str, "/")+1);
                    $url = substr($str,$length);
                    if ($movefile && !isset($movefile['error'])) {
                        $uploadFileName = end(explode("/",$url));
                        //上传成功后将图片信息存入tospur_image表
                        $insert_image_array = array(
                            'name' => $uploadFileName,
                            'path' => $url,
                            'creattime' => date("Y-m-d H:i:s"),
                            'alt' => "",
                            'image_type' =>$data[$key]["type"]
                        );
                        $imagePath = get_home_path().$url;
                        Image::makeImage($uploadFileName,$imagePath);
                        //插入图片表
                        $imgRes = $wpdb->insert('tospur_image', $insert_image_array);
                        if (!$imgRes) {
                            return 501;
                        }

                        //获取插入图片的id
                        $imgid = $wpdb->insert_id;
                        if($_POST["frontCover"] == $key){
                            $frontCover =$imgid;
                        }

                        //房源类型、面积与图片关联表
                        if($data[$key]["mainHouse"] == "0"){
                            $houseTypeArea = array(
                                'house_id' => $houseId,
                                "buildproperty_id" => $data["$key"]["buildProperty"],
                                "house_area" => $data["$key"]["housearea"],
                                "image_id" => $imgid
                            );
                            $houseTypeAreaRes = $wpdb->insert(Config::A_DISTRICT_AREA_TABLE, $houseTypeArea);
                            if (!$houseTypeAreaRes) {
                                return 502;
                            }
                        }
                        //将房源id与图片id储存到关联表中
                        $house_img_array = array(
                            'house_id' => $houseId,
                            'image_id' => $imgid,
                        );
                        $houseImgRes = $wpdb->insert(Config::A_HOUSE_IMAGE_TABLE, $house_img_array);
                        if (!$houseImgRes) {
                            return 503;
                        }
                    } else {
                        return $movefile['error'];
                    }
                }
            }
        }
        $wpdb->update(Config::TOSPUR_HOUSE_TABLE,array("frontCover_id"=>$frontCover),array("id"=>$houseId));
    }

    public static function addRecommend($houseId,$data){
        global $wpdb;
        if(isset($data["recommend"])){
            //插入推荐房源id与添加新房id到关联表a_house_recommend
            foreach($data["recommend"] as $value){
                $a_house_recommendArray = array(
                    "house_id" => $houseId,
                    "recommend_id" =>$value
                );
                $a_house_recommendRes = $wpdb->insert(Config::A_HOUSE_RECOMMEND_TABLE, $a_house_recommendArray);
                if(!$a_house_recommendRes){
                    return 504;
                }
            }
        }
    }

    public static function addRecConsultant($houseId,$data){
        global $wpdb;
        if($data["recConsultant"]){
            //插入推荐置业顾问user_id与新房id到关联表a_house_recommend
            foreach($data["recConsultant"] as $val){
                $a_house_userArray = array(
                    "user_id" => $val,
                    "house_id" => $houseId,
                    "user_type" =>1
                );
                $a_house_userRes = $wpdb->replace(Config::A_HOUSE_USER_TABLE,$a_house_userArray);
                if(!$a_house_userRes){
                    return 505;
                }
            }
        }
    }
    public static function addHouseFeature($houseId,$data){
        global $wpdb;
        if($data["houseFeature"]){
            foreach($data["houseFeature"] as $val){
                $a_house_feature = array(
                    "house_id" => $houseId,
                    "tag_id" =>$val
                );

                $a_house_featureRes = $wpdb->insert(Config::A_HOUSE_TAG_TABLE,$a_house_feature);
                if(!$a_house_featureRes){
                    return 506;
                }
            }
        }
    }


    public static function addHouseTag($tags, $house_id)
    {
        global $wpdb;
        $arr = array('，' => ',');
        $in = explode(',', strtr($tags, $arr));
        //string
        $tags_string = InsertDao::arrayToString($in);
        //房源的标签id数组
        $tags_ids = array();
        //查询存在的标签
        $sql = "select * from ".Config::TOSPUR_TAG_TABLE." where name in " . $tags_string." and type=0";
        $has_tags_result = $wpdb->get_results($sql);
        //排除存在的标签，剩下未有的标签和存在标签id数组
        foreach ($has_tags_result as $key => $value) {
            if (($key = array_search($value->name, $in)) !== false) {
                unset($in[$key]);
            }
            $tags_ids[] = $value->id;
        }
        //添加未有的标签
        foreach ($in as $value) {
            $insert = $wpdb->insert(
                'tospur_tag',
                array(
                    'name' => $value
                )
            );
            if($insert){
                $tags_ids[] = $wpdb->insert_id;
            }
        }
        //删除该房源的标签关联后，添加新的标签关联
        $wpdb->query(
            $wpdb->prepare(
                "DELETE FROM a_house_tag
                WHERE tag_id in(select tag_id from (select tag_id,tt.type from a_house_tag as aht
                left JOIN tospur_tag tt on aht.tag_id = tt.id) as a
                where house_id = %d and a.type = 0);", $house_id)
        );
        foreach ($tags_ids as $value) {
            $wpdb->insert(
                'a_house_tag',
                array(
                    'house_id' => $house_id,
                    'tag_id' => $value
                )
            );
        }
    }

    public static function arrayToString($array)
    {
        $string = "(";
        $length = count($array);
        $i = 0;
        foreach ($array as $key => $value) {
            $i++;
            $string .= "'" . $value . "'";
            if ($i != $length) {
                $string .= ",";
            }
        }
        $string .= ")";
        return $string;
    }
}




?>