<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Tree;

/**
 * 规格管理
 *
 * @icon fa fa-circle-o
 */
class Spec extends Backend
{
    
    /* @var SpecModel $SpecModel */
    private $SpecModel;

    /* @var SpecValueModel $SpecModel */
    private $SpecValueModel;

    public function _initialize()
    {
        parent::_initialize();
        $this->SpecModel = new \app\admin\model\Spec;
        $this->SpecValueModel = new \app\admin\model\SpecValue;
    }

    /**
     * 添加规则组
     */
    public function addSpec($spec_name, $spec_value_name)
    {
        // 判断规格组是否存在
        if (!$specId = $this->SpecModel->getSpecIdByName($spec_name)) {
            // 新增规格组and规则值
            if ($this->SpecModel->add($spec_name)
                && $this->SpecValueModel->add($this->SpecModel['id'], $spec_value_name))
                $this->success('', null, [
                    'spec_id' => (int)$this->SpecModel['id'],
                    'spec_value_id' => (int)$this->SpecValueModel['id'],
                ]);
            $this->error();
        }
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($specId, $spec_value_name)) {
            $this->success('', null, [
                'spec_id' => (int)$specId,
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($specId, $spec_value_name))
            $this->success('', null, [
                'spec_id' => (int)$specId,
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        $this->error();
    }

    /**
     * 添加规格值
     */
    public function addSpecValue($spec_id, $spec_value_name)
    {
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($spec_id, $spec_value_name)) {
            $this->success('', null, [
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($spec_id, $spec_value_name))
            $this->success('', null, [
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        $this->error();
    }
}