<?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;
use home\modules\customer\models\Customer;
use home\modules\customer\models\Contacter;
use home\modules\sale\models\Category;
use home\modules\sale\models\Origin;
use home\modules\sale\models\Status;
use home\models\Area;
use qcbase\models\Auth;
use common\models\User;

/**
 * 销售机会表 ({%sale_opportunity})
 *
 * @property integer $opportunity_id  (销售机会id)
 * @property string $name  (销售机会名称)
 * @property integer $origin_id  (销售机会来源id 关联qc_sale_origin)
 * @property integer $category_id  (销售机会阶段id 关联qc_sale_category)
 * @property integer $status_id  (销售机会状态id 关联qc_sale_status)
 * @property integer $leader_id  (负责人ID （关联qc_user表）)
 * @property integer $customer_no  (客户编号 关联qc_customer)
 * @property integer $contacter_id  (联系人)
 * @property string $contract_address  (合同签订地址)
 * @property decimal $gain_rate  (赢单率(百分比))
 * @property decimal $estimate_price  (预计价格)
 * @property integer $due_date  (预计成交日期)
 * @property string $nextstep  (下次联系内容)
 * @property integer $nextstep_time  (下次联系时间)
 * @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 关联表qc_user)
 * @property string $ip  (创建人ip)
 * @property integer  $province_id  (省份ID)
 * @property integer  $city_id  (城市ID)
 * @property integer  $area_id  (区ID)
 * @property string   $street (街道地址)
 * @property string   $opportunity_no (销售机会编号)
 * @property tinyint  $attention (热点)
 * @property integer  $discoverer_id (发现人)
 *
 * @author Strief http://blog.u-bo.com
 * @since 0.1
 */
class Opportunity extends ActiveRecord
{
    public $leader_name; //负责人
    public $customer_name; //客户名称
    public $contacter_name; //联系人
    public $discoverer_name; //发现人名称

    const STATUS_ENABLE  = 1;    //启用
    const STATUS_DISABLE = 0;    //禁用

    /**
    * @inheritdoc
    */
    public static function tableName()
    {
        return '{{%sale_opportunity}}';
    }
    
    /**
    * @inheritdoc
    */
    public function rules()
    {
        return [
            [['name', 'leader_name', 'customer_name', 'contacter_name', 'estimate_price', 'due_date', 'opportunity_no', 'discoverer_name'], 'required'],
            [['origin_id', 'category_id', 'status_id', 'leader_id', 'contacter_id', 'sort', 'status', 'create_time', 'update_time', 'user_id', 'attention', 'discoverer_id'], 'integer'],
            [['opportunity_no'], 'unique'],
            [['estimate_price'], 'number', 'max' => 99999999.99],
//            [['gain_rate'], 'number', 'max' => 100],
            [['remark', 'customer_no'], 'string'],
            [['name'], 'string', 'max' => 50],
//            [['contract_address', 'street'], 'string', 'max' => 255],
            [['nextstep'], 'string', 'max' => 2000],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
    * @inheritdoc
    */
    public function attributeLabels()
    {
        return [
            'opportunity_id' => 'ID',
            'name' => '机会名称',
            'origin_id' => '来源',
            'category_id' => '阶段',
            'status_id' => '状态',
            'leader_id' => '负责人ID',
            'customer_no' => '客户编号',
            'contacter_id' => '联系人ID',
//            'contract_address' => '合同签订地址',   屏蔽掉--20150126
//            'gain_rate' => '赢单率',
            'estimate_price' => '预计价格',
            'due_date' => '预计成交日期',
            'nextstep' => '商务分析',
//            'nextstep_time' => '下次联系日期',    屏蔽掉--20150126
            'sort' => '排序',
            'status' => '状态',
            'remark' => '用户需求',
            'create_time' => '创建时间',
            'update_time' => '修改时间',
            'user_id' => '创建人ID',
            'ip' => '创建人Ip',
            'leader_name' => '所有人',
            'customer_name' => '客户名称',
            'contacter_name' => '联系人',
//            'province_id' => '省份ID',  屏蔽掉--20150126
//            'city_id' => '城市ID',  屏蔽掉--20150126
//            'area_id' => '地区ID',  屏蔽掉--20150126
//            'street' => '街道地址',   屏蔽掉--20150126
            'opportunity_no' => '机会编号',
            'attention' => '热点',
            'discoverer_id' => '发现人',
            'discoverer_name' => '发现人',
        ];
    }

    /**
     * 公共搜索所需信息
     * 
     * 这里返回公共搜索的信息，我们希望所有的搜索走统一的配置
     * 返回值里的键名为keywords的数组为搜索里关键字搜索所支持的字段
     * 返回值里的键名为status的数组为搜索里状态搜索所支持的字段
     */
    public function search()
    {
        return [
            'keywords' => [
                'name' => '销售机会名称',
                'customer' => '客户名称',
                'leader' => '负责人',
            ],
            'origin' => self::getOriginList(),
            'status' => self::getSaleStatusList(),
        ];
    }

    /**
     *  返回关注状态值
     */
    public static function getAttentionList()
    {
        return [
            self::STATUS_ENABLE => '是',
            self::STATUS_DISABLE => '否',
        ];
    }

    /**
     * 销售机会来源下拉框
     *
     * @return array $date 销售机会来源数据
     */
    public static function getOriginList()
    {
        $data=[];
        $SaleOriginList = Origin::getOrigin([], ['sort' => SORT_DESC], 'origin_id, name');
        foreach ($SaleOriginList as $item) {
            $data[$item['origin_id']] = $item['name'];
        }
        return $data;
    }

    /**
     * 销售机会状态下拉框
     *
     * @return array $date 销售机会状态数据
     */
    public static function getSaleStatusList()
    {
        $data=[];
        $SaleStatusList = Status::getStatus([], ['sort' => SORT_DESC], 'status_id, name');
        foreach ($SaleStatusList as $item) {
            $data[$item['status_id']] = $item['name'];
        }
        return $data;
    }

    /**
     * 关联获取客户信息
     */
    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['customer_no' => 'customer_no']);
    }

    /**
     *负责人信息
     */
    public function getLeader()
    {
        return $this->hasOne(User::className(), ['user_id' => 'leader_id'])->select('realname,username,user_id');
    }

    /**
     * 关联获取联系人信息
     */
    public function getContacter()
    {
        return $this->hasOne(Contacter::className(), ['contacter_id' => 'contacter_id'])->select('name');
    }

    /**
     * 关联获取销售来源
     */ 
    public function getOrigin()
    {
        return $this->hasOne(Origin::className(), ['origin_id' => 'origin_id']);
    }

    /**
     * 关联获取销售类别
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['cat_id' => 'category_id']);
    }

    /**
     * 关联获取销售状态
     */
    public function getSaleStatus()
    {
        return $this->hasOne(Status::className(), ['status_id' => 'status_id']);
    }

    /**
     * 获取当前销售机会关联的所有日程
     */
    public function getSchedule()
    {
        return $this->hasMany(\home\models\Schedule::className(), ['link_id' => 'customer_no'])->where(['link_type' => 'sale_opportunity'])->orderBy(['schedule_time' => SORT_DESC])->asArray();
    }

    /**
     * 插入更新前置操作
     */
    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->due_date = strtotime($this->due_date);
           // $this->nextstep_time = empty($this->nextstep_time)?$this->due_date:strtotime($this->nextstep_time);   屏蔽掉--20150126
            $this->update_time = time();

//            $province = Area::findOne($this->province_id);  屏蔽掉--20150126
//            $city = Area::findOne($this->city_id);    屏蔽掉--20150126
//            $area = Area::findOne($this->area_id);    屏蔽掉--20150126
            //$this->contract_address = $province['title'].$city['title'].$area['title'].$this->street;   屏蔽掉--20150126
            return true;
        } else {
            return false;
        }
    }
    
     public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        \qcbase\models\ActionLog::insertLog('home','修改',json_encode($changedAttributes));
    }

    /**
     * 生成销售机会编号
     */
    public static function getNo()
    {
        $prefix = 'XS';
        return $prefix.date('Ymd').mt_rand(1000, 9999);
    }

    /**
     * 权限审核
     * @param  string  $url     操作URL
     * @param  integer $user_id 用户ID
     */
    public static function readAccess($url = null, $user_id = 0)
    {
        if (empty($url)) {
            return false;
        }
        empty($user_id) ? $user_id = \Yii::$app->user->id : $user_id;
        //非超级管理员，需要检测权限
        if (Yii::$app->session->get('isSuperAdmin')) {
            return true;
        }
        //检测是否具有某一特定权限
        if (Auth::checkAccess($url, $user_id)) {
            return true;
        }
        return false;
    }

}
