<?php
/**
 * @link      http://www.u-bo.com
 * @copyright 南京友博网络科技有限公司 
 * @license   http://www.u-bo.com/license/
 */

namespace qcbase\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query as query;
use yii\helpers\Url;
use common\components\Tree;
use common\components\Tool;
use common\models\User;

/**
 * This is the model class for table "{{%project_category}}".
 * 
 * 项目类别表 
 *
 * @property integer $cat_id  (项目类别id)
 * @property string $name  (项目分类名称)
 * @property integer $parent_id  (父级id)
 * @property string $parent_ids  (父级所有类别项目id)
 * @property string $child_ids  (所有子项目类别id)
 * @property text $remark  (备注)
 * @property smallint $status  (状态  1：启用 0：禁用  99:逻辑删除 默认启用)
 * @property integer $sort  (排序 默认为0)
 * @property integer $create_time  (创建时间)
 * @property integer $update_time  (更新时间)
 * @property string $ip  (创建人ip)
 * @property integer $user_id  (创建人id)
 *
 * @author xiaobai http://blog.u-bo.com
 * @since 0.1
 */
class ProjectCategory extends ActiveRecord
{   
    public $category = [];//分类
    const STATUS_ENABLE = 1;//启用
    const STATUS_DISABLE = 0;//禁用
    
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%project_category}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'parent_id', 'remark', 'sort',], 'required'],
            [['parent_id', 'status', 'sort',], 'integer'],
            [['remark'], 'string'],
            [['name'], 'string', 'max' => 100],
            [['parent_ids', 'child_ids'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'cat_id' => 'ID',
            'name' => '项目分类名称',
            'parent_id' => '父级id',
            'parent_ids' => '父级所有id集',
            'child_ids' => '子集所有id集',
            'remark' => '备注',
            'status' => '状态',
            'sort' => '排序',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'ip' => 'ip地址',
            'user_id' => '用户id',
        ];
    }
    
    /**
     * 获取项目分类
     * 
     * @param type $map 查询条件
     * @param type $order 排序
     * @param type $field 查询字段 默认所有
     * @return type
     */
    public static function getProjectcategory($map = [], $order = ['cat_id' => SORT_ASC], $field = '*')
    {
        $projectcategoryList = static::find()
                ->select($field)
                ->where($map)
                ->orderBy($order)
                ->asArray()
                ->all();
        return $projectcategoryList;
    }
    
    /**
     * 生成所有的类别的下拉框
     * 
     * @param type $cutCat  默认选择
     * @return  array $list 返回值 
     */
    public static function getProjectcategoryTreeList($cutCat = 0, $disabled_id=0)
    {
        $category = self::getProjectcategory(['status' => 1], [], 'cat_id,parent_id as pid,name');
        foreach ($category as $result) {
            $projectcategoryList[$result['cat_id']] = $result;
        }
        $str = "<option value='\$cat_id' \$selected \$disabled>\$spacer \$name</option>";
        $Tree = new Tree($projectcategoryList);
        $Tree ->icon =array('&nbsp;&nbsp;&nbsp;│', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $list = $Tree->get_tree(0, $str,intval($cutCat),$disabled_id);
        return $list;
    }
    
    public static function getProjectcategoryTree($cutCat = 0, $where = [])
    {
        $projectcategoryList=[];
        $order = [
            'sort' => SORT_DESC,
            'cat_id' => SORT_DESC,
        ];
        $category = self::getProjectcategory($where, $order,'cat_id,parent_id as pid,name,sort,status,create_time');
        
        $pid = $category[0]['pid'];
        foreach ($category as $result) {
            if ($pid > $result['pid']) {
                $pid = $result['pid'];
            }
            $projectcategoryList[$result['cat_id']] = $result;
            $projectcategoryList[$result['cat_id']]['create_time'] = date('Y-m-d H:i:s',$result['create_time']);
            $projectcategoryList[$result['cat_id']]['str_status'] = ($result['status'] == 1) ? '<font color="green">启用</font>' : '<font color="red">禁用</font>';
            $childsProjectcategory = self::getProjectcategory(['parent_id' => $result['cat_id']], [], 'cat_id'); //检测是否有子类
          
            if (!empty($childsProjectcategory)) {
                $deleteUrl = 'javascript:;';
                $classInfo = 'link-undelete gray';
                $projectcategoryList[$result['cat_id']]['checkbox'] ="<input type='checkbox' name='delete[]' class='box-delete' value='".$result['cat_id']."' disabled='true'/>";
            }else {
                $deleteUrl = Url::toRoute(array('projectcategory/delete', 'id' => $result['cat_id']));
                $classInfo = 'link-delete';
                $projectcategoryList[$result['cat_id']]['checkbox'] = "<input type='checkbox' name='delete[]' class='box-delete' value='".$result['cat_id']."'/>";
            }
            $projectcategoryList[$result['cat_id']]['str_operation'] = "<a href='" . Url::toRoute(array('projectcategory/view', 'id' => $result['cat_id'])) . "' > 修改 </a>&nbsp;&nbsp;|&nbsp;&nbsp;
                <a href='" . Url::toRoute(array('projectcategory/create', 'cat_id' => $result['cat_id'])) . "' > 添加子类 </a>&nbsp;&nbsp;|&nbsp;&nbsp;
                <a href='" . $deleteUrl . "' class='" . $classInfo . "'>删除</a>";
        }
//           Tool::dump($projectcategoryList);
      
         $str = "<tr>
             <td class='key_num'></td>
            <td>\$checkbox</td>
            <td align='center' style='vertical-align: middle;' >
            <input type='text' size='4' value='\$sort' class='input' name='sort[\$cat_id]' />
            </td>
            <td>\$cat_id</td>
            <td>\$spacer\$name  </td>
            <td>\$create_time</td>
            <td align='center' style='vertical-align:middle'>\$str_status</td>
            <td align='center'>\$str_operation</td>
            </tr>";
        $Tree = new Tree($projectcategoryList);
        $Tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $Tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $list = $Tree->get_tree($pid, $str, intval($cutCat));
        return $list;  
       
      }
    
    /**
     * 公共搜索所需信息 
     */
    public function search()
    {
        return [
            'name' => '类别名称',
        ];
    }
    
    /**
     * 返回状态列表
     */
    public static function getStatusList()
    {
        return [
            self::STATUS_ENABLE => '显示',
            self::STATUS_DISABLE => '锁定',
        ];
    }
    
    /**
     * 插入更新前置操作
     */
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            //判断是否是插入操作
            if ($this->isNewRecord) {
                $this->user_id =  Yii::$app->user->identity->user_id;
                $this->create_time = time();
                $this->ip = Yii::$app->getRequest()->getUserIP();
            }
            $this->update_time = time();
            $this->ip = Yii::$app->getRequest()->getUserIP();
            return true;
        } else {
            return false;
        }
    }
    
    /**
     * 更新后更新类表
     */
    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        //先更新父级ID集，子集ID集以便更新状态
        self::repairCategory();
        //若用户修改了类的状态则更新其子类状态
        if ($this->status != $changedAttributes['status']) {
            self::updateStatus($this->cat_id);
        }
        //检查更新类禁用状态
        self::updateStatusFalse();
    }
    
    /**
     * 删除后更新类表
     */
    public function afterDelete()
    {
        parent::afterDelete();
        self::repairCategory();
    }
    
    /**
     * 更新子和父集合
     */
    public static  function repairCategory()
    {
        $cate = self::getCate();
        if (is_array($cate)) {
            $command = Yii::$app -> db -> createCommand();
            //更新父级
            foreach ($cate as $id => $category) {
                $cate[$id]['parent_ids'] = $parent_ids = self::getParentids($id);
                $command->update('{{%project_category}}', ['parent_ids' => $parent_ids], 'cat_id=:id', [':id' => $id])->execute();
            }
            //通过更新父级更新子集
            foreach ($cate as $id =>$category) {
                $cate[$id]['child_ids'] = $child_ids =  self::getChildids($id);
                $command->update('{{%project_category}}', ['child_ids'=> $child_ids], 'cat_id=:id', [':id' => $id])->execute();
            }
            
        }
        
    }

    /**
     * 返回以类id为索引的类列表
     * 
     * @return array 类列表
     */
    public static function getCate()
    {
        $cate_info = self::getProjectcategory([], [], 'cat_id, parent_id, name, parent_ids, child_ids, status');
        if ($cate_info) {
            foreach ($cate_info as $value) {
                $newarr[$value['cat_id']] = $value;
            }
            return $newarr;
        }
    }
    
    /**
     * 获取父集合
     * 
     * @param type $id
     * @param type $arrparentid
     * @return boolean
     */
    public static function getParentids($id, $arrparentid = '')
    {
        $cate = self::getCate();
        if (!is_array($cate) || !isset($cate[$id]))
            return false;
        $parentid = $cate[$id]['parent_id'];
        $arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid;
        if ($parentid) {
            $arrparentid = self::getParentids($parentid, $arrparentid);
        }else {
            $cate[$id]['parent_ids'] = $arrparentid;
        }
        return $arrparentid;
    }
    
    /**
     * 获取子类集合
     * 
     * @param type $id
     * @return string
     */
    public static function getChildids($id)
    {
        $cate = self::getCate();
        $arrchildid = $id;
        if (is_array($cate)) {
            foreach ($cate as $cateid =>$category) {
                if ($category['parent_id'] && $id != $cateid) {
                    $arrchildids = explode(',', $category['parent_ids']);
                    if (in_array($id, $arrchildids)) {
                        $arrchildid .= ','.$cateid;
                    }
                }
            }
        }
        return $arrchildid;           
    }
    
    /**
     * 遍历类表检查项目类禁用状态
     * 
     * @param  integer $parentId 父级ID
     * @param  integer $childId  父级ID下的子ID
     */
    public static function updateStatusFalse()
    {
        $parent = $child = self::getCate();
        if (is_array($parent)) {
            foreach ($parent as $parentId => $parentValue) {
                //若当前状态为禁用将其子类状态
                if ($parentValue['status'] == 0) {
                    self::updateStatus($parentId);
                }
            }  
        }
    }
    
    /**
     * 更新当前修改类下的子类状态
     * 
     * @param  integer $id 当前修改的类ID
     */
    public static function updateStatus($id)
    {
        $parent = static::findOne(['cat_id' => $id]);
        $parentStatus = $parent['status'];
        $childs = $parent['child_ids'];
        $arrparentids = explode(',', $childs);
        $command = Yii::$app->db->createCommand();
        $child = self::getCate();
        //将当前类下的所有子类状态与当前类的状态保持一致
        if (is_array($child)) {
            foreach ($child as $cateid => $category) {
                if ($category['parent_id'] && $id != $cateid) {
                    if (in_array($cateid, $arrparentids)) {
                        $command->update('{{%project_category}}', ['status' => $parentStatus], 'cat_id=:id', [':id' => $cateid])->execute();
                    }
                }
            }
        }
    }
    
}
