<?php
/**
 * Created by PhpStorm.
 * User: stanley-king
 * Date: 15/11/2
 * Time: 下午2:59
 */

class ModelOperator
{
    private $mod_goods_tmp;
    private $mod_spec_ex;
    private $mod_spec;
    private $mod_spec_value;
    private $mod_good_class;
    private $mod_item_props;
    private $mod_item_prop_values;
    private $mod_type;
    private $mod_type_spec;
    private $mod_spvid_tvid; //spec value id => tmall props vid

    private $mod_attribute;
    private $mod_attr_tcpid;
    private $mod_attribute_value;

    public function __construct()
    {
        $this->mod_goods_tmp = Model('goods_tmp');
        $this->mod_spec_ex = Model('spec_ex');
        $this->mod_spec = Model('spec');
        $this->mod_good_class = Model('goods_class');
        $this->mod_item_props = Model('item_props');
        $this->mod_item_prop_values = Model('item_prop_values');
        $this->mod_spec_value = Model('spec_value');

        $this->mod_type = Model('type');
        $this->mod_type_spec = Model('type_spec');
        $this->mod_spvid_tvid = Model('spvid_tvid');

        $this->mod_attribute = Model('attribute');
        $this->mod_attr_tcpid = Model('attr_tcpid');
        $this->mod_attribute_value = Model('attribute_value');
    }

    public function __call($method,$args)
    {
        //$num_iid = $args[0];
        $body = &$args[1];
        $response = json_decode($body, true);

        $methods = array('spec');
        if(in_array(strtolower($method),$methods) == false) {
            return;
        }
        if($method == 'spec')
        {
            $item = &$response['item_get_response']['item'];
            if($item['approve_status'] != 'onsale') {
                return;
            }

            $cid = $item['cid'];
            $num_iid = $item['num_iid'];
            $title = $item['title'];

            $skus = &$item['skus'];
            foreach($skus as $skuex)
            {
                foreach($skuex as $sku) {
                    $val = array();
                    $val['cid'] = $cid;
                    $val['num_iid'] = $num_iid;
                    $val['sp_name'] = $sku['properties_name'];
                    $val['sku_id'] = $sku['sku_id'];
                    $val['outer_id'] = $sku['outer_id'];
                    $props = $this->parse_props($sku['properties']);
                    $val['props'] = empty($props) ? "" : $props[0];
                    $val['props_val'] = $sku['properties_name'];
                    $val['title'] = $title;
                    $val['body'] = $body;

                    $this->mod_spec_ex->insert($val);
                }
            }
            //把数据添加到商品临时表里面
            $this->mod_goods_tmp->insert(array("num_iid" => $num_iid,'body' => $body,'cid' => $cid,'product_id' =>$item['product_id'],'title' => $title));
        }
    }

    function parse_props($props)
    {
        $data = preg_split("/[:]+/", $props);
        $ret = array();

        $count = count($data);
        for ($i = 0; $i < $count; $i += 2) {
            array_push($ret, $data[$i]);
        }
        return $ret;
    }

    //根据天猫的商品规格，对应生成规格，并做好分类，类型，规格的映射关系
    public function genspec()
    {
        $datas = $this->mod_spec_ex->group('props')->order('props')->limit(false)->select(); //获取所有独立的规格

        $pids = array();
        foreach($datas as $item) {
            $cid = $item['cid'];
            $pid = $item['props'];
            $spec_name = $this->get_spec_name($cid, $pid);

            //向数据库中添加spec
            $val = array('sp_id' => $pid, 'sp_name' => $spec_name);
            $this->mod_spec->insert($val);
            array_push($pids,$pid);
        }

        $this->add_spec_val(); //添加规格值，由于规格值是按照分类走的
        $this->add_type($pids); //建立类型，以及 规格与类型 的关系
    }

    private function add_type($pids)
    {
        //通过分类直接建立类型
        $items = $this->mod_spec_ex->field('cid')->group('cid')->limit(false)->select();
        foreach($items as $item) {
            $cid = $item['cid']; // $cid => $typeid 以分类建立类型
            $cnmae = $this->get_class_name($cid);
            $this->mod_type->insert(array("type_id" => $cid, "type_name" => $cnmae));
            $this->mod_good_class->where(array("gc_id" => $cid))->update(array("type_id" => $cid, "type_name" => $cnmae));
        }

        foreach ($pids as $pid)
        {
            //按照分类建立类型
            $specexs = $this->mod_spec_ex->group('cid')->where(array('props' => $pid))->limit(false)->select();
            foreach($specexs as $specex) {
                $cid = $specex['cid']; // $cid => $typeid 以分类建立类型
                $this->mod_type_spec->insert(array("type_id" => $cid,"sp_id" => $pid));
            }
        }
    }

    private function add_spec_val()
    {
        $specex = $this->mod_spec_ex->field('cid,props')->group('cid,props')->limit(false)->select();
        foreach ($specex as $sp) {
            $cid = $sp["cid"];
            $pid = $sp["props"];
            if($cid == 50013794 && $pid ==1627207) {
                $x = 100;
            }
            $items = $this->get_prop_values($cid,$pid);
            foreach($items as $item) {
                $spec_val = array();
                $spec_val['sp_id'] = $pid;
                //$spec_val['sp_value_id'] = $item['vid']; //此处不能赋值，因为sp_value_id 是自索引的
                $spec_val['sp_value_name'] = $item['name'];
                $spec_val['store_id'] = fetch_config::store_id;
                $spec_val['sp_value_color'] = '#ddd9c3';
                $spec_val['gc_id'] = $cid;
                $spec_val['sp_value_sort'] = 0;

                $tm_vid = $item['vid'];
                $specval_id = $this->mod_spec_value->insert($spec_val);
                if($specval_id) {
                    $this->mod_spvid_tvid->insert(array('spvid' => $specval_id,'tpvid' => $tm_vid));
                }
            }
        }
    }

    private function get_class_name($cid)
    {
        $item = $this->mod_good_class->where(array('gc_id' => $cid))->limit(false)->select();
        if(empty($item)) {
            return NULL;
        } else {
            return $item[0]['gc_name'];
        }
    }

    //根据cid 和 pid 取到规格名称。
    private function get_spec_name($cid,$pid)
    {
        $item = $this->mod_item_props->where(array('cid' => $cid,'pid' => $pid))->limit(false)->select();
        if(empty($item)) {
            return NULL;
        } else {
            return $item[0]['name'];
        }
    }

    private function get_prop_values($cid,$pid)
    {
        $items = $this->mod_item_prop_values->where(array('cid' => $cid,'pid' => $pid))->limit(false)->select();
        return $items;
    }

    private function get_expids()
    {
        $items = $this->mod_spec->field('sp_id')->group('sp_id')->limit(false)->select();

        $expids = array();
        foreach($items as $item) {
            array_push($expids,$item['sp_id']);
        }
        return $expids;
    }

    private function get_cids()
    {
        $items = $this->mod_spec_ex->group('cid')->order('cid')->limit(false)->select();

        $cids = array();
        foreach ($items as $item) {
            array_push($cids,$item['cid']);
        }

        return $cids;
    }

    private function get_attrid($cid,$pid)
    {
        $item = $this->mod_attr_tcpid->where(array("cid" => $cid,"pid" => $pid))->select();
        return $item[0]['attr_id'];
    }

    //需要从天猫的数据表里面排除掉 规格 ＝》 从而得到属性
    public function add_attribute()
    {
        $expids = $this->get_expids();
        $cids = $this->get_cids();

        foreach($cids as $cid)
        {
            $items =$this->mod_item_props->where(array('cid' => $cid))->select();

            $pids = array();
            foreach($items as $item) {
                $pid = $item['pid'];
                if(in_array($pid,$expids)) continue;

                array_push($pids,$pid);

                $name = $item['name'];
                $multi = strtolower($item['multi']) == 'true' ? true : false;
                $attr_multi = $multi ? "TRUE" : "FALSE";

                $attrid = $this->mod_attribute->table('attribute')->insert(array( "attr_name" => $name,"type_id" => $cid,"attr_multi" => $attr_multi,"attr_show" => 1));


                if($attrid) { // 建立shopnc attribute id 与 天猫数据 pid ＋ cid 的对应关系
                    $this->mod_attr_tcpid->insert(array("attr_id" => $attrid, "cid" => $cid, "pid" => $pid));
                } else {
                    // add log...
                }
            }

            foreach($pids as $pid)
            {
                $tm_valus = $this->mod_item_prop_values->where(array('pid' => $pid,'cid'=>$cid))->select();

                foreach($tm_valus as $val)
                {
                    $type_id = $cid;
                    $attrid = $this->get_attrid($cid,$pid);
                    $attr_value_name = $val['name'];
                    $vid = $val['vid'];

                    $attr_vid = $this->mod_attribute_value->insert(array("attr_id" => $attrid,"type_id" => $type_id, "attr_value_name" => $attr_value_name));
                    if($attr_vid) {
                        $this->mod_spvid_tvid->insert(array('spvid' =>$attr_vid,"tpvid" => $vid));
                    } else {
                        throw(new Exception("cannot add attribute value."));
                    }
                }
            }
        }
    }
}