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

use backend\models\searches\CommissionSearch;
use common\helpers\ExcelHelper;
use common\helpers\UserAgentHelper;
use Yii;
use backend\models\MemberApi;
use backend\models\forms\MemberForm;
use backend\models\MemberIdentity;
use common\helpers\Utils;
use yii\web\NotFoundHttpException;
use backend\models\forms\CommissionForm;
use backend\models\CommissionApi;
use yii\helpers\Url;
use backend\models\MemberBankInfoApi;

/**
 * 代理商管理
 */
class IbController extends BaseController
{

    /**
     * 列表页
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * AJAX获取数据
     */
    public function actionAjax()
    {
        $get = Yii::$app->request->get();
        $orderInt = isset($get['order'][0]['column']) ? (int) $get['order'][0]['column'] : 1;
        $order = isset($get['columns'][$orderInt]['data']) ? $get['columns'][$orderInt]['data'] : '';
        $orderBy = isset($get['order'][0]['dir']) ? $get['order'][0]['dir'] : 'desc';
        $search = isset($get['search']['value']) ? trim($get['search']['value']) : '';

        $start = isset($get['start']) ? (int) $get['start'] : 0;
        $length = isset($get['length']) ? (int) $get['length'] : 20;
        $draw = isset($get['draw']) ? $get['draw'] : 1;

        $params = [
            'order' => $order,
            'orderBy' => $orderBy,
            'search' => $search,
            'start' => $start,
            'length' => $length,
            'draw' => $draw,
        ];

        if ($params['length'] > 5000) {
            if (Yii::$app->getRequest()->getIsAjax()) {
                Yii::$app->getResponse()->redirect(Url::current(), UserAgentHelper::isIE() ? 200 : 302);
            } else {
                $this->exportXls($params);
            }
            Yii::$app->end();
        }

        $api = new MemberApi();
        $result = $api->getAdminIbList($params);
        echo json_encode($result['data']);
    }
    
    /**
     * 添加代理商页面
     */
    public function actionAdd()
    {
        $id = Yii::$app->request->get('id', '');
        return $this->renderPartial('add', [
            'id' => $id,
        ]);
    }
    
    /**
     * 添加代理商数据处理
     */
    public function actionSave()
    {
        $response = ['code' => 0, 'message' => '添加失败', 'data' => []];

        $model = new MemberForm(0, [], true);
        $model->setScenario('add_admin_ib');
        $model->load(Yii::$app->request->post());
        if ($model->validate()) {
            $api = new MemberApi();
            $params = $model->attributes;
            //$isSendSms = Yii::$app->request->post('isSendSms');
            //$params['isSendSms'] = $isSendSms;
            $result = $api->addAdminIb($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);
    }
    
    /**
     * 名下代理
     */
    public function actionTree()
    {
        $id = (int) Yii::$app->request->get('id');
        
        $api = new MemberApi();
        $ibs = $api->getIbs($id)['data'];

        $member = [];
        $list = [];
        if ($ibs) {
            $ibs2 = [];
            foreach ($ibs as $k => $v) {
                if ($v['id'] == $id) {
                    $member = $v;
                }
                $ibs2[$v['id']] = $v;
            }
            $ibs = $ibs2;

            foreach ($ibs as $k => $v) {
                $ibs[$v['ref_id']]['sub'][$k] = &$ibs[$k];
            }

            $list = isset($ibs[$member['id']]['sub']) ? $ibs[$member['id']]['sub'] : [];
        }

        return $this->renderPartial('tree', [
            'member' => $member,
            'list' => $list,
        ]);
    }
    
    /**
     * 名下客户
     */
    public function actionUsers()
    {
        $id = (int) Yii::$app->request->get('id');
        
        return $this->render('users', [
            'id' => $id,
        ]);
    }
    
    /**
     * 名下客户
     */
    public function actionUsersAjax()
    {
        $get = Yii::$app->request->get();
        $id = isset($get['id']) ? $get['id'] : 0;
        $orderInt = isset($get['order'][0]['column']) ? (int) $get['order'][0]['column'] : 1;
        $order = isset($get['columns'][$orderInt]['data']) ? $get['columns'][$orderInt]['data'] : '';
        $orderBy = isset($get['order'][0]['dir']) ? $get['order'][0]['dir'] : 'desc';
        $search = isset($get['search']['value']) ? trim($get['search']['value']) : '';

        $start = isset($get['start']) ? (int) $get['start'] : 0;
        $length = isset($get['length']) ? (int) $get['length'] : 20;
        $draw = isset($get['draw']) ? $get['draw'] : 1;

        $params = [
            'id' => $id,
            'order' => $order,
            'orderBy' => $orderBy,
            'search' => $search,
            'start' => $start,
            'length' => $length,
            'draw' => $draw,
        ];

        $api = new MemberApi();
        $result = $api->getAdminIbUsersList($params);
        echo json_encode($result['data']);
    }

    /**
     * 名下代理详细
     */
    public function actionView()
    {
        $id = (int) Yii::$app->request->get('id');

        $params = [
            'id' => $id,
        ];

        $api = new MemberApi();
        $result = $api->getAdminIbView($params);
        if ($result['code'] == 0) {
            throw new NotFoundHttpException($result['message']);
        }

        $data = $result['data'];

        return $this->render('view', [
            'member' => $data['member'],
            'signins' => $data['signins'],
            'bank_info' => $data['bank_info'],
        ]);
    }
    
    /**
     * 启用或锁定账户
     */
    public function actionAction()
    {
        $id = (int) Yii::$app->request->get('id');
        $isEnable = (int) Yii::$app->request->get('enable');
        
        if ($isEnable && $isEnable != 1) {
            $isEnable = 1;
        }

        $api = new MemberApi();
        $result = $api->updateMemberEnable($id, $isEnable);
        
        return $this->redirect('/admin/ib/view?id=' . $id);
    }


    /**
     * 删除用户 
     * @return \yii\web\Response
     */
    public function actionDelete()
    {
        $id = (int) Yii::$app->request->post('id');
        $api = new MemberApi();
        $result = $api->deleteMember($id);
        if ($result['code'] == 1) {
            return $this->asJson(['isSuccess' => true, 'msg' => $result['message']]);
        }
        return $this->asJson(['isSuccess' => false, 'msg' => $result['message']]);
    }

    /**
     * 跳转登录到ib模块
     */
    public function actionLogin()
    {
        $id = (int) Yii::$app->request->get('id');
        if ($id <= 0) {
            throw new NotFoundHttpException('用户不存在');
        }

        $api = new MemberApi();
        $result = $api->getMemberInfo($id, ['id', 'password']);
        if ($result['code'] == 0) {
            throw new NotFoundHttpException('用户不存在.');
        }

        $member = $result['data'];
        if ($member) {
            setcookie(MemberIdentity::IB_LOGIN_ID_COOKIE, $member['id'], time() + 86400, '/', Utils::getTopDomain());
            setcookie(MemberIdentity::IB_LOGIN_TOKEN_COOKIE, $member['password'], time() + 86400, '/', Utils::getTopDomain());
            setcookie(MemberIdentity::ADMIN_LOGIN_ID_COOKIE, Yii::$app->user->id, time() + 86400, '/', Utils::getTopDomain());
        }

        $host = Utils::getCrmHostByEnv();
        
        return $this->redirect($host . '/ib/dashboard');
    }
    
    /**
     * 修改logins
     */
    public function actionModifyLogins()
    {
        $id = (int) Yii::$app->request->post('id');
        $logins = Yii::$app->request->post('logins');

        $api = new MemberApi();
        $result = $api->updateMemberLogins($id, $logins);

        $result['message'] = $result['code'] == 1 ? '修改成功' : '修改失败';
        return json_encode($result);
    }

    /**
     * 修改密码
     */
    public function actionModifyPwd()
    {
        $id = (int) Yii::$app->request->post('id');
        $pwd = Yii::$app->request->post('pwd');

        $api = new MemberApi();
        $result = $api->updateMemberPassword($id, $pwd);

        $result['message'] = $result['code'] == 1 ? '修改成功' : '修改失败';
        return json_encode($result);
    }

    /**
     * 修改资料
     */
    public function actionModifyInfo()
    {
        $post = Yii::$app->request->post();
        $id = isset($post['id']) ? intval($post['id']) : 0;
        $data = [
            'ref_id' => isset($post['ref_id']) ? intval($post['ref_id']) : 0,
            'username' => isset($post['username']) ? trim($post['username']) : '',
            'name' => isset($post['name']) ? trim($post['name']) : '',
            'id_no' => isset($post['id_no']) ? trim($post['id_no']) : '',
            'address' => isset($post['address']) ? trim($post['address']) : '',
            'mobile' => isset($post['mobile']) ? trim($post['mobile']) : '',
            'gender' => isset($post['gender']) ? intval($post['gender']) : '',
            'birthday' => isset($post['birthday']) ? trim($post['birthday']) : '',
        ];  

        $api = new MemberApi();
        $result = $api->updateMember($id, $data);

        $result['message'] = $result['code'] == 1 ? '修改成功' : '修改失败';
        return json_encode($result);
    }

    /**
     * 批量设置返佣规则
     */
    public function actionCommissionVolumeSet()
    {
        $memberId = (int) Yii::$app->request->get('memberId');
        $api = new MemberApi();
        $member = $api->getMemberInfo($memberId)['data'];
        return $this->renderPartial('commissionVolumeSet', [
            'member' => $member,
        ]);
    }

    /**
     * 批量设置返佣规则
     */
    public function actionCommissionVolumeSetAjax()
    {
        $response = ['code' => 0, 'message' => '设置失败', 'data' => []];

        $ibMemberId = (int) Yii::$app->request->post('ibMemberId');
        $setType = Yii::$app->request->post('setType');
        $subordinateIbLogins = (int) Yii::$app->request->post('subordinateIbLogins');
        if (!$ibMemberId) {
            $response['message'] = '参数错误';
            return json_encode($response);
        }
        if (!in_array($setType, ['direct', 'indirect'])) {
            $response['message'] = '请先选择设置类型';
            return json_encode($response);
        }
        if ($setType == 'indirect' && !$subordinateIbLogins) {
            $response['message'] = '请输入需要设置差佣的下级代理';
            return json_encode($response);
        }

        $model = new CommissionForm();
        $model->setScenario('admin_batch_set');
        $model->load(Yii::$app->request->post());
        if ($model->validate()) {
            $api = new CommissionApi();
            $params = $model->attributes;
            $params['userId'] = Yii::$app->user->identity->getId();
            $params['ibMemberId'] = $ibMemberId;
            $params['setType'] = $setType;
            $params['subordinateIbLogins'] = $subordinateIbLogins;
            $result = $api->batchSet($params);
            if ($result['code'] == 1) {
                $response['code'] = 1;
                $response['message'] = '操作成功';
            } else {
                $response['message'] = $result['message'];
            }
        } else {
            $errors = $model->getFirstErrors();
            $error = reset($errors);
            $response['message'] = !empty($error) ? $error : '数据输入错误';
        }
        return json_encode($response);
    }

    /**
     * 查看返佣规则记录
     */
    public function actionCommissionLog()
    {
        $id = Yii::$app->request->get('id', '');
        $member = new MemberApi();
        $info = $member->getMemberInfo($id);
        return $this->render('commission-log', [
            'id' => $id,
            'name' => $info['data']['name'],
        ]);
    }

    public function actionCommissionLogAjax()
    {
        $data = Yii::$app->request->get();
        $data['memberId'] = isset($data['id']) ? intval($data['id']) : '';
        $api = new CommissionSearch();
        $result = $api->search($data);
        return $this->asJson($api->outResult($result));
    }

    /**
     * 获取代理商列表，在设置上级代理商时给用户查询
     * @return string
     * @see \backend\modules\admin\controllers\UserController::actionIbs() 参考该方法
     */
    public function actionIbs()
    {
        return $this->renderPartial('ibs');
    }

    /**
     * @param array $params
     */
    protected function exportXls($params)
    {
        ExcelHelper::init();
        $attachmentName = "代理商管理_" . date('Y-m-d') . '.xlsx';
        $header = ['ID', '上级代理商', '用户名', '账户', '邮箱', '姓名', '手机', '状态', '注册时间'];
        $source = [];
        $api = new MemberApi();
        $isEnableMap = [
            0 => '禁用',
            1 => '启用',
        ];
        $params['length'] = 5000;
        while (true) {
            $result = $api->getAdminIbList($params);
            if ($result['code'] == 1 && !empty($result['data']['data'])) {
                foreach ((array)$result['data']['data'] as $key => $row) {
                    $isEnable = isset($isEnableMap[$row['is_enable']]) ? $isEnableMap[$row['is_enable']] : '';
                    $inTime = date('Y-m-d H:i:s', intval($row['in_time'] / 1000));
                    $arr = [];
                    $arr[] = $row['id'];
                    $arr[] = $row['IBNAME'];
                    $arr[] = $row['ib_old_login_name'];
                    $arr[] = $row['logins'];
                    $arr[] = $row['username'];
                    $arr[] = $row['name'];
                    $arr[] = $row['mobile'];
                    $arr[] = $isEnable;
                    $arr[] = $inTime;
                    $source[] = $arr;
                }
            } else {
                break;
            }
            $params['start'] += $params['length'];
            if ($params['start'] >= $result['data']['recordsTotal']) {
                break;
            }
        }
        ExcelHelper::output($source, $header, $attachmentName);
    }

    /**
     * 修改银行资料
     */
    public function actionModifyBankInfo()
    {
        $post = Yii::$app->request->post();

        $api = new MemberBankInfoApi();
        $params = array_merge($post, ['member_type' => MemberIdentity::MEMBER_TYPE_IB]);
        $result = $api->update($params);

        return json_encode($result);
    }
}




