<?php

/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 16/1/9
 * Time: 下午1:35
 */
class skumatcher
{
    private $input_file;
    private $good_file;
    private $err_file;
    private $mod_goods_common;
    private $mod_goods;

    public function __construct($input)
    {
        if(file_exists($input) == false) {
            throw new Exception("no such file {$input}.");
        }

        $this->input_file = new SplFileObject($input);
        $this->input_file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
        $this->good_file = new SplFileObject("./good.csv","a");
        $this->err_file = new SplFileObject("./err.csv","a");

        $this->mod_goods_common = Model('goods_common');
        $this->mod_goods = Model('goods');
    }

    public function proc()
    {
        foreach($this->input_file as $line)
        {
            $this->parase_one($line[0]);
        }
    }

    private function match_item($name)
    {
        $items = $this->mod_goods_common->field('goods_commonid,goods_name')->where(array('goods_name' => $name))->select();
        if(empty($items)) {
            $con['goods_name'] = array('like',"%{$name}%");
            $items = $this->mod_goods_common->field('goods_commonid,goods_name')->where($con)->select();
        }
        if(empty($items)) {
            $len = mb_strlen($name);
            $name_x = mb_substr($name,0,$len / 2);
            $con['goods_name'] = array('like',"%{$name_x}%");
            $items = $this->mod_goods_common->field('goods_commonid,goods_name')->where($con)->select();
        }

        return $items;
    }

    private function parase_one($name)
    {
        $items = $this->match_item($name);

        if(empty($items)) {
            $fields = array($name);
            $this->err_file->fputcsv($fields,',');
            return;
        }
        $goods_commonid = $items[0]['goods_commonid'];
        $goods = $this->mod_goods->field('*')->where(array('goods_commonid' => $goods_commonid))->limit(false)->select();
        if(empty(goods)) {
            $fields = array($name);
            $this->err_file->fputcsv($fields,',');
            return;
        }

        foreach($goods as $val)
        {
            $fields = array($val['goods_name'],$val['goods_serial_tm'],$val['num_iid']);
            $this->good_file->fputcsv($fields,',');
        }
    }
}


$matcher =  new skumatcher('/Users/stanley-king/Desktop/name.csv');
$matcher->proc();

