<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/1/21
 * Time: 下午3:34
 */


class body_filder
{
    private $goods_common;
    static $save_path = BASE_DATA_PATH . '/upload/detail';
    static $down_path = BASE_DATA_PATH . '/Download/detail';

    //static $req_path = 'http://p.lrlz.com/data/upload/detail/';
    static $req_path = 'http://localhost/data/upload/detail/';

    public function __construct()
    {
        $this->goods_common = Model('goods_common');
    }

    private function filter_gif($val)
    {
//        $style = '/\s+style\s*=\s*\"{1}[^\"]*\"{1}/i';
//        $val = preg_replace($style,'',$val);

        $gif = '/<img\s+[^>]*spaceball.gif\"[^>]*>/i';
        $val = preg_replace($gif,'',$val);

        return $val;
    }

    private function download($url,$path)
    {
        $info = pathinfo($url);

        if(!file_exists($path)) {
            $pic_url = $info['dirname'] . '/' . urlencode($info['basename']);
            exec("wget -O $path $pic_url");
        }

        if(file_exists($path))
        {
            if(filesize($path) > 0) {
                return true;
            } else {
                unlink($path);
                return false;
            }
        } else {
            return false;
        }
    }


    //
    private function filterex($val,$commid)
    {
        $style = '/\s*<img\s*[^>]*src\s*=\s*\"([^>\"]*)\"\s*[^>]*>/i';
        $val = preg_match_all($style,$val,$match);
        if(!empty($val) && $val > 0)
        {
            $html = '';
            $num = 1;
            foreach($match[1] as $url)
            {
                $info = pathinfo($url);
                if(empty($info['extension'])) continue;

                $name = md5($url) . '.' . $info['extension'];
                $path = self::$down_path . '/' . $name;

                if(file_exists($path) || $this->download($url,$path))
                {
                    $name = "{$commid}-{$num}.{$info['extension']}";
                    $newpath = self::$save_path . "/{$name}";

                    if(file_exists($newpath)) {
                        unlink($newpath);
                    }
                    copy($path,$newpath);

                    ++$num;
                    $html .= "<img src=\"" . self::$req_path . "{$name}\">";
                }
            }

            return $html;
        } else {
            return false;
        }
    }

    private function filter_table($val,$commid)
    {
        $style = '/\s*<img\s*[^>]*src\s*=\s*\"([^>\"]*)\"\s*[^>]*>/i';
        $val = preg_match_all($style,$val,$match);
        if(!empty($val) && $val > 0)
        {
            $imgs = array();

            $num = 1;
            foreach($match[1] as $url)
            {
                $info = pathinfo($url);
                if(empty($info['extension'])) continue;

                $name = md5($url) . '.' . $info['extension'];
                $path = self::$down_path . '/' . $name;

                if(file_exists($path) || $this->download($url,$path))
                {
                    $name = "{$commid}-{$num}.{$info['extension']}";
                    $newpath = self::$save_path . "/{$name}";

                    if(file_exists($newpath)) {
                        unlink($newpath);
                    }
                    copy($path,$newpath);

                    ++$num;
                    array_push($imgs,$name);
                }
            }
            if(isset($imgs)) {
                return $imgs;
            } else {
                return false;
            }
        } else {
            return false;

        }
    }

    public function fillbody()
    {
        $tm_goods = Model('tm_goods');

        $items = $tm_goods->field('num_iid,description')->limit(false)->select();
        foreach($items as $val)
        {
            $num_iid = $val['num_iid'];
            $body = $val['description'];
            $this->goods_common->where(array('num_iid' => $num_iid))->update(array('goods_body' => $body));
        }
    }

    private function img_width($img)
    {
        $path = self::$save_path . '/' . $img;
        $img_info = getimagesize($path);
        if (empty($img_info) || count($img_info) == 0) return 0;

        return $img_info[0];

    }
    private function group($pics,$max_width)
    {
        $ret = array();

        $row = array();
        $width_count = 0;
        foreach($pics as $img)
        {
            $width = $this->img_width($img);
            $width_count += $width;
            if($width_count > $max_width) {
                array_push($ret,$row);
                $row = array();
                array_push($row,$img);
                $width_count = 0;
            }
            else if($width_count == $max_width){
                array_push($row,$img);
                array_push($ret,$row);
                $row = array();
                $width_count = 0;
            } else {
                array_push($row,$img);
            }
        }

        return $ret;
    }

    private function layout($pics)
    {
        $table_start = "<table style=\"width:100%%;\" cellpadding=\"0\" cellspacing=\"0\">";
        $table_end = "</table>";

        //1. 枚举图片
        $max_width = $this->max_width($pics);
        $table = $this->group($pics,$max_width);

        $html = $table_start;;
        foreach($table as $row)
        {
//            if(count($row) == 1) {
//                $name = $row[0];
//                $html .= "<img src=\"" . self::$req_path . "{$name}\">";
//            }
//            else
//            {

                $html .= "<tr>";
                foreach($row as $col) {
                    $tmp = "<img src=\"" . self::$req_path . "{$col}\">";
                    $html .= "<td> {$tmp} </td>";
                }
                $html .= "</tr>";
//            }
        }
        $html .= $table_end;

        return $html;
    }

    public function proc()
    {
        $goods = $this->goods_common->field('goods_commonid,goods_body')->limit(false)->select();
        foreach($goods as $val)
        {
            $body = $val['goods_body'];
            $comm_id = $val['goods_commonid'];
            $body = $this->filter_gif($body);

            $this->filterex($body,$comm_id);

            $imgs = $this->filter_table($body,$comm_id);

            if($imgs == false) continue;
            $body = $this->layout($imgs);

            if(!empty($body)) {
                $this->goods_common->where(array('goods_commonid' => $comm_id))->update(array('goods_body' => $body));
            }
        }
    }

    /**
     * @param $pics
     * @return array
     */
    private function max_width(&$pics)
    {
        $max_width = 0;
        foreach ($pics as &$img)
        {
            $path = self::$save_path . '/' . $img;
            $img_info = getimagesize($path);
            if (empty($img_info) || count($img_info) == 0) {
                continue;
            }

            $max_width = $img_info[0] > $max_width ? $img_info[0] : $max_width;
        }

        return $max_width;
    }
}