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

namespace home\modules\customer\models;

use home\modules\contract\models\Contract;
use Yii;
use home\models\Tag;
use home\models\TagLink;
use home\models\Area;
use qcbase\models\Auth;
use home\modules\customer\models\District;
use home\modules\customer\models\DistrictLink;

/**
 * This is the model class for table "{{%customer%}}".
 *
 * 客户模型
 *
 * @property integer  $customer_id       (客户ID)
 * @property string   $customer_no       (客户编号)
 * @property string   $name              (客户名称)--(全称)
 * @property string   $simple_name       (客户简称)
 * @property integer  $category_id       (客户类别)--(关联表customer_category)
 * @property string   $organization_no   (组织机构代码)
 * @property integer  $level_id          (客户等级ID)--(关联表customer_level)
 * @property integer  $district_id       (客户区域ID)--(关联表customer_district)
 * @property integer  $leader_id         (负责人ID)--(关联表user)
 * @property string   $share_user_ids    (共享人ID)--(关联表user)
 * @property string   $department1       (信息科)
 * @property string   $dept_phone1       (信息科电话)
 * @property string   $department2       (科室)
 * @property string   $dept_phone2       (科室电话)
 * @property string   $google_coordinate (Google坐标)
 * @property string   $baidu_coordinate  (百度坐标)
 * @property string   $address           (客户地址)
 * @property string   $info              (客户信息)
 * @property string   $remark            (备注)
 * @property integer  $sort              (排序)
 * @property tinyint  $status            (状态)--(默认值:1)--(0:禁用; 1:开启; 99:逻辑删除)
 * @property integer  $user_id           (创建人ID)--(关联表user)
 * @property integer  $create_time       (创建时间)
 * @property integer  $update_time       (更新时间)
 * @property string   $ip                (创建人IP)
 * @property integer  $province_id       (省份ID)
 * @property integer  $city_id           (城市ID)
 * @property integer  $area_id           (区ID)
 * @property string   $street            (街道地址)
 * @property tinyint  $attention         (星标关注)--(默认值:0)--(0:不关注; 1:关注)
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class Customer extends \yii\db\ActiveRecord
{
    /**
     * configured leader_name
     * 负责人的名字
     *
     * @var String
     */
    public $leader_name;

    /**
     * configured share_user_names
     * 共享人的名字
     *
     * @var Array
     */
    public $share_user_names;


    public $tag_names;           //所有标签的名称    array

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

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%customer}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'category_id', 'level_id', 'leader_id', 'leader_name', 'province_id', 'city_id', 'area_id', 'simple_name'], 'required'],
            [['customer_no'], 'unique'],
            [['category_id', 'level_id', 'district_id', 'leader_id', 'sort', 'status', 'attention', 'user_id', 'create_time', 'update_time', 'province_id', 'city_id', 'area_id'], 'integer'],
            [['province_id', 'city_id', 'area_id'], 'number', 'min' => 1],
            [['department1', 'department2', 'organization_no'], 'string', 'max' => 20],
            [['name', 'dept_phone1', 'dept_phone2', 'google_coordinate', 'baidu_coordinate', 'tag_names'], 'string', 'max' => 50],
            [['simple_name'], 'string', 'max' => 10],
            [['customer_no'], 'string', 'max' => 64],
            [['share_user_ids', 'address', 'share_user_names', 'info', 'remark', 'street'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'customer_id'       => 'ID',
            'customer_no'       => '客户编号',
            'name'              => '客户名称',
            'simple_name'       => '客户简称',
            'category_id'       => '客户类别',
            'organization_no'   => '组织机构代码',
            'level_id'          => '客户等级',
            'district_id'       => '所属区域',
            'leader_id'         => '当前负责人',
            'leader_name'       => '负责人',
            'share_user_ids'    => '共享人',
            'share_user_names'  => '共享人',
            'department1'       => '信息科',
            'dept_phone1'       => '信息科电话',
            'department2'       => '科室',
            'dept_phone2'       => '科室电话',
            'google_coordinate' => '谷歌坐标',
            'baidu_coordinate'  => '百度坐标',
            'address'           => '客户地址',
            'info'              => '客户信息',
            'remark'            => '备注',
            'sort'              => '排序',
            'status'            => '状态',
            'user_id'           => '创建人id',
            'create_time'       => '创建时间',
            'update_time'       => '更新时间',
            'tag_names'         => '输入标签',
            'ip'                => 'ip地址',
            'province_id'       => '省份ID',
            'city_id'           => '城市ID',
            'area_id'           => '地区ID',
            'street'            => '街道地址',
            'attention'         => '星标关注',
        ];
    }

    /**
     * 查询符合条件的客户
     *
     * @param  type   $map             查询条件
     * @param  type   $order           排序
     * @param  type   $field           查询字段 默认全部（*）
     * @return type   $customerList    返回查询的数组
    */
    public static function getCustomer($map = [], $order = ['customer_id' => SORT_DESC], $field = "*")
    {
        $customerList = static::find()
                            ->select($field)
                            ->where($map)
                            ->orderBy($order)
                            ->asArray()
                            ->all();
        return $customerList;
    }

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

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

    /**
     * 公共搜索所需信息
     */
    public static function search()
    {
        return [
			'keywords' => [
				'name' => '客户名称',
                'leader_name' => '负责人'
			],
//			'status' => static::getLevelList(),
        ];
    }

    /**
     * 关联获取当前用户关联的最新的合同
     */
    public  function getNewestCustomer()
    {
        return $this->hasOne(Contract::className(), ['customer_no' => 'customer_no'])->orderBy(['create_time' => SORT_DESC])->select('contract_id, name');
    }

    /**
     * 关联获取当前用户的等级名称
     */
    public  function getLevel()
    {
        return $this->hasOne(Level::className(), ['level_id' => 'level_id'])->select('name');
    }

    /**
     * 关联获取当前用户的类别名称
     */
    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['cat_id' => 'category_id'])->select('name');
    }

    /**
     * 关联获取当前用户的区域名称
     */
    public function getDistrict()
    {
        return $this->hasOne(District::className(), ['district_id' => 'district_id'])->select('name');
    }

    /**
     * 关联获取创建人的姓名
     */
    public function getUser()
    {
        return $this->hasOne(\common\models\User::className(), ['user_id' => 'user_id'])->select('realname');
    }

    /**
     * 关联获取负责人姓名
     */
    public function getLeader()
    {
        return $this->hasOne(\common\models\User::className(), ['user_id' => 'leader_id'])->select('realname');
    }

    /**
     *
     * 关联获取负责人姓名
     */
    public function getSharer()
    {
        return $this->hasOne(\common\models\User::className(), ['user_id' => 'share_user_ids' ])->select('realname');
    }

   

 

    /**
     * 获取当前客户关联的所有合同
     */
    public function getContractAll()
    {
        return $this->hasMany(Contract::className(), ['customer_no' => 'customer_no'])->orderBy(['create_time' => SORT_DESC])->select('contract_id, name')->asArray();
    }

    /**
     * 获取当前客户关联的所有合同的个数
     */
    public function getContractNumber()
    {
        return $this->hasMany(Contract::className(), ['customer_no' => 'customer_no'])->count();
    }

    /**
     * 获取当前客户关联的所有销售机会
     */
    public function getOpportunityAll()
    {
        return $this->hasMany(\home\modules\sale\models\Opportunity::className(), ['customer_no' => 'customer_no'])->orderBy(['create_time' => SORT_DESC])->select('opportunity_id, name')->asArray();
    }

    /**
     * 获取当前客户关联的所有销售机会的个数
     */
    public function getOpportunityNumber()
    {
        return $this->hasMany(\home\modules\sale\models\Opportunity::className(), ['customer_no' => 'customer_no'])->count();
    }

    /**
     * 获取客户的联系人列表
     *
     * @return type
     */
    public function getContacters($customer_no)
    {
        return Contacter::getContacter(['customer_no'=>$customer_no, 'status' => Contacter::STATUS_ENABLE ],['contacter_id' => SORT_ASC],"*");
    }

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

    /**
     * 查询客户的所有等级列表
     *
     * @return type  array 返回等级ID为键名，等级名称为键值的一维数组
     */
    public static function getLevelList()
    {
        $data = [];
        $LevelList = Level::getCustomerLevel(['status' => Level::STATUS_ENABLE], ['level_id' => SORT_ASC], 'level_id, name');
        foreach ($LevelList as $result) {
            $data[$result['level_id']] = $result['name'];
        }
        return $data;
    }

    /**
	 * 获取客户编号
	 *
	 * @return type
	 */
	public static function getNo()
	{
		$prefix = 'KH';
		return $prefix.date('Ymd').mt_rand(1000, 9999);
	}

    /**
     * 获取客户所属区域列表
     *
     * @return type  array 返回区域ID为键名，区域名称为键值的一维数组
     */
    public static function getAreaList()
    {
        $data = [];
        $AreaList = District::getArea([], ['district_id' => SORT_ASC], 'district_id, name');
        foreach ($AreaList as $result) {
            $data[$result['district_id']] = $result['name'];
        }
        return $data;
    }

    /**
     * 插入更新前置操作
     */
    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();
            }

            //查找省，市，区 串联起来赋值给地址栏
            $province = Area::findOne($this->province_id);
            $city = Area::findOne($this->city_id);
            $area = Area::findOne($this->area_id);
            $this->address = $province['title'].$city['title'].$area['title'].$this->street;

            //获取客户区域
            $this->district_id = District::getAreaDistrict($this->province_id, $this->city_id, $this->area_id);

            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取所有的标签name json格式
     *
     * @param type $map
     * @return type
     */
    public static function getName()
    {
        $TagList = Tag::find()
                ->select('name')
                ->asArray()
                ->column();
        return json_encode($TagList);
    }

    /**
     * 获取关联标签的id数组
     *
     * @param type $map
     * @param type $field
     * @return type
     */
    public static function getTagLink($map = [],$field = '*')
    {
        $list = TagLink::find()
                ->where($map)
                ->select($field)
                ->asArray()
                ->column();
        return $list;
    }

    /**
     * 获取标签的名字
     *
     * @return type
     */
    public function getTag()
    {
       $list = $this->hasMany(Tag::className(), ['tag_id' => 'tag_id'])
                        ->viaTable('{{%tag_link}}', ['link_id' => 'customer_id'])->asArray();
        return $list;
    }

    /**
     * 关联表插入记录
     */
    public function afterSave($insert, $changedAttributes) 
    {
        parent::afterSave($insert, $changedAttributes);
        $request = Yii::$app -> request;
        $linkId = $this->customer_id;
        $linkType ="customer";
        //更新标签关联表
        $tags = Tag::insertTags($this->tag_names);
        TagLink::deleteTagLink($linkId, $linkType);
        TagLink::insertTagLink($tags, $linkId, $linkType);
        
        \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 judgeDistrict()
    {
        if (!Yii::$app->session->get('isSuperAdmin')) {
            $result = District::getMyDistrict('customer/customer/index');
            if($result === false){
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

    /**
     * 更新客户的地区
     * 
     * 每次添加修改客户区域的时候要更新一下所有的客户，重新定位区域
     */
    public static function updateDistrict()
    {
        $query = static::find();
        $connect = Yii::$app->db;
        foreach ($query->batch() as $customers) {
            foreach ($customers as $customer) {
                $districtId = District::getAreaDistrict($customer['province_id'], $customer['city_id'], $customer['area_id']);
                if ($districtId != $customer['district_id']) {
                    $connect->createCommand()
                        ->update(static::tableName(), ['district_id' => $districtId], 'customer_id = :id', [':id' => $customer['customer_id']])
                        ->execute();
                }
            }
        }
    }

}
