<?php

namespace common\models;

use common\util\Util;
use fx\util\FxUtil;
use Yii;
use yii\db\ActiveRecord;
use yii\db\Exception;
use yii\db\Expression;

/**
 * This is the model class for table "fx_user".
 *
 * @property integer $uid
 * @property string $user_name
 * @property string $openid
 * @property string $phone
 * @property string $nickname
 * @property string $headimgurl
 * @property integer $sex
 * @property string $country
 * @property string $province
 * @property string $city
 * @property integer $status
 * @property string $reg_time
 * @property integer $delete_flag
 * @property string $wx_openid
 * @property integer $main_user_id
 */
class FxUser extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'fx_user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['openid'], 'required'],
            [['sex', 'status', 'delete_flag', 'main_user_id', 'change_price_power'], 'integer'],
            [['reg_time'], 'safe'],
            [['user_name'], 'string', 'max' => 100],
            [['openid', 'wx_openid'], 'string', 'max' => 120],
            [['phone'], 'string', 'max' => 11],
            [['nickname'], 'string', 'max' => 100],
            [['headimgurl', 'country', 'province', 'city', 'user_area'], 'string', 'max' => 255],
            [['openid'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'uid' => 'Uid',
            'user_name' => 'User Name',
            'openid' => 'Openid',
            'phone' => 'Phone',
            'nickname' => 'Nickname',
            'headimgurl' => 'Headimgurl',
            'sex' => 'Sex',
            'country' => 'Country',
            'province' => 'Province',
            'city' => 'City',
            'status' => 'Status',
            'reg_time' => 'Reg Time',
            'delete_flag' => 'Delete Flag',
            'wx_openid' => 'Wx Openid',
            'main_user_id' => 'Main User ID',
            'change_price_power' => 'change_price_power',
            'user_area' => 'user_area'
        ];
    }

    /**
     * Function Description:验证是否已注册手机号
     * Function Name: checkPhone
     *
     * @return array
     *
     * @author 娄梦宁
     */
    public function checkPhone()
    {
        $cookies = Yii::$app->request->cookies;
        $user_id = $cookies->getValue('user_id');
        $phone = self::find()->select('phone')
            ->where(['uid' => $user_id])
            ->one();
        return $phone;
    }

    /**
     * Function Description:注册手机号
     * Function Name: registerPhone
     * @param $phone
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function registerPhone($phone)
    {
        $values = [
            'phone' => $phone
        ];
        $base_one = self::findOne(['uid' => FxUtil::$uid, 'delete_flag' => 0]);
        $req = "/^.*[0-9a-zA-Z_\x{4e00}-\x{9fa5}].*$/u";
        if (Util::checkPattern('', $base_one->nickname, $req) == false) {//如果用户名是空则用户名设置为手机号
            $values['nickname'] = $phone;
        }
        $base_one->attributes = $values;
        $res = $base_one->update();
        if ($res === false) {
            return false;
        }
        return true;
    }

    /**
     * Des:根据openid获取用户ID
     * Name: getUidByOpenid
     * @param $openid
     * @return mixed|string
     * @author 倪宗锋
     */
    public function getInfoByOpenid($openid)
    {
        $getUserInfo = self::find()->select(['uid', 'phone', 'status'])
            ->where(array('openid' => $openid))
            ->asArray(true)
            ->one();
        if ($getUserInfo == null) {
            return '';
        }
        return $getUserInfo;
    }

    /**
     * Des:添加用户信息
     * Name: addUserFromWeChat
     * @param $params
     * @return bool
     * @throws \Exception
     * @throws bool
     * @author 倪宗锋
     */
    public function addUserFromWeChat($params)
    {
        $this->setAttributes($params);
        $return = $this->insert(true);
        return $return;
    }


    /**
     * Des:获取用户信息
     * Name: getUserInfoByUid
     * @param $uid
     * @return array|null|string|ActiveRecord
     * @author 倪宗锋
     */
    public function getUserInfoByUid($uid)
    {
        $userInfo = self::find()
            ->where(array('uid' => $uid))
            ->asArray(true)
            ->one();
        if ($userInfo == null) {
            return '';
        }
        return $userInfo;
    }

    /**
     * Function Description:获取分销商列表
     * Function Name: getUserList
     * @param $param
     *
     * @return array|\yii\db\ActiveRecord[]
     *
     * @author 娄梦宁
     */
    public function getUserList($param)
    {
        $where = ['and', ['!=', 'phone', '']];
        if (empty($param['wechat_name']) == false) {
            $where[] = ['like', 'nickname', $param['wechat_name']];
        }
        if (empty($param['fx_phone']) == false) {
            $where[] = ['like', 'phone', $param['fx_phone']];
        }
        if (empty($param['start_reg_time']) == false) {
            $where[] = ['>=', 'reg_time', $param['start_reg_time']];
        }
        if (empty($param['end_reg_time']) == false) {
            $where[] = ['<', 'reg_time', date('Y-m-d', strtotime("{$param['end_reg_time']} +1 day"))];
        }
        if (empty($param['main_user_id']) == false) {
            $where[] = ['=', 'a.main_user_id', $param['main_user_id']];
        }
        if (empty($param['user_area']) == false) {
            $where[] = ['=', 'a.user_area', $param['user_area']];
        }
        //果运营主体非1或空，则读取自身对应的订单数据，如果运营主体为空，或者运营主体是1则读取订单运营主体是0或1的订单
        $cookies = $_COOKIE;
        if (empty($cookies['user_main_corp']) == false && $cookies['user_main_corp'] != 1 && in_array(YII_ENV,['pro','dev'])) {
            $where[] = ['=', 'e.main_corp_id', $cookies['user_main_corp']];
        }
        $offset = ($param['current_page'] - 1) * $param['page_size'];
        $select = [
            'a.uid as fx_uid',
            new Expression('FORMAT(b.remaining_sum,0) as remaining_sum'),
            'a.nickname as wechat_name',
            "ifnull(a.user_name,'') user_name",
            'a.phone as fx_phone',
            'a.reg_time',
            'b.status as fx_status_id',
            "if(b.status=1,'已启用','未启用') as fx_status",
            'ifnull(b.total_commission,0) as total_commission',
            'ifnull(b.closed_commission,0) as  closed_commission',
            'ifnull(b.available_commission,0) available_commission',
            'change_price_power' => new Expression("SUBSTR(change_price_power FROM 1 FOR 1)"),//巴士自由行的改价权限
            'change_price_power_hotel' => new Expression("SUBSTR(change_price_power FROM 2 FOR 1)"),//酒店的改价权限
            'main_user_name' => new Expression("ifnull((SELECT user_name from main_corp_user WHERE id= a.main_user_id),'')"),
            'main_corp_name' => new Expression("ifnull((SELECT main_corp_name from main_corp_user WHERE id= a.main_user_id),'')"),
            'user_area' => new  Expression("ifnull((SELECT GROUP_CONCAT(area_name SEPARATOR '</br>') from fx_user_area WHERE FIND_IN_SET(area_id,a.user_area)),'')")
        ];
        $result = self::find()->select($select)
            ->from(self::tableName() . ' as a')
            ->innerJoin('fx_user_account as b', ' b.fx_uid=a.uid')
            ->leftJoin(MainCorpUser::tableName() . ' e', 'a.main_user_id = e.id')
            ->where($where)
            ->orderBy('a.reg_time desc')
            ->offset($offset)
            ->limit($param['page_size'])
            ->asArray()
            ->all();
        $result1 = self::find()->select('count(1) as count')
            ->from(self::tableName() . ' as a')
            ->innerJoin('fx_user_account as b', ' b.fx_uid=a.uid')
            ->leftJoin(MainCorpUser::tableName() . ' e', 'a.main_user_id = e.id')
            ->asArray()
            ->where($where)
            ->one();
        $result1 = $result1['count'];
        return ['list' => $result,
            'count' => $result1
        ];
    }

    /*
     * 分销商审核列表
     */
    public function CheckFxUser($param)
    {
        $where = ['and', ['=', 'a.delete_flag', '0']];
        if ($param['wechat_name'] != '') {
            $where[] = ['like', 'a.nickname', $param['wechat_name']];
        }
        if ($param['fx_phone'] != '') {
            $where[] = ['like', 'a.phone', $param['fx_phone']];
        }
        if ($param['start_reg_time'] != '') {
            $where[] = ['>=', 'a.reg_time', $param['start_reg_time']];
        }
        if ($param['end_reg_time'] != '') {
            $where[] = ['<', 'a.reg_time', date('Y-m-d', strtotime("{$param['end_reg_time']} +1 day"))];
        }
        if ($param['status'] != '') {
            $where[] = ['=', 'a.status', $param['status']];
        }
        if (empty($param['main_user_id']) == false) {
            $where[] = ['=', 'a.main_user_id', $param['main_user_id']];
        }
        if (empty($param['user_area']) == false) {
            $where[] = ['=', 'a.user_area', $param['user_area']];
        }
        //果运营主体非1或空，则读取自身对应的订单数据，如果运营主体为空，或者运营主体是1则读取订单运营主体是0或1的订单
        $cookies = $_COOKIE;
        if (empty($cookies['user_main_corp']) == false && !in_array($cookies['user_main_corp'], [1, 34])) {
            $where[] = ['=', 'e.main_corp_id', $cookies['user_main_corp']];
        }
        $offset = ($param['current_page'] - 1) * $param['page_size'];
        $select = [
            'a.nickname',
            "ifnull(a.user_name,'') user_name",
            'a.phone',
            'a.reg_time',
            "if(a.status = 1,'审核未通过',if(a.status=2,'审核通过','待审核')) as status_type",
            'a.uid as fx_uid',
            'a.status',
            'main_user_name' => new Expression("ifnull((SELECT user_name from main_corp_user WHERE id= a.main_user_id),'')"),
            'main_corp_name' => new Expression("ifnull((SELECT main_corp_name from main_corp_user WHERE id= a.main_user_id),'')")
        ];
        $result = self::find()->select($select)
            ->from(self::tableName() . ' a')
            ->leftJoin(MainCorpUser::tableName() . ' e', 'a.main_user_id = e.id')
            ->where($where)
            ->orderBy('a.reg_time desc')
            ->offset($offset)
            ->limit($param['page_size'])
            ->asArray()
            ->all();
        $result1 = self::find()->select('count(1) as count')
            ->from(self::tableName() . ' a')
            ->leftJoin(MainCorpUser::tableName() . ' e', 'a.main_user_id = e.id')
            ->asArray()
            ->where($where)
            ->one();
        $result1 = $result1['count'];
        return ['list' => $result,
            'count' => $result1
        ];
    }

    /*
     * 分销商审核通过
     */
    public function ThroughFxUser($fx_uid, $status)
    {
        $count = self::updateAll(['status' => $status], ['=', 'uid', $fx_uid]);
        return $count;
    }

    /**
     * Des:修改用户名
     * Name: updateUserName
     * @param $fx_uid
     * @param $user_name
     * @return int
     * @author 倪宗锋
     */
    public function updateUserName($fx_uid, $user_name)
    {
        $count = self::updateAll(['user_name' => $user_name], ['=', 'uid', $fx_uid]);
        return $count;
    }

    /**
     * Des:绑定运维负责人
     * Name: updateUserName
     * @param $fx_uid
     * @param $main_user_id
     * @return int
     * @author 倪宗锋
     */
    public function bindMainCorp($fx_uid, $main_user_id)
    {
        $count = self::updateAll(['main_user_id' => $main_user_id], ['=', 'uid', $fx_uid]);
        return $count;
    }

    /**
     * Des:获取用户详细
     * Name: getUserInfo
     * @param $fx_uid
     * @return array|null|ActiveRecord
     * @author 倪宗锋
     */
    public function getUserInfo($fx_uid)
    {
        $select = [
            'a.uid',
            'a.nickname',
            'a.phone',
            'a.main_user_id',
            'b.id',
            'b.user_name',
            'b.main_corp_id',
            'b.main_corp_name',
            'a.user_area'
        ];
        $info = self::find()->select($select)
            ->from(static::tableName() . ' a')
            ->leftJoin(MainCorpUser::tableName() . ' b', 'a.main_user_id = b.id')
            ->where(['=', 'a.uid', $fx_uid])
            ->asArray()
            ->one();
        return $info;
    }

    /**
     * Function Description:修改用户改价权限
     * Function Name: uptChangePricePower
     * @param $fx_uid
     * @param $change_price_power
     * @param  $type
     *
     * @return bool
     *
     * @author 娄梦宁
     */
    public function uptChangePricePower($fx_uid, $change_price_power, $type)
    {
//        print_r([$type,$change_price_power,$change_price_power]);die;
        try {
            self::updateAll(['change_price_power' => new Expression("INSERT(change_price_power,$type,1,$change_price_power)")], ['=', 'uid', $fx_uid]);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Des:修改用户名
     * Name: updateUserName
     * @param $fx_uid
     * @param $userArea
     * @return int
     * @author 倪宗锋
     */
    public function updateUserArea($fx_uid, $userArea)
    {
        $count = self::updateAll(['user_area' => $userArea], ['=', 'uid', $fx_uid]);
        return $count;
    }
}
