<?php  
namespace backend\controllers;

use backend\helpers\PaginationHelper;
use backend\helpers\ValidatorHelper;
use backend\models\Member;
use backend\models\Mt4Users;
use backend\models\Open;
use Yii;

class MemberController extends BaseController
{
    /**
     * 用户信息
     * @return \yii\web\Response
     */
    public function actionInfo()
    {
        $id = Yii::$app->getRequest()->get('id');
        $fields = Yii::$app->getRequest()->get('fields');
        if ($fields == null || trim($fields) === '') {
            $fields = Member::getTableSchema()->getColumnNames();
            unset($fields['password']);
        } elseif (!is_array($fields)) {
            $fields = preg_split('/\s*,\s*/', $fields, -1, PREG_SPLIT_NO_EMPTY);
        }
        $model = Member::find()->select($fields)->where(['id' => $id])->limit(1)->one();
        if ($model == null) {
            return $this->outJson(0, [], '用户不存在');
        }
        return $this->outJson(1, $model->getAttributes(), 'OK');
    }

    /**
     * 切换MT4账户
     * @return \yii\web\Response
     */
    public function actionSwitch()
    {
        $id = Yii::$app->getRequest()->get('id');
        $login = Yii::$app->getRequest()->get('login');
        /** @var Member $model */
        $model = Member::find()->where(['id' => $id])->limit(1)->one();
        if ($model == null) {
            return $this->outJson(0, [], '用户不存在');
        }
        $loginArr = explode(',', $model['logins']);
        if (in_array($login, $loginArr)) {
            $model->main_login = $login;
            if ($model->save()) {
                return $this->outJson(1, [], 'OK');
            } else {
                return $this->outJson(0, [], $model->getErrors());
            }
        } else {
            return $this->outJson(0, [], 'login不属于当前用户');
        }
    }
    
    /**
     * 获取下级代理商
     */
    public function actionGetIbs()
    {
        $id = (int) Yii::$app->request->get('id');
        $model = new Member();
        $ibs = $model->findChildrenIncludeSelf($id);
        return $this->outJson(1, $ibs, '');    
    }

    /**
     * @return \yii\web\Response
     */
    public function actionCheckemailexist()
    {
        $email = trim(Yii::$app->getRequest()->get('email'));
        if ($email == '') {
            return $this->outJson(0, [], '邮箱不能为空');
        }
        //if (Member::checkEmailExist($email) || Open::checkEmailExist($email)) {
        if (Member::checkEmailExist($email)) {
            return $this->outJson(0, [], '邮箱已被注册');
        }
        return $this->outJson(1, [], '邮箱未被注册');
    }

    /**
     * @return \yii\web\Response
     */
    public function actionCheckidnoexist()
    {
        $idNo = trim(Yii::$app->getRequest()->get('id_no'));
        if ($idNo == '') {
            return $this->outJson(0, [], '身份证不能为空');
        }
       // if (Member::checkIdNoExist($idNo) || Open::checkIdNoExist($idNo)) {
        if (Member::checkIdNoExist($idNo)) {
            return $this->outJson(0, [], '身份证已被注册');
        }
        return $this->outJson(1, [], '身份证未被注册');
    }

    /**
     * 名下代理详情页
     */
    public function actionGetView()
    {
        $model = new Member();
        $result = $model->getView(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }

    /**
     * 用户列表
     * @return \yii\web\Response
     */
    public function actionList()
    {
        $data = Yii::$app->getRequest()->get();
        $data['type'] = isset($data['type']) ? trim($data['type']) : '';
        $data['search'] = isset($data['search']) ? trim($data['search']) : '';
        $data['page'] = isset($data['page']) ? max(intval($data['page']), 1) : 1;
        $data['pageSize'] = isset($data['pageSize']) ? intval($data['pageSize']) : 20;
        $data['orderBy'] = isset($data['orderBy']) ? trim($data['orderBy']) : 'id desc';
        $data = ValidatorHelper::validateData($data, [
            ['type', 'required'],
            ['search', 'string'],
            ['page', 'integer', 'min' => 1],
            ['pageSize', 'integer', 'min' => 1],
            ['orderBy', 'string'],
        ], $errors);
        if ($data == false) {
            return $this->outJson(0, '', $errors);
        }
        $query = Member::find()->orderBy($data['orderBy']);
        $query->andWhere(['type' => $data['type']]);
        $query->andFilterWhere(['or',
            ['like', 'username', $data['search']],
            ['like', 'name', $data['search']],
            ['like', 'ip', $data['search']],
            ['like', 'logins', $data['search']],
        ]);
        $result = PaginationHelper::queryPage($query, $data['page'], $data['pageSize']);
        return $this->outJson(1, $result);
    }

    /**
     * 修改用户信息
     * @return \yii\web\Response
     */
    public function actionUpdate()
    {
        $id = intval(Yii::$app->getRequest()->post('id'));
        if ($id <= 0) {
            return $this->outJson(0, [], '未指定数据对象');
        }
        /** @var Member $member */
        $member = Member::find()->where(['id' => $id])->one();
        if ($member == null) {
            return $this->outJson(0, [], '用户不存在');
        }
        $data = Yii::$app->getRequest()->post();
        if(isset($data['password']) && trim($data['password']) != '') {
            $data['password'] = $member->hash($data['password']);
        } else {
            unset($data['password']);
        }

        $transaction = Member::getDb()->beginTransaction();
        
        try {
            // 修改了ref_id的话，同时也修改ref_path，同时修改他下级代理的ref_path
            if (!empty($data['ref_id'])) {
                $ref = Member::find()->where(['id' => intval($data['ref_id'])])->limit(1)->asArray()->one();
                if ($ref) {
                    $data['ref_path'] = rtrim($ref['ref_path'], ',') . ',' . $ref['id'] . ','; // 以逗号结尾

                    $model = new Member();
                    $ibs = $model->findChildrenIncludeSelf($id);
                    foreach ($ibs as $k => $v) {
                        // 把代理其下级代理商的原上级代理的父辈结构改成新代理的父辈结构加上上级代理本身
                        // 例如，当前代理为260，ref_path为“70,75,1204,”，
                        // 某个下级代理为491，ref_path为“70,75,1204,260,500,”
                        // 260的上级代理改成1509，那么其ref_path改成“70,1196,67,1482,1509,”
                        // 491的ref_path改成“70,1196,67,1482,1509,260,500,”
                        $ibModel = Member::find()->where(['id' => $v['id']])->limit(1)->one();
                        $ibModel->ref_path = ltrim(str_replace(','.$member->ref_path, ','.$data['ref_path'], ','.$ibModel->ref_path), ',');
                        $ibModel->save();
                    }
                } else {
                    unset($data['ref_id']);
                }
            }

            $member->setAttributes($data);
            $res = $member->save();

            $transaction->commit();
        } catch (\Exception $e) {
            $res = false;
            
            $transaction->rollBack();
        }
        
        if ($res) {
            return $this->outJson(1, $member->getAttributes(null, ['password']), '操作成功');
        } else {
            return $this->outJson(0, [], '操作失败');
        }
    }

    /**
     * 后台代理商列表数据
     * @return array
     */
    public function actionAdminIbList()
    {
        $model = new Member();
        $result = $model->getAdminIbList(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }
    
    /**
     * 后台添加代理商
     * @return array
     */
    public function actionAddAdminIb()
    {
        $model = new Member();
        $result = $model->addAdminIb(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, $result['data'], $result['message']);
        }
    }

    /**
     * 后台添加用户
     * @return array
     */
    public function actionAddAdminMember()
    {
        $model = new Member();
        $result = $model->addAdminMember(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, $result['data'], $result['message']);
        }
    }

    /**
     * 后台代理商名下客户列表数据
     * @return array
     */
    public function actionAdminIbUsersList()
    {
        $model = new Mt4Users();
        $post = Yii::$app->request->post();
        $post['member_id'] = $post['id'];
        unset($post['id']);
        $result = $model->getList($post, false);
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }

    /**
     * 后台代理商详情页
     */
    public function actionGetAdminIbView()
    {
        $model = new Member();
        $result = $model->getAdminIbView(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }

    /**
     * 后台管理员列表数据
     * @return array
     */
    public function actionAdminAdminList()
    {
        $model = new Member();
        $result = $model->getAdminAdminList(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }

    /**
     * 后台添加管理员
     * @return array
     */
    public function actionAddAdminAdmin()
    {
        $model = new Member();
        $result = $model->addAdminAdmin(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }

    /**
     * 后台编辑管理员
     * @return array
     */
    public function actionEditAdminAdmin()
    {
        $model = new Member();
        $result = $model->editAdminAdmin(Yii::$app->request->post());
        if ($result['code']) {
            return $this->outJson(1, $result['data']);
        } else {
            return $this->outJson(0, [], $result['message']);
        }
    }
    
    public function actionDelete()
    {
        $id = intval(Yii::$app->getRequest()->post('id'));
        if ($id <= 0) {
            return $this->outJson(0, [], '参数非法');
        }
        $result = Member::deleteById($id);
        if ($result['code'] == 1) {
            return $this->outJson(1, [], $result['message']);
        } else {
            return $this->outJson(0,$result['data'], $result['message']);
        }
    }

    /**
     * 通过logins获取member_id
     */
    public function actionGetIdByLogin()
    {
        $login = Yii::$app->getRequest()->get('login');
        $rs = Member::findByLogin($login, 2);
        return $this->outJson(1, $rs['id']);
    }
}

