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

namespace home\modules\customer\models;

use Yii;
use yii\db\ActiveRecord;
use yii\db\Query;
use common\components\Tool;
use common\components\Tree;
use common\models\TreeList;
use home\models\Area;
use yii\base\ErrorException;
use common\models\Common;
use common\models\PermissionScope;

/**
 * This is the model class for table "{{%customer_district}}".
 *
 * 客户区域模型
 *
 * @property integer  $district_id  (地区区域ID)
 * @property integer  $leader_id  (区域负责人ID)
 * @property string   $leader_name  (区域负责人姓名)
 * @property string   $code         (区域编号)
 * @property string   $name         (区域名称)
 * @property integer  $parent_id    (父级ID)
 * @property string   $parent_ids   (父级ID集)
 * @property string   $child_ids    (子ID集)
 * @property integer  $sort         (排序)
 * @property smallint $status       (状态：0 禁用 1开启 99逻辑删除 默认开启)
 * @property integer  $user_id      (创建人，关联表qc_user)
 * @property integer  $create_time  (创建时间)
 * @property integer  $update_time  (更新时间)
 * @property string   $ip           (创建人IP)
 *
 * @author zealxd http://blog.u-bo.com
 * @since 0.1
 */
class District extends TreeList
{
    public $territory;  //负责区域
    public $num;        //

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

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'sort', 'status', 'code'], 'required'],
            [['parent_id', 'leader_id', 'sort', 'status', 'user_id', 'create_time', 'update_time', 'num'], 'integer'],
            [['leader_name'], 'string', 'max' => 50],
            [['code'], 'string', 'max' => 20],
            [['name', 'parent_ids', 'child_ids'], 'string', 'max' => 255],
            [['ip'], 'string', 'max' => 15]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'district_id' => 'ID',
            'leader_id'   => '区域负责人',
            'leader_name' => '区域负责人',
            'code'        => '区域代码',
            'name'        => '区域名',
            'parent_id'   => '父级id',
            'parent_ids'  => '父级所有id',
            'child_ids'   => '子级所有id',
            'sort'        => '排序',
            'status'      => '状态',
            'user_id'     => '创建人id',
            'create_time' => '创建时间',
            'update_time' => '更新时间',
            'ip'          => 'Ip地址',
            'territory'   => '负责区域',
        ];
    }


    /**
     * 列表页项目类别树形结构列表显示
     *
     * @param  integer $curCat 默认选择节点
     * @param  [type]  $where  关键字搜索
     * @return array   $list   列表内容
     */
    public static function getIndexTree($curCat = 0, $where = [], $showFirst = 0)
    {
         $str = "<tr>
            <td>\$checkbox</td>
            <td class='key_num'></td>
            <td class='theleft'>\$spacer\$name  </td>
            <td>\$code</td>
            <td>\$leader_name</td>
            <td align='center' style='vertical-align:middle'>\$str_status</td>
            <td align='center'>\$str_operation</td>
            </tr>";
        return parent::getIndexTreeList($curCat, $where, $str, 'district_id', 610, 287, $showFirst);
    }

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

    /**
     * 获取当前客户区域所负责的地区,关联qc_district_link
     */
    public function getDistrict()
    {
        return $this->hasMany(DistrictLink::className(), ['district_id' => 'district_id'])->orderBy(['link_id' => SORT_ASC])->asArray();
    }
    /**
     * 生成客户区域下拉框
     *
     * @param  integer $curCat      默认选择节点
     * @param  integer $disabledId  忽略节点
     * @return array   $list        上级类别下拉框内容
     */
    public static function getDropDownTree($curCat = 0, $disabledId = 0, $isNewRecord = 'true', $pk = 'district_id')
    {
        return parent::getDropDownTreeList($curCat, $disabledId, 'district_id', $isNewRecord, $pk);
    }

    /**
     * 返回状态列表
     */
    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();
            } else {
                $this->update_time = time();

                //当编辑更新的时候，会把当前关联的实际负责区域删除
                $model = new DistrictLink;
                $where['district_id'] = $this->district_id;
                $model::deleteAll($where);
            }
            //当负责人为空时，给默认值‘暂无’，负责人ID为0
            $this->leader_id = empty($this->leader_id)?0:$this->leader_id;
            $this->leader_name = empty($this->leader_name)?'':$this->leader_name;

            //把客户实际负责的区域数组赋值给一个自定义的字段，留待后面调用
            $this->territory = Yii::$app->request->post('district');
            return true;
        } else {
            return false;
        }
    }

    /**
     * 更新后更新项目类别表
     */
    public function afterSave($insert, $changedAttributes)
    {
        //获取当前编辑的主键值
        $district_id = $this->district_id;
        //获取更新前的赋值的字段
        $districtArray = $this->territory;
        unset($districtArray['parent_id']);  //删除多余的字段
        //把最新的实际负责区域存入到数据库中
        foreach($districtArray as $v) {
            $model = new DistrictLink;
            $model->district_id = $district_id;
            $model->province_id = $v['province_id'];
            $model->city_id = $v['city_id'];
            $model->area_id = $v['area_id'];
            if ($model->validate() && $model->save()) {
                continue;
            } else {
                throw new ErrorException($model->getErrors());
            }
        }

        parent::afterSave($insert, $changedAttributes);
        //更新父级ID集，子集ID集
        parent::repairTree(self::tableName(), 'district_id');
        //若用户修改了项目类别的状态则更新其子项目类别状态
        if ($this->status!='' &&$this->status != $changedAttributes['status']) {
            parent::updateStatus(self::tableName(), $this->district_id, 'district_id');
        }
        //检查更新项目类别禁用状态
        parent::updateStatusFalse(self::tableName(), 'district_id');

        //更新客户区域
        Customer::updateDistrict();
    }

    /**
     * 删除后更新项目类别表
     */
    public function afterDelete()
    {
        parent::afterDelete();
        parent::repairTree(self::tableName(),'district_id');
    }

    /**
     * 查找自己所负责的所有区域
     *
     * @return array  返回所有不重复的子集数组
     */
    public static function getMyDistrict($url = null)
    {
        $scopeUser = PermissionScope::getScopeUser($url);

        if ($scopeUser === false) {   //为false表示无此权限
            return false;
        }
        if ($scopeUser === []) {   //为[]表示超级管理员或所有人
            return [];
        }
        $data = '';
        $myResult =  static::find()->select('child_ids')->where(['in', 'leader_id', $scopeUser])->asArray()->all();

        if (empty($myResult)) {  //没有负责的区域
            return false;
        }

        foreach ($myResult as $v) {
            $data .= $v['child_ids'].',';
        }
        //这边要删除最后一个字符
        $resultData = rtrim($data, ',');
        $array = explode(',' , $resultData);
        //把数组中重复的值移除掉
        $endResult = array_unique($array);
        return $endResult;
    }

    /**
     * 查出自己所负责的详细地址（客户）
     *
     * @return array  返回包含省市区的二维数组
     */
    public static function getCustomerAddress()
    {
        $data = '';
        $array = [];
        $province_ids = [];
        $city_ids['y'] = [];
        $city_ids['n'] = [];
        $area_ids['y'] = [];
        $area_ids['n'] = [];

        //查找当前客户负责的区域
        $myResult = static::find()->select('district_id')->where(['leader_id' => Yii::$app->user->identity->user_id])->asArray()->all();
        foreach ($myResult as $k => $v) {
            $data .= $v['district_id'].',';
        }
        //去除最后一个字符，不然数组会多出一个空白，而empty判断空和0返回值一样，所有要避免掉
        $resultData = rtrim($data, ',');
        $array = explode(',', $resultData);

        //根据管理区域查出客户实际管理的省市区
        $linkResult = DistrictLink::find()->where(['in', 'district_id', $array])->asArray()->all();
        if (empty($linkResult)) {
            return false;
        }

        $returnAll = static::doForeach($linkResult);
        return $returnAll;
    }

    /**
     * 查出自己所负责的详细地址（客户区域）
     *
     * @param int $district_id 为0表示最顶级   其余为指定范围
     * @return array 返回值  返回包含省市区的二维数组
     */
    public static function getDistrictAddress($district_id = 0)
    {
        $data = '';
        $array = [];
        $province_ids = [];
        $city_ids['y'] = [];
        $city_ids['n'] = [];
        $area_ids['y'] = [];
        $area_ids['n'] = [];

        //判断是否为超级管理员并且是建立一级目录，如果是不需要下面的判断
        if (Yii::$app->session->get('isSuperAdmin') && empty($district_id)) {
            return false;
        }

        if (empty($district_id)) {
            //当为最顶级的，查出所能创建的所有区域
            $myResult = static::find()->select('district_id')->where(['leader_id' => Yii::$app->user->identity->user_id])->asArray()->all();
            foreach ($myResult as $k => $v) {
                $data .= $v['district_id'].',';
            }
            $resultData = rtrim($data, ',');
            $array = explode(',', $resultData);
        } else {
            $array = [$district_id];
        }
        //查找出负责区域对应的实际负责区域
        $linkResult = DistrictLink::find()->where(['in', 'district_id', $array])->asArray()->all();
        if (empty($linkResult)) {
            return false;
        }

        $returnAll = static::doForeach($linkResult);
        return $returnAll;
    }

    /**
     * 对传过来的数组进行解析重组
     *
     * @return array 返回值  返回包含省市区的二维数组
     */
    public function doForeach($array)
    {
        $province_ids = [];
        $city_ids['y'] = [];
        $city_ids['n'] = [];
        $area_ids['y'] = [];
        $area_ids['n'] = [];

        foreach ($array as $v) {
            $province_ids[] = $v['province_id'];  //省份必有
            if(empty($v['city_id'])){    //当市为空，表示包含了全部的市和区
                $city_ids['y'][] = $v['province_id'];   //表明区是省份下面的所有省份
                $allCity = Area::find()->where(['pid'=> $v['province_id']])->orderBy(['area_id' => SORT_ASC])->asArray()->all();
                foreach($allCity as $city) {
                    $area_ids['y'][] = $city['area_id'];   //表明区是当前省份下面的所有市所有区
                }
            } else {    //当市不为空，表示包含了特定的市
                $city_ids['n'][] = $v['city_id'];
                if(empty($v['area_id'])){     //当区为空，表示包含了全部的区
                    $area_ids['y'][] = $v['city_id'];
                } else {                      //当区不为空，表示包含了特定的区
                    $area_ids['n'][] = $v['area_id'];
                }
            }
        }
        $returnAll = ['province' => $province_ids, 'city' => $city_ids, 'area' => $area_ids];
        return $returnAll;
    }

    /**
     * 获取分类数据
     * @param string $field  需要获取的字段
     * @param array $map     查询条件
     * @param array $order   排序
     * @param string $index  索引
     */
    public static function getCateData($field = "*", $map = [], $order = [], $index = null)
    {
        $query = static::find()
        ->select($field)
        ->orderBy($order);
        if ($map !== null && is_array($map)) {
            $query->andWhere($map);     
        }
        if ($index !== null) {
            $query->indexBy($index);
        }
        $list = $query->asArray()->all();
        return $list;
    }

    /**
     * 查找一个地区所属的客户区域
     */
    public static function getAreaDistrict($province_id, $city_id, $area_id)
    {
        $districtId = 0;
        //查找区ID对应的客户区域ID
        $returnArea = DistrictLink::find()->select('district_id')->where(['area_id' => $area_id])->orderBy(['link_id' => SORT_DESC])->one();
        if(!empty($returnArea)) {
            return $returnArea['district_id'];
        }
        //当区查无内容时，查找市ID对应的客户区域ID
        $returnCity = DistrictLink::find()->select('district_id')->where(['city_id' => $city_id, 'area_id' => 0])->orderBy(['link_id' => SORT_DESC])->one();
        if(!empty($returnCity)) {
            return $returnCity['district_id'];
        }
        //当市查无内容时，查找省ID对应的客户区域ID
        $returnProvince = DistrictLink::find()->select('district_id')->where(['province_id' => $province_id, 'city_id' => 0, 'area_id' => 0])->orderBy(['link_id' => SORT_DESC])->one();
        if(!empty($returnProvince)) {
            return $returnProvince['district_id'];
        }
        return $districtId;
    }

}
