<?php

namespace app\admin\controller\manystore;

use app\admin\model\User;
use app\common\model\school\classes\Order;

use app\manystore\model\Manystore;
use app\manystore\model\ManystoreLog;
use app\manystore\model\ManystoreShop;
use app\manystore\model\ManystoreAuthGroup;
use app\manystore\model\ManystoreAuthGroupAccess;
use app\common\controller\Backend;
use fast\Random;
use fast\Tree;
use think\Exception;
use think\Hook;
use think\Validate;

/**
 * 管理员管理
 *
 * @icon fa fa-users
 * @remark 一个管理员可以有多个角色组,左侧的菜单根据管理员所拥有的权限进行生成
 */
class Index extends Backend
{

    /**
     * @var \app\manystore\model\Manystore
     */
    protected $model = null;
    protected $shopModel = null;
    protected $selectpageFields = 'id,username,nickname,avatar';
    protected $searchFields = 'id,username,nickname';
    protected $childrenGroupIds = [];
    protected $childrenAdminIds = [];


    //不用审核允许修改的字段
    protected $no_auth_fields = [ "name",'image','images','address_city','province',"city","district","address","address_detail",
        "longitude","latitude","content","desc"
    ];

    //更新数据是否需要触发审核开关
    protected $need_auth = false;
    protected $have_auth = false;

    protected $success_auth = false;
    protected $error_auth = false;


    public function _initialize()
    {
        parent::_initialize();

        $this->model = new Manystore();
        $this->shopModel = new ManystoreShop();
        $this->view->assign("statusList", $this->shopModel->getStatusList());
        $this->view->assign("typeList", $this->shopModel->getTypeList());
        $this->view->assign("shop_backend_url",  config("site.shop_backend_url"));

    }



    /**
     * 免登录进入机构后台
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\BindParamException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function free($ids = ''){
        $param = $this->request->param();
        if($this->request->isPost()){
//            try{
                if(isset($param['ids']))$ids = $param['ids'];
                //机构登录
                  //如果存在登录,先退出登录
                $auth = \app\manystore\library\Auth::instance();
                if($auth->isLogin()){
                    $auth->logout();
                    Hook::listen("manystore_logout_after", $this->request);
                }
                //执行登录
                ManystoreLog::setTitle(__('Login'));
                $result = $auth->freelogin($ids,  0);
                if ($result === true) {
                    Hook::listen("admin_login_after", $this->request);
                    $this->success(__('Login successful'), null, [ 'id' => $auth->id,  'avatar' => $auth->avatar]);
                } else {
                    $msg = $auth->getError();
                    $msg = $msg ? $msg : __('Username or password is incorrect');
                    $this->error($msg, null, ['token' => $this->request->token()]);
                }



//            }catch (\Exception $e){
//                $this->error($e->getMessage());
//            }

        }
        $row = $this->model->get($ids);
        $this->view->assign('vo', $row);
        return $this->view->fetch();
    }




    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage,则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();



            $total = $this->model
                ->with(['shop',"user"])
                ->where($where)
                ->where(array('is_main'=>1))
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['shop',"user"])
                ->where($where)
                ->where(array('is_main'=>1))
//                ->field(['password', 'salt', 'token'], true)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    protected function authClasses(&$params,&$shop,$row=null){
        //审核失败需填写原因
        if($shop["status"] == '2' && empty($shop["reason"])){
            $this->error("审核失败需填写原因");
        }

        if($shop["status"] == '2'){
            //审核不通过会平台下架
            $params["status"] = 'hidden';
        }

        //更新
        if($row){

            if($shop["status"] != '1' && $row["status"] == '1'){
                $this->error("审核已通过的课程不允许再修改审核状态!");
            }

            if($shop["status"] != '0' && $row["status"] == '0'){
                //填写审核时间和审核人
                $shop["auth_time"] = time();
                $shop["admin_id"] = $this->auth->id;
                if($shop["status"] == '1'){
                    //审核通过
                    $this->success_auth = true;
                }
                if($shop["status"] == '2'){
                    //审核通过
                    $this->error_auth = true;
                }
            }

            //审核通过
            if($this->success_auth){
                //如果是平台下架,则更新成正常下架
                if($params["status"] == 'hidden')$params["status"] = 'normal';

                //当前密码
//                $password = $params['password'] ? $params['password'] : \app\common\model\dyqc\ManystoreShop::getDefaultPassword($params["type"],$params["user_id"],$params);

                //调用通过事件
//                $data = ['shop' => $row,"password"=>$password];
//                \think\Hook::listen('shop_auth_success_after', $data);


            }
            if($this->error_auth){
                //审核不通过会平台下架
                $params["status"] = 'hidden';
                //调用通过事件
                //调用通过事件
//                $data = ['shop' => $row];
//                \think\Hook::listen('shop_auth_fail_after', $data);

            }


        }else{
            //新增
        }

    }


    protected function updateCheck($id,$params=[],$shop=[],$row=null){
        if($shop && $row){

            if(!$this->no_auth_fields_check($shop,$row)){
                return true;
            }
        }

        // 课程存在未完成订单则不允许操作
        $order = Order::where("manystore_id",$id)->where("status","in","0,3")->find();
        if($order)$this->error("存在正在使用中的课程订单或存在正在售后中的课程订单无法继续操作!");
        // 课程存在售后订单则不允许操作
    }



    protected function update_check(&$params,&$shop,$row=null)
    {



        $shop["user_id"] = $params["user_id"];
        if(!$shop["user_id"])throw new \Exception("认证用户不存在!");
        $user = User::get($shop["user_id"]);
        if(!$user) throw new \Exception("认证用户不存在!");



        //独立地点需传定位信息
//         if(empty($params["address_city"])
//                || empty($params["province"])
//                || empty($params["city"])
//                || empty($params["district"])
//                || empty($params["longitude"])
//                || empty($params["latitude"]))  $this->error("独立地点需传定位信息");



        //特有认证判断
        $this->authClasses($params,$shop,$row);
//        var_dump($row);die;


        //更新
        if($row){
            $this->have_auth = false;
            if($this->need_auth){
                //判断更新的变动数据
                $this->no_auth_fields_check($params,$shop,$row);

                if($this->have_auth){
                    //注释掉先不一刀切
//                    $params['status'] = "hidden";
                    $shop['status'] = "0";
                }
            }

            $this->updateCheck($row->id,$params,$shop,$row);


            //名称title不能与其他课程重复
            $check_title = $this->shopModel->where('id','<>',$row["id"])->where('name',$shop["name"])->find();
            if($check_title){
                $this->error("机构或个人认证名称已存在或被其他机构占用,请更改!");
            }
            //user_id不能与其他机构重复
            $check_user_id = $this->shopModel->where('id','<>',$row["id"])->where('user_id',$shop["user_id"])->find();
            if($check_user_id){
                $this->error("机构或个人认证用户已存在或被其他机构占用,请更改!");
            }

        }else{
            //新增


            //名称title不能重复
            $check_title = $this->shopModel->where('name',$shop["name"])->find();
            if($check_title){
                $this->error("机构或个人认证名称已存在或被其他机构占用,请更改!");
            }
            //user_id不能与其他机构重复
            $check_user_id = $this->shopModel->where('user_id',$shop["user_id"])->find();
            if($check_user_id){
                $this->error("机构或个人认证用户已存在或被其他机构占用,请更改!");
            }
        }

    }





    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            $shop = $this->request->post("shop/a");
            if ($params) {
                if (!Validate::is($params['password'], '\S{6,16}')) {
                    $this->error(__("Please input correct password"));
                }
                db()->startTrans();
                try{

                    $shop["user_id"] =  $params['user_id'];
                    $this->update_check($params,$shop,$row=null);
                    $shop_info = $this->shopModel->save($shop);
                    if($shop_info === false){
                        $this->error($this->shopModel->getError());
                    }

                    $params['shop_id'] = $this->shopModel->id;
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                    $params['avatar'] = '/assets/img/avatar.png'; //设置新管理员默认头像。
                    $params['is_main'] = 1;

                    $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                    $result = $this->model->validate($validate)->save($params);
                    if ($result === false) {
                        $this->error($this->model->getError());
                    }


                    $manystoreAuthGroupModel = new ManystoreAuthGroup();
                    $group = [];
                    $group['shop_id'] = $this->shopModel->id;
                    $group['name'] = '超级管理员';
                    $group['rules'] = '*';
                    $group['createtime'] = time();
                    $group['updatetime'] = time();
                    $group_id = $manystoreAuthGroupModel->insertGetId($group);
                    if(!$group_id){
                        $this->error('添加失败');
                    }

                    $manystoreAuthGroupAccessModel = new ManystoreAuthGroupAccess();
                    $group_access = [];
                    $group_access['uid'] = $this->model->id;
                    $group_access['group_id'] = $group_id;

                    $manystoreAuthGroupAccessModel->insert($group_access);

                    db()->commit();
                    $this->success();
                }catch (Exception $e){
                    db()->rollback();
                    $this->error($e->getMessage());
                }

            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids,'is_main'=>1]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $shop_info = $this->shopModel->get(array('id'=>$row['shop_id']));
        if(!$shop_info){
            $this->error(__('商家信息资料不存在'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            $shop = $this->request->post("shop/a");
            if ($params) {
                $shop["user_id"] =  $params['user_id'];
                $this->update_check($params,$shop,$shop_info);
                $result = $shop_info->save($shop);
                if($result === false){
                    $this->error(__("修改商家信息资料失败"));
                }

                if($this->success_auth){
                    //当前密码
                    $password = $params['password'] ? $params['password'] : \app\common\model\dyqc\ManystoreShop::getDefaultPassword($params["type"],$params["user_id"],$params);
                    //调用通过事件
                    $data = ['shop' => $row,"password"=>$password];
                    \think\Hook::listen('shop_auth_success_after', $data);
                }
                if($this->error_auth){

                    //调用通过事件
                    $data = ['shop' => $row];
                    \think\Hook::listen('shop_auth_fail_after', $data);
                }


                if ($params['password']) {
                    if (!Validate::is($params['password'], '\S{6,16}')) {
                        $this->error(__("Please input correct password"));
                    }
                    $params['salt'] = Random::alnum();
                    $params['password'] = md5(md5($params['password']) . $params['salt']);
                } else {
                    unset($params['password'], $params['salt']);
                }
                //这里需要针对username和email做唯一验证
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;

                $manystoreValidate = \think\Loader::validate($validate);
                $manystoreValidate->rule([
                    'username' => 'regex:\w{3,12}|unique:manystore,username,' . $row->id,
                    'email'    => 'require|email|unique:manystore,email,' . $row->id,
                    'password' => 'regex:\S{32}',
                ]);

                $result = $row->validate($validate)->save($params);
                if ($result === false) {
                    $this->error($row->getError());
                }

                $this->success();
            }
            $this->error();
        }
        $grouplist = $this->auth->getGroups($row['id']);
        $groupids = [];
        foreach ($grouplist as $k => $v) {
            $groupids[] = $v['id'];
        }
        $this->view->assign("row", $row);
        $this->view->assign("shop", $shop_info);
        $this->view->assign("groupids", $groupids);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $row = $this->model->get(['id' => $ids,'is_main'=>1]);
            if(!$row){
                $this->error(__('No Results were found'));
            }

            $this->updateCheck($ids);

            db()->startTrans();
            try{
                $result = $row->delete();
                if(!$result){
                    exception('账号信息删除失败');
                }
                $result =  $this->shopModel->where(array('id'=>$row['shop_id']))->delete();
                if(!$result){
                    exception('商家信息删除失败');
                }
                db()->commit();
                $this->success('删除成功');
            }catch (Exception $e){
                db()->rollback();
                $this->error($e->getMessage());
            }
        }
        $this->error(__('You have no permission'));
    }

    /**
     * 批量更新
     * @internal
     */
    public function multi($ids = "")
    {
        // 管理员禁止批量操作
        $this->error();
    }

    /**
     * 下拉搜索
     */
    public function selectpage()
    {
        $this->dataLimit = 'auth';
        $this->dataLimitField = 'id';
        return parent::selectpage();
    }
}