<?php

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

namespace home\modules\customer\models;

use Yii;
use qcbase\models\Auth;
use home\modules\customer\models\District;
use home\modules\customer\models\Customer;
use yii\helpers\ArrayHelper;
use common\models\PermissionScope;

/**
 * This is the model class for table "{{%customer_contacter}}".
 *
 * 客户关联的联系人模型
 *
 * @property integer  $contacter_id (客户联系人ID)
 * @property string   $name         (联系人姓名)
 * @property integer  $customer_no  (所属客户，关联表qc_customer)
 * @property string   $job          (职务)
 * @property string   $phone        (联系电话)
 * @property string   $remark       (备注)
 * @property integer  $sort         (排序)
 * @property smallint $status       (状态：0 禁用 1开启 99逻辑删除 默认开启)
 * @property integer  $create_time  (创建时间)
 * @property integer  $update_time  (更新时间)
 * @property integer  $user_id      (创建人，关联表qc_user)
 * @property string   $ip           (创建人IP)
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class Contacter extends \yii\db\ActiveRecord
{

    public $customer_name;    //所属客户名称

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

    /**
     * @inheritdoc
     */

    public static function tableName()
    {
        return '{{%customer_contacter}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'job', 'customer_no', 'customer_name', 'phone', 'sort', 'status'], 'required'],
            [['sort', 'create_time', 'update_time', 'user_id'], 'integer'],
            [['name'], 'string', 'max' => 20],
            [['job'], 'string', 'max' => 55],
            [['phone'], 'string', 'max' => 50],
            [['customer_no'], 'string', 'max' => 64],
            [['remark'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'contacter_id' => 'ID',
            'name' => '联系人',
            'customer_no' => '所属客户',
            'customer_name' => '所属客户',
            'job' => '职务',
            'phone' => '电话',
            'remark' => '备注',
            'sort' => '排序',
            'status' => '状态',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'user_id' => '创建人id',
            'ip' => 'IP地址',
        ];
    }

    /**
     * 查询符合条件的联系人
     *
     * @param type $map  查询条件
     * @param type $order   排序
     * @param type $field 查询字段 默认全部（*）
     * @return type 返回值
     */
    public static function getContacter($map = [], $order = ['contacter_id' => SORT_DESC], $field = "*")
    {
        $contacterList = static::find()
                ->select($field)
                ->where($map)
                ->orderBy($order)
                ->asArray()
                ->all();
        return $contacterList;
    }

    /**
     * 查询所有客户
     *
     * @return type  array 返回客户编号为键名，客户名称为键值的一维数组
     */
    public function getCustomerList()
    {
        $data = [];
        $CustomerList = Customer::getCustomer([], ['customer_id' => SORT_DESC], 'customer_no, name,customer_id');
        foreach ($CustomerList as $result) {
            $data[$result['customer_no']] = $result['name'];
        }
        return $data;
    }

    /**
     * 关联获取当前的客户名称
     */
    public function getCustomer()
    {
        return $this->hasOne(Customer::className(), ['customer_no' => 'customer_no'])->select('name,customer_id');
    }

    /**
     *
     * @return type返回状态
     */
    public static function getStatusList()
    {
        return [
            self::STATUS_ENABLE => '启用',
            self::STATUS_DISABLE => '禁用',
        ];
    }

    /**
     * 公共搜索所需信息
     */
    public function search()
    {
        return [
            'keywords' => [
                'name' => '联系人名称',
                'job' => '职务',
                'customer'=>'所属客户',
                'creater'=>'创建人'
            ],
            'status' => self::getStatusList(),
        ];
    }

    public function getUser(){
        return $this->hasOne(\common\models\User::className(),['user_id'=>'user_id'])->select('realname,user_id,username');
    }

    /**
     * 插入更新前置操作
     */
    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();
            } else {
                $this->update_time = time();
            }
            return true;
        } else {
            return false;
        }
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        \qcbase\models\ActionLog::insertLog('home', '修改', json_encode($changedAttributes));
    }

    /**
     * 权限审核
     * @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;
    }

    /**
     * 查找当前所有客户的所有联系人
     */
    public static function getEligibilityContacter()
    {
        $result = PermissionScope::getScopeUser('customer/contacter/index');

        if($result === false){
            $result = [];
        } else if ($result === []) {
            return true;
        }
        $findArr = [];
        $userId = Yii::$app->user->id;
        $findArr[] = 'FIND_IN_SET(' . (int) $userId . ', share_user_ids)';
        $findStr = implode(' or ', $findArr);
        $district = Customer::find()->select('customer_no')->where(['in', 'leader_id', $result])->orWhere($findStr)->asArray()->all();
        $customerArray = arrayHelper::getColumn($district,'customer_no');
        return $customerArray;
    }

}
