<?php
namespace backend\modules\admin\controllers;

use backend\models\forms\MemberForm;
use backend\models\MemberApi;
use backend\models\MemberIdentity;
use backend\models\searches\MemberSearch;
use backend\models\SigninApi;
use common\helpers\Utils;
use Yii;
use yii\web\NotFoundHttpException;

class MemberController extends BaseController
{
    /**
     * 用户列表
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * 添加用户页面
     */
    public function actionAdd()
    {
        $id = Yii::$app->request->get('id', '');
        return $this->renderPartial('add', [
            'id' => $id,
        ]);
    }

    /**
     * 用户列表 ajax
     * @return \yii\web\Response
     */
    public function actionAjax()
    {
        $searchModel = new MemberSearch();
        $dataProvider = $searchModel->search(Yii::$app->getRequest()->getQueryParams(), 1);
        return $this->asJson($searchModel->outResult($dataProvider));
    }

    /**
     * 用户详情
     * @return string
     * @throws NotFoundHttpException
     */
    public function actionView()
    {
        try {
            $model = new MemberForm(Yii::$app->getRequest()->get('id'));
        } catch (\Exception $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
        return $this->render('view', [
            'member' => $model,
            'signins' => $this->findMemberSignins($model->id),
        ]);
    }

    /**
     * 锁定账户
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionAction()
    {
        try {
            $model = new MemberForm(Yii::$app->getRequest()->get('id'));
        } catch (\Exception $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
        $enable = trim(Yii::$app->getRequest()->get('enable'));
        $model->updateIsEnable($enable);
        return $this->redirect(['view', 'id' => $model->id]);
    }

    /**
     * 用户登录
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionLogin()
    {
        $id = intval(Yii::$app->getRequest()->get('id'));
        if ($id <= 0) {
            throw new NotFoundHttpException('用户不存在');
        }
        $member = $this->findMember($id, ['id', 'password']);
        setcookie(MemberIdentity::USER_LOGIN_ID_COOKIE, $member['id'], time() + 86400, '/', Utils::getTopDomain());
        setcookie(MemberIdentity::USER_LOGIN_TOKEN_COOKIE, $member['password'], time() + 86400, '/', Utils::getTopDomain());

        $host = Utils::getCrmHostByEnv();
        
        return $this->redirect($host . '/user/dashboard');
    }

    /**
     * 修改用户MT4账号
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionModifyLogins()
    {
        try {
            $model = new MemberForm(Yii::$app->getRequest()->post('id'));
        } catch (\Exception $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
        $logins = trim(Yii::$app->getRequest()->post('logins'));
        if ($model->updateLogins($logins)) {
            return $this->asJson(['isSuccess' => true, 'msg' => '操作成功']);
        } else {
            return $this->asJson(['isSuccess' => false, 'msg' => '操作失败']);
        }
    }

    /**
     * 修改用户密码
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionModifyPwd()
    {
        try {
            $model = new MemberForm(Yii::$app->getRequest()->post('id'));
        } catch (\Exception $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
        $pwd = trim(Yii::$app->getRequest()->post('pwd'));
        if ($model->updatePassword($pwd)) {
            return $this->asJson(['isSuccess' => true, 'msg' => '操作成功']);
        } else {
            return $this->asJson(['isSuccess' => false, 'msg' => '操作失败']);
        }
    }

    /**
     * 修改用户信息
     * @return \yii\web\Response
     * @throws NotFoundHttpException
     */
    public function actionModifyInfo()
    {
        try {
            $model = new MemberForm(Yii::$app->getRequest()->post('id'));
        } catch (\Exception $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
        if ($model->updateInfo(Yii::$app->getRequest()->post())) {
            return $this->asJson(['isSuccess' => true, 'msg' => '操作成功']);
        } else {
            return $this->asJson(['isSuccess' => false, 'msg' => '操作失败']);
        }
    }

    public function actionDelete()
    {
        try {
            $model = new MemberForm(Yii::$app->getRequest()->post('id'));
        } catch (\Exception $e) {
            throw new NotFoundHttpException($e->getMessage());
        }
        if ($model->delete()) {
            return $this->asJson(['isSuccess' => true, 'msg' => '操作成功']);
        } else {
            return $this->asJson(['isSuccess' => false, 'msg' => '操作失败']);
        }
    }

    /**
     * @param int $id
     * @param null|string $fields
     * @return mixed
     * @throws NotFoundHttpException
     */
    protected function findMember($id, $fields = null)
    {
        $api = new MemberApi();
        $result = $api->getMemberInfo($id, $fields);
        if ($result['code'] == 0) {
            throw new NotFoundHttpException($result['message']);
        } else {
            return $result['data'];
        }
    }

    /**
     * 获取用户登录信息
     * @param $memberId
     * @return array
     */
    protected function findMemberSignins($memberId)
    {
        $api = new SigninApi();
        $result = $api->getListByMemberId($memberId);
        if ($result['code'] == 0) {
            return [];
        } else {
            return $result['data']['dataList'];
        }
    }

    /**
     * 添加用户数据处理
     */
    public function actionSave()
    {
        $response = ['code' => 0, 'message' => '添加失败', 'data' => []];

        $model = new MemberForm(0, [], true);
        $model->setScenario('add_admin_member');
        $model->load(Yii::$app->request->post());
        if ($model->validate()) {
            $api = new MemberApi();
            $params = $model->attributes;
           // $isSendMail = Yii::$app->request->post('isSendMail');
           // $params['isSendMail'] = $isSendMail;
            $result = $api->addAdminMember($params);
            if ($result['code'] == 1) {
                $response['code'] = 1;
                $response['message'] = '添加成功';
            } else {
                $response['message'] = $result['message'];
                $response['data'] = $result['data'];
            }
        } else {
            $errors = $model->getFirstErrors();
            $error = reset($errors);
            $response['message'] = !empty($error) ? $error : '数据输入错误';
        }
        return json_encode($response);
    }
}


