<?php

namespace app\manystoreapi\controller;

use app\common\controller\ManystoreApiBase;
use app\common\model\manystore\UserAuth as UserAuthmodel;
use app\common\model\User;
use app\manystore\model\Manystore;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 机构API后台：机构用户认证接口
 */
class UserAuth extends ManystoreApiBase
{
//    protected $noNeedLogin = ["detail",'people','spec',"teacher_list"];
//    protected $noNeedRight = '*';

    protected $model = null;

    /**
     * 初始化操作
     * @access protected
     */
    public function _initialize()
    {

        $this->model = new UserAuthmodel;
        parent::_initialize();

        //判断登录用户是否是员工
    }


    /**
     * @ApiTitle( 认证详情)
     * @ApiSummary(认证详情)
     * @ApiMethod(GET)
     * @ApiParams(name = "id", type = "int",required=true,description = "认证id")
     * @ApiReturn({
     *
     *})
     */
    public function detail(){
        $id = $this->request->get('id/d','');

        if(empty($id)){
            $this->apierror(__('缺少必要参数'));
        }

        try {
            $res =  $this->model->detail($id);
        } catch (\Exception $e){
//            Log::log($e->getMessage());
            $this->apierror($e->getMessage(),['errcode'=>$e->getCode()]);
        }
        $this->apisuccess('获取成功', ['detail' => $res]);
    }







    /**
     * @ApiTitle( 授权信息列表（取决于搜索条件）)
     * @ApiSummary(授权信息列表（取决于搜索条件）)
     * @ApiMethod(GET)
     * @ApiParams(name = "keywords", type = "string",required=false,description = "搜索关键字")
     * @ApiParams(name = "page", type = "string",required=true,description = "页数")
     * @ApiParams(name = "limit", type = "string",required=true,description = "条数")
     * @ApiParams(name = "status", type = "string",required=false,description = "授权状态:1=通过,2=拒绝")
     * @ApiParams(name = "shop_id", type = "int",required=false,description = "机构店铺id")
     * @ApiReturn({
     *
     *})
     */
    public function auth_list()
    {
        $user_id = 0;
        $user = $this->auth->getUser();//登录用户
        if($user)$user_id = $user['id'];
        $params=[
            "shop_id"=>$this->auth->shop_id,
        ];
        $page      =  $this->request->get('page/d', 0); //页数
        $limit   =  $this->request->get('limit/d', 0); //条数
        $params['status']  =  $this->request->get('status/s', ''); //搜索关键字
        $params['shop_id']  =  $this->request->get('shop_id/d', ''); //搜索关键字
        $params['user_id']  =  $user_id; //搜索关键字
        $params['keywords']  =  $this->request->get('keywords/s', ''); //搜索关键字

//        $type =  $this->request->get('type/s', ''); //筛选学员和教练单

        try{
            //当前申请状态
            $res =  $this->model::allList($page, $limit,$params);
//            if($user_id =='670153'){
//               file_put_contents("ceshi66.txt",(new AppointmentOrder())->getLastSql());
//            }
        }catch (\Exception $e){

            $this->apierror($e->getMessage());
        }
        $this->apisuccess('查询成功', $res);
    }





    /**
     * @ApiTitle( 生成用户账号)
     * @ApiSummary(根据手机号和昵称生成用户账号)
     * @ApiMethod(POST)
     * @ApiParams(name = "people_name", type = "string",required=false,description = "姓名")
     * @ApiParams(name = "people_mobile", type = "string",required=true,description = "手机号")
     * @ApiReturn({
     *
     *})
     */
    public function changeuser(){
        if($this->request->isPost())
        {
            try{
                $people_name = $this->request->param('people_name/s');
                $people_mobile = $this->request->param('people_mobile/s');
                $user = \app\common\model\User::where("mobile",$people_mobile)->find();
                //检测更新教练下单学员账号创建状态 2022/8/27 new
                if(!$user)$user = (new \app\common\model\User)->addUserByMobile($people_mobile,$people_name);
                $user['nickname'] = $people_name;
                $user->save();

                //添加用户机构认证
                try {
                    \app\common\model\manystore\UserAuth::auth(0,SHOP_ID,$user["id"],0,'shop',$this->auth->id);
                }catch (\Exception $e){

                }



            }catch (\Exception $e){
                $this->apierror($e->getMessage());
            }
            //退押金
            $this->apisuccess("已成功创建{$people_name}");
        }

    }





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

        // 课程存在售后订单则不允许操作
    }


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

        $shop_id = SHOP_ID;
        $manystore = Manystore::where("shop_id", $shop_id)->find();
        if (!$manystore) {
            $this->apierror("店铺不存在");
        }
//        $params["manystore_id"] = $manystore["id"];
        $params["shop_id"] = $shop_id;
        $user = User::where("nickname|realname|mobile", $params["user_id"])->find();
        if(!$user) $this->apierror("未找到用户请先让用户登录小程序再提交表单");
        $params["user_id"] = $user["id"];

        $user_id = $params["user_id"];
        //修改
        if($row){
            //用户已是其他的教师（搜索）
            $teacher_user =  $this->model->where("user_id",$user_id)->where("shop_id",$shop_id)->where("id","<>",$row["id"])->find();
            if($teacher_user){
                $this->apierror("已向用户发起过授权申请！");
            }
        }else{
            //新增
            //用户已是教师（搜索）
            $teacher_user =  $this->model->where("user_id",$user_id)->where("shop_id",$shop_id)->find();
            if($teacher_user){
                $this->apierror("已向用户发起过授权申请！");
            }
        }


    }



    /**
     * @ApiTitle( 添加认证)
     * @ApiSummary(添加认证)
     * @ApiMethod(POST)
     * @ApiParams(name = "user_id", type = "int",required=true,description = "认证用户id")
     * @ApiReturn({
     *
     *})
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {

                if($this->storeIdFieldAutoFill && STORE_ID ){
                    $params['store_id'] = STORE_ID;
                }

                if($this->shopIdAutoCondition && SHOP_ID){
                    $params['shop_id'] = SHOP_ID;
                }

                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $this->update_check($params,$row=null);
//                    $result = $this->model->allowField(true)->save($params);
                    $result = \app\common\model\manystore\UserAuth::auth(0,$params["shop_id"],$params["user_id"],0,'shop',$this->auth->id);

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->apierror($e->getMessage());
                }
                if ($result !== false) {
                    $this->apisuccess();
                } else {
                    $this->apierror(__('No rows were inserted'));
                }
            }
            $this->apierror(__('Parameter %s can not be empty', ''));
        }

    }


    /**
     * @ApiTitle( 认证删除)
     * @ApiSummary(认证删除)
     * @ApiMethod(POST)
     * @ApiParams(name = "ids", type = "int",required=true,description = "认证id")
     * @ApiReturn({
     *  微信小程序码图片流
     *})
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->apierror(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            if($this->shopIdAutoCondition){
                $this->model->where(array('shop_id'=>SHOP_ID));
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            foreach ($list as $item) {
                $this->updateCheck($item->id);
            }
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->apierror($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->apierror($e->getMessage());
            }
            if ($count) {
                $this->apisuccess();
            } else {
                $this->apierror(__('No rows were deleted'));
            }
        }
        $this->apierror(__('Parameter %s can not be empty', 'ids'));
    }






}

