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

namespace home\modules\sale\models;

use Yii;
use yii\db\ActiveRecord;

/**
 * 销售机会来源表 ({%sale_origin})
 *
 * @property integer $origin_id  (销售机会来源id)
 * @property string $name  (来源名称)
 * @property integer $sort  (排序  默认0)
 * @property smallint $status  (状态：0 禁用 1开启 99逻辑删除 默认开启)
 * @property text $remark  (备注)
 * @property integer $create_time  (创建时间)
 * @property integer $update_time  (修改时间)
 * @property integer $user_id  (创建人id)
 * @property string $ip  (创建人ip)
 *
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */
class Origin extends ActiveRecord
{
    const STATUS_ENABLE = 1; //启用
    const STATUS_DISABLE = 0; //禁用

    /**
    * @inheritdoc
    */
    public static function tableName()
    {
        return '{{%sale_origin}}';
    }
    
    /**
    * @inheritdoc
    */
    public function rules()
    {
        return [
            [['sort', 'status', 'create_time', 'update_time', 'user_id'], 'integer'],
            [['name'], 'required'],
            [['remark'], 'string'],
            [['name'], 'string', 'max' => 20],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
    * @inheritdoc
    */
    public function attributeLabels()
    {
        return [
            'origin_id' => 'ID',
            'name' => '来源名称',
            'sort' => '排序',
            'status' => '状态',
            'remark' => '备注',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'user_id' => '创建人ID',
            'ip' => '创建人Ip',
        ];
    }

    /**
     * 查询销售机会来源列表
     *
     * @return array   $originLists 返回查询结果
     */
    public static function getOrigin($map = [], $order = ['sort' => SORT_DESC], $field = "*")
    {
        $map['status'] = 1;
        $originLists = static::find()
                ->select($field)
                ->where($map)
                ->orderBy($order)
                ->asArray()
                 ->all();
        return $originLists;
    }

    /**
     * 返回状态列表 
     */
    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->ip = Yii::$app->getRequest()->getUserIP();
                $this->create_time = time();
            }
            $this->update_time = time();
            return true;
        } else {
            return false;
        }
    }
}