<?php

namespace app\common\model\dyqc;

use app\admin\model\Admin;
use app\common\library\Virtual;
use app\common\model\BaseModel;
use app\common\model\manystore\ShopApply;
use app\common\model\school\Area;
use app\common\model\school\classes\activity\Activity;
use app\common\model\school\classes\ClassesLib;
use app\common\model\school\classes\Teacher;
use app\common\model\school\classes\Verification;
use app\common\model\school\SearchCity;
use app\common\model\User;
use app\manystore\model\Manystore;
use app\manystore\model\ManystoreApiAuthGroup;
use app\manystore\model\ManystoreApiAuthGroupAccess;
use app\manystore\model\ManystoreAuthGroup;
use app\manystore\model\ManystoreAuthGroupAccess;
use fast\Random;
use think\Cache;
use think\Model;


class ManystoreShop extends BaseModel
{

    

    

    // 表名
    protected $name = 'manystore_shop';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'type_text',
        'status_text',
        'auth_time_text',
        'create_time_text',
        'update_time_text'
    ];

    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }



    // 拼音对象
    protected static $pinyin = null;

    protected static function init()
    {
        self::$pinyin = new \Overtrue\Pinyin\Pinyin('Overtrue\Pinyin\MemoryFileDictLoader');

    }


    /** 专家团队
     * @return \think\model\relation\HasMany
     */
    public function teachers()
    {
        return $this->hasMany(Teacher::class,'shop_id')->where("status","1")->order("weigh desc");
    }







    public function getLogoAttr($value, $data)
    {
        if (!empty($value)) return cdnurl($value, true);
    }


    public function getImageAttr($value, $data)
    {
        if (!empty($value)) return cdnurl($value, true);
    }


    public function getImagesAttr($value, $data)
    {
        $imagesArray = [];
        if (!empty($value)) {
            $imagesArray = explode(',', $value);
            foreach ($imagesArray as &$v) {
                $v = cdnurl($v, true);
            }
            return $imagesArray;
        }
        return $imagesArray;
    }


    public function getYyzzImagesAttr($value, $data)
    {
        $imagesArray = [];
        if (!empty($value)) {
            $imagesArray = explode(',', $value);
            foreach ($imagesArray as &$v) {
                $v = cdnurl($v, true);
            }
            return $imagesArray;
        }
        return $imagesArray;
    }






    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1'), '2' => __('Status 2')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getAuthTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['auth_time']) ? $data['auth_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setAuthTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'admin_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function checkFull($id){
        $self = $this->get($id,['teachers']);
        if($self){
            if(empty($self["address_city"])
                || empty($self["province"])
                || empty($self["city"])
                || empty($self["district"])
                || empty($self["longitude"])
                || empty($self["latitude"])
                || empty($self["name"])
                || empty($self["image"])
                || empty($self["images"])
                || empty($self["content"])
                || empty($self["tel"])
                ||  empty($self["logo"])
            ) return false;

            return true;
        }
        return false;
    }

    public function checkFullMsg($id){
        if($id && $this->checkFull($id)){
            //必要信息已完善
           return '<div class="alert alert-success-light">
           <b >必要展示信息已完善！可正常上架课程！</b></div>';
        }else{
            //必要信息未完善
           return "<div class='alert alert-danger-light'><b>必要展示信息未完善，请先在机构完善展示信息</b><br><br>
             
              <span>必要展示信息为： </span><br><br><br>
              <span>1：地址信息：包括详细地址、所在城市、所在省、所在市、所在县、经纬度</span><br>
              <span>2：申请人姓名|机构名称</span><br>
              <span>3：logo</span><br>
              <span>4：封面图</span><br>
              <span>5：环境图片</span><br>
              <span>6：服务电话</span><br>
              <span>7：详情</span><br><br><br>
              <b>请您确保上述信息均已完善后才能正常上架课程。 </b><br><br>
              <b>若已完善请您刷新页面。 </b><br><br>
             </div>
";
        }
    }




    /** 机构详情
     * @param $id
     * @throws \think\exception\DbException
     */
    public function detail($id){
        $self = $this->get($id,['teachers']);
        if(!$this->checkFull($id))throw new \Exception("当前机构未完善信息，暂时无法展示！");


        //一对多隐藏字段方法
//        foreach ($self['teachers'] as $k=>$v){
//            $v->visible(['id','name','expert_image','expert_content']);
//        }
//        $self->visible(['id','name','expert_image','expert_content']);
        $self["hot"] = $this->getHotClasses($id,$limit=5);
        return $self;
    }


    public function getHotClasses($id,$limit=5){
          $data = ClassesLib::where("shop_id",$id)
              ->where("status",'1')
              ->limit($limit)
              ->order("hot desc,weigh desc")
              ->field("title,headimage,price,hot,weigh")
              ->select();
       return $data;
    }







    /**申请机构
     * @param $type 申请类型 类型:1=个人,2=机构
     * @param int $user_id 申请人
     * @param $params 申请参数
     * @param bool $check
     * @param bool $trans
     * @return bool
     * @throws \Exception
     */
    public  function apply($type,$user_id=0,$params=[],$check=false,$trans=false){

        if($check){
            $user = User::get($user_id);
            if(!$user)throw new \Exception("用户不存在");
            //已经是机构
            $shop = ManystoreShop::where( 'user_id',$user_id)->where("status","1")->find();
            if($shop)throw new \Exception("已申请机构，请勿重复申请");

            //验证参数
            //$type 1=个人,2=机构
            if(!in_array($type,['1','2']))throw new \Exception("类型参数错误");

            if(!in_array($params['gender'],[0,1]))throw new \Exception("年龄参数错误");



            //switch不同类型type做不同验证
            //未传手机号则默认用户手机号
            if(empty($params['tel'])) $params['tel'] = $user['mobile'];

            switch ($type) {
                case '1': //个人
                    $rule = [
                    'name' => 'require',
                    'tel' => 'require|number',
//                    'desc' => 'require',
                    'front_idcard_image' => 'require',
                    'reverse_idcard_image' => 'require',

                    'address' => 'require',
//                    'address_detail' => 'require',
                     'longitude' => 'require',
                     'latitude' => 'require',
                     'province' => 'require',
                     'city' => 'require',
                     'district' => 'require',

                        'gender'=> 'require',
                        'nation'=> 'require',
                        'out_look'=> 'require',
                        'birthtime'=> 'require',
                        'native_place'=> 'require',
                        'card_number'=> 'require',





                    ];
                   $rule_msg = [
                    'name.require' => '姓名必须填写',
                    'tel.require' => '服务电话必须填写',
                    'tel.number' => '服务电话必须是数字',
//                    'desc.require' => '申请备注必须填写',
                    'front_idcard_image.require' => '身份证正面必须上传',
                    'reverse_idcard_image.require' => '身份证反面必须上传',
                     'address.require' => '地址必填',
//                     'address_detail.require' => '详细地址必填',
                     'longitude.require' => '经度必填',
                     'latitude.require' => '纬度必填',
                     'province.require' => '省编号必填',
                     'city.require' => '市编号必填',
                     'district.require' => '县区编号必填',


                        'gender.require'=> '个人性别必填',
                        'nation.require'=> '个人民族必填',
                        'out_look.require'=> '个人政治面貌必填',
                        'birthtime.require'=> '个人出生日期必填',
                        'native_place.require'=> '个人籍贯必填',
                        'card_number.require'=> '个人身份证号码必填',

                   ];
                    break;
                case '2': //机构

                    $rule = [
                        'name' => 'require',
                        'tel' => 'require|number',
//                    'desc' => 'require',
                        'front_idcard_image' => 'require',
                        'reverse_idcard_image' => 'require',
                        'images' => 'require',
                        'yyzz_images' => 'require',
//                        'yyzzdm'  => 'require',


                         'address' => 'require',
//                         'address_detail' => 'require',
                         'longitude' => 'require',
                         'latitude' => 'require',
                         'province' => 'require',
                         'city' => 'require',
                         'district' => 'require',

//                        'establish_time' => 'require',
//                        'people' => 'require',


                        'gender'=> 'require',
                        'nation'=> 'require',
                        'out_look'=> 'require',
                        'birthtime'=> 'require',
                        'native_place'=> 'require',
                        'card_number'=> 'require',

                    ];

                    $rule_msg = [
                         'address.require' => '地址必填',
//                         'address_detail.require' => '详细地址必填',
                         'longitude.require' => '经度必填',
                         'latitude.require' => '纬度必填',
                         'province.require' => '省编号必填',
                         'city.require' => '市编号必填',
                         'district.require' => '县区编号必填',
                         'name.require' => '机构名称必须填写',
                         'tel.require' => '服务电话必须填写',
                         'tel.number' => '服务电话必须是数字',
//                    'desc.require' => '申请备注必须填写',
                        'front_idcard_image.require' => '法人身份证正面必须上传',
                        'reverse_idcard_image.require' => '法人身份证反面必须上传',
                        'images.require' => '机构环境照片必须上传',
                        'yyzz_images.require' => '营业执照照片必须上传',
//                        'yyzzdm.require'  => '企业统一信用代码必填',
//                        'establish_time.require' => '成立时间必填',
//                        'people.require' => '员工人数必填',


                        'gender.require'=> '法人性别必填',
                        'nation.require'=> '法人民族必填',
                        'out_look.require'=> '法人政治面貌必填',
                        'birthtime.require'=> '法人出生日期必填',
                        'native_place.require'=> '法人籍贯必填',
                        'card_number.require'=> '法人身份证号码必填',

                    ];

                    break;
            }
            self::check($params,$rule,$rule_msg);

        }
          $province_name = Area::where("id" ,$params['province'])->value("name");
            if(!$province_name) throw new \Exception("省份不存在");
            $city_name = Area::where("id" ,$params['city'])->value("name");
            if(!$city_name) throw new \Exception("市不存在");
            $district_name = Area::where("id" ,$params['district'])->value("name");
            if(!$district_name) throw new \Exception("区县不存在");
            $params['address_city'] = $province_name."/".$city_name."/".$district_name;

        $params["type"] = $type;







//        $order = self::getHaveCancelOrder($order_no);

        //判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
            //事务逻辑
            //得到申请单（没有则创建）
            $shop = ManystoreShop::where( 'user_id',$user_id)->find();
            //如果存在申请单，则直接更新这个单的状态
            //如果不存在则创建一个新单
            if(!$shop){

                //申请认证的时候不能是老师或其他机构的核销员
                $teacher = Teacher::where("user_id" ,$user_id)->find();
                if($teacher) throw new \Exception("您已经是老师，不能申请认证！");

               $verification = Verification::where("user_id" ,$user_id)->find();
                if($verification) throw new \Exception("您已经是机构核销员，不能申请认证！");

                //创建申请单
                $shop = $this->creatShop($type,$user_id,$params);
            }else{
                 //商家表单更新
               $shop_info = $shop->allowField(true)->save($params);
            if($shop_info === false){
               throw new \Exception($shop->getError());
             }
            }

            $shop = ManystoreShop::where( 'user_id',$user_id)->find();
             //更新申请单状态为审核中
            $shop['status']= '0';
            //清空审核时间
            $shop['reason']= '';
            $shop['auth_time']= 0;
            $shop["admin_id"] = 0;
            $shop->save();

            $store = Manystore::where("shop_id",$shop['id'])->find();
            $store["status"] = 'hidden';
            $store->save();


            //调用订单事件
            $data = ['shop' => $shop];
            \think\Hook::listen('shop_apply_after', $data);

            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage());
        }
        return $res;
    }




    /**更新机构数据
     * @param $type 申请类型 类型:1=个人,2=机构
     * @param int $user_id 申请人
     * @param $params 申请参数
     * @param bool $check
     * @param bool $trans
     * @return bool
     * @throws \Exception
     */
    public  function updateData($user_id=0,$params=[],$check=false,$trans=false){

        if($check){
            $user = User::get($user_id);
            if(!$user)throw new \Exception("用户不存在");
            //已经是机构
            $shop = ManystoreShop::where( 'user_id',$user_id)->find();
            if(!$shop)throw new \Exception("未申请机构，请先去申请机构");

            //验证参数
            //$type 1=个人,2=机构
            if(!in_array($shop['type'],['1','2']))throw new \Exception("类型参数错误");

            if(!in_array($params['gender'],[0,1]))throw new \Exception("年龄参数错误");

            unset($params['user_id']);
            unset($params['type']);

            //switch不同类型type做不同验证
            //未传手机号则默认用户手机号
            if(empty($params['tel'])) $params['tel'] = $user['mobile'];

            switch ($shop['type']) {
                case '1': //个人
                    $rule = [
                        'name' => 'require',
                        'tel' => 'require|number',
//                    'desc' => 'require',
                        'front_idcard_image' => 'require',
                        'reverse_idcard_image' => 'require',

                        'address' => 'require',
//                    'address_detail' => 'require',
                        'longitude' => 'require',
                        'latitude' => 'require',
                        'province' => 'require',
                        'city' => 'require',
                        'district' => 'require',

                        'gender'=> 'require',
                        'nation'=> 'require',
                        'out_look'=> 'require',
                        'birthtime'=> 'require',
                        'native_place'=> 'require',
                        'card_number'=> 'require',





                    ];
                    $rule_msg = [
                        'name.require' => '姓名必须填写',
                        'tel.require' => '服务电话必须填写',
                        'tel.number' => '服务电话必须是数字',
//                    'desc.require' => '申请备注必须填写',
                        'front_idcard_image.require' => '身份证正面必须上传',
                        'reverse_idcard_image.require' => '身份证反面必须上传',
                        'address.require' => '地址必填',
//                     'address_detail.require' => '详细地址必填',
                        'longitude.require' => '经度必填',
                        'latitude.require' => '纬度必填',
                        'province.require' => '省编号必填',
                        'city.require' => '市编号必填',
                        'district.require' => '县区编号必填',


                        'gender.require'=> '个人性别必填',
                        'nation.require'=> '个人民族必填',
                        'out_look.require'=> '个人政治面貌必填',
                        'birthtime.require'=> '个人出生日期必填',
                        'native_place.require'=> '个人籍贯必填',
                        'card_number.require'=> '个人身份证号码必填',

                    ];
                    break;
                case '2': //机构

                    $rule = [
                        'name' => 'require',
                        'tel' => 'require|number',
//                    'desc' => 'require',
                        'front_idcard_image' => 'require',
                        'reverse_idcard_image' => 'require',
                        'images' => 'require',
                        'yyzz_images' => 'require',
//                        'yyzzdm'  => 'require',


                        'address' => 'require',
//                         'address_detail' => 'require',
                        'longitude' => 'require',
                        'latitude' => 'require',
                        'province' => 'require',
                        'city' => 'require',
                        'district' => 'require',

//                        'establish_time' => 'require',
//                        'people' => 'require',


                        'gender'=> 'require',
                        'nation'=> 'require',
                        'out_look'=> 'require',
                        'birthtime'=> 'require',
                        'native_place'=> 'require',
                        'card_number'=> 'require',

                    ];

                    $rule_msg = [
                        'address.require' => '地址必填',
//                         'address_detail.require' => '详细地址必填',
                        'longitude.require' => '经度必填',
                        'latitude.require' => '纬度必填',
                        'province.require' => '省编号必填',
                        'city.require' => '市编号必填',
                        'district.require' => '县区编号必填',
                        'name.require' => '机构名称必须填写',
                        'tel.require' => '服务电话必须填写',
                        'tel.number' => '服务电话必须是数字',
//                    'desc.require' => '申请备注必须填写',
                        'front_idcard_image.require' => '法人身份证正面必须上传',
                        'reverse_idcard_image.require' => '法人身份证反面必须上传',
                        'images.require' => '机构环境照片必须上传',
                        'yyzz_images.require' => '营业执照照片必须上传',
//                        'yyzzdm.require'  => '企业统一信用代码必填',
//                        'establish_time.require' => '成立时间必填',
//                        'people.require' => '员工人数必填',


                        'gender.require'=> '法人性别必填',
                        'nation.require'=> '法人民族必填',
                        'out_look.require'=> '法人政治面貌必填',
                        'birthtime.require'=> '法人出生日期必填',
                        'native_place.require'=> '法人籍贯必填',
                        'card_number.require'=> '法人身份证号码必填',

                    ];

                    break;
            }
            self::check($params,$rule,$rule_msg);

        }
        $province_name = Area::where("id" ,$params['province'])->value("name");
        if(!$province_name) throw new \Exception("省份不存在");
        $city_name = Area::where("id" ,$params['city'])->value("name");
        if(!$city_name) throw new \Exception("市不存在");
        $district_name = Area::where("id" ,$params['district'])->value("name");
        if(!$district_name) throw new \Exception("区县不存在");
        $params['address_city'] = $province_name."/".$city_name."/".$district_name;




//        $order = self::getHaveCancelOrder($order_no);

        //判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
            //事务逻辑

            //商家表单更新
            $shop_info = $shop->allowField(true)->save($params);
            if($shop_info === false){
                    throw new \Exception($shop->getError());
            }


            $shop = ManystoreShop::where( 'user_id',$user_id)->find();
            //更新申请单状态为审核中 暂时先屏蔽
//            $shop['status']= '0';
//            //清空审核时间
//            $shop['reason']= '';
//            $shop['auth_time']= 0;
//            $shop["admin_id"] = 0;
//            $shop->save();

//            $store = Manystore::where("shop_id",$shop['id'])->find();
//            $store["status"] = 'hidden';
//            $store->save();


            //调用订单事件
            $data = ['shop' => $shop];
            \think\Hook::listen('shop_apply_after', $data);
            \think\Hook::listen('shop_update_after', $data);
            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage());
        }
        return $res;
    }


    /** 机构后台默认密码获取
     * @param $type
     * @param $user_id
     * @param $params
     *
     * @throws \think\exception\DbException
     */
public static function getDefaultPassword($type,$user_id,$params){
        $user = User::get($user_id);
    $defaultPassword = null;
    switch ($type) {
        case '1': //个人
            //手机号 + 个人id生成的code
            $defaultPassword =  $user["mobile"].en_code($user['id']);
//            $rule = [
//                'name' => 'require',
//                'tel' => 'require|number',
////                    'desc' => 'require',
//                'front_idcard_image' => 'require',
//                'reverse_idcard_image' => 'require',
//            ];
//            $rule_msg = [
//                'name.require' => '姓名必须填写',
//                'tel.require' => '服务电话必须填写',
//                'tel.number' => '服务电话必须是数字',
////                    'desc.require' => '申请备注必须填写',
//                'front_idcard_image.require' => '身份证正面必须上传',
//                'reverse_idcard_image.require' => '身份证反面必须上传',
//            ];
            break;
        case '2': //机构
            $defaultPassword =  $user["mobile"].en_code($user['id']);
//            $rule = [
//                'name' => 'require',
//                'tel' => 'require|number',
////                    'desc' => 'require',
//                'front_idcard_image' => 'require',
//                'reverse_idcard_image' => 'require',
//                'images' => 'require',
//                'yyzz_images' => 'require',
//            ];

//            $rule_msg = [
//                'name.require' => '机构名称必须填写',
//                'tel.require' => '服务电话必须填写',
//                'tel.number' => '服务电话必须是数字',
////                    'desc.require' => '申请备注必须填写',
//                'front_idcard_image.require' => '法人身份证正面必须上传',
//                'reverse_idcard_image.require' => '法人身份证反面必须上传',
//                'images.require' => '机构环境照片必须上传',
//                'yyzz_images.require' => '营业执照照片必须上传',
//            ];

            break;
    }
    return $defaultPassword;
}



public  function creatShop($type,$user_id,$params){

    $params["user_id"] = $user_id;
    //商家附表
    $shop = (new self);
    $shop_info = $shop->allowField(true)->save($params);
    if($shop_info === false){
        throw new \Exception($shop->getError());
    }




    $user = User::where("id",$user_id)->find();
    if(!$user) throw new \Exception("用户不存在");

    //账号主表
    $manystore_params = [
        "nickname" => $user["realname"] ?: $user["nickname"],
        "user_id"=>$user_id,
    ];
    $manystore_params["username"] = $params["tel"] ?: self::$pinyin->permalink($manystore_params["nickname"]);
    $manystore_params["email"] = $manystore_params["username"] . "@xx.com";

    $manystore_params['password'] = $params['password'] ?? self::getDefaultPassword($type,$user_id,$params);

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

    //如果用户存在头像取用户头像
    if($user["avatar"]) $manystore_params['avatar'] = $user["avatar"];
    $manystore_params['is_main'] = 1;
    if(!isset($params['password'])){
        $manystore_params['status'] = "hidden";
    }

    $model = new Manystore();

    $result = $model->allowField(true)->save($manystore_params);
    if ($result === false) {
        throw new \Exception($model->getError());
    }


    $manystoreAuthGroupModel = new ManystoreAuthGroup();
    $group = [];

    switch ($type) {
        case '1': //个人
            $group['name'] = '个人认证类型';
            $group['rules'] = '*';
            break;
        case '2': //机构
            $group['name'] = '机构认证类型';
            $group['rules'] = '*';
            break;
    }

    $group['shop_id'] = $shop->id;
    $group['createtime'] = time();
    $group['updatetime'] = time();
    $group_id = $manystoreAuthGroupModel->insertGetId($group);
    if(!$group_id){
        throw new \Exception('添加失败');
    }
    $manystoreApiAuthGroupModel = new ManystoreApiAuthGroup();
    $api_group_id = $manystoreApiAuthGroupModel->insertGetId($group);
    if(!$api_group_id){
        throw new \Exception('添加失败');
    }


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

    $manystoreAuthGroupAccessModel->insert($group_access);

    $manystoreApiAuthGroupAccessModel = new ManystoreApiAuthGroupAccess();
    $group_access = [];
    $group_access['uid'] = $model->id;
    $group_access['group_id'] = $api_group_id;

    $manystoreApiAuthGroupAccessModel->insert($group_access);


    //调用订单事件
    $data = ['shop' => $shop];
    \think\Hook::listen('shop_create_after', $data);


   return $shop;
}


    /** 机耕申请状态查询
     *
     */
public static function getAuthInfo($user_id){
    $auth_status = '-1'; //-1=未申请,0=待审核,1=审核通过,2=审核失败
    $shop_id = 0;
    $type = '1';
    $reason =""; //失败原因
    $check_full_msg = "";
    $check_full = false;

    $verification = true; //核销权限
    $verification_shop_id = 0; //可核销机构
    $join_number = self::getJoinNumber();
    try{
        $verification_shop_id = ClassesLib::checkOptionAuth(0,$user_id,"user");
    }catch (\Exception $e){

    }
    $verification_classes_lib_ids = (new ClassesLib)->getClassesAuthIds($user_id);
    $verification_classes_activity_ids = (new Activity())->getActivityAuthIds($user_id);

    //如果没有任何可管理的classes_lib_id 则返回错误
    if(!$verification_classes_lib_ids && !$verification_shop_id && !$verification_classes_activity_ids){
        $verification = false;
    }
    $verification_auth = compact("join_number","verification","verification_shop_id","verification_classes_lib_ids","verification_classes_activity_ids");



    $check_field = [
        "address_city",
        "province",
        "city",
        "district",
        "longitude",
        "latitude",
        "name",
        "image",
        "images",
        "content",
        "tel",
        "logo"
    ];
    $apply_info = null;
    if(!$user_id)return compact("join_number","verification_auth","check_full_msg","check_full","check_field",'auth_status','shop_id','reason','apply_info',"type");

    //得到申请单
    $apply_info =  self::where("user_id",$user_id)->where("status","1")->find();
    if(!$apply_info)$apply_info =  self::where("user_id",$user_id)->find();
       //不存在说明未申请，直接返回
    if(!$apply_info){
        return compact("join_number","verification_auth","check_full_msg","check_full","check_field",'auth_status','shop_id','reason','apply_info',"type");
    }
    $type =  $apply_info['type'];
    //从申请单取到申请状态
    $auth_status = $apply_info['status'];
    //如果是审核失败，取失败原因
    if($auth_status == '2'){
        $reason = $apply_info['reason'];
    }
    //如果是申请成功，取店铺id
    if($auth_status == '1'){
        $shop_id = $apply_info['id'];
    }

    //是否完善展示信息
    $self = new self;
    $check_full_msg = $self->checkFullMsg($shop_id);
    $check_full = $self->checkFull($shop_id);


    return compact("join_number","verification_auth","check_full_msg","check_full","check_field",'auth_status','shop_id','reason','apply_info',"type");
}



public static function getJoinNumber($real=false)
{
    $number =self::count();
    if($real) return $number;
    return $number + (int) config('site.shop_base_apply_num');
}





    /**
     * 获取所有课程列表
     */
    public static function getVaildList($params) {
        extract($params);
        $a = (new self)->getWithAlisaName().'.';
        // 查询自提点
        if(isset($status) && in_array($status, [1,2,0])){
            $selfetch = self::with(['user']);
        }else{
            $selfetch = self::with(['user'])->where($a.'status', '1')->where("{$a}auth_status",1);
        }


        $order  = $order?? 'normal';
        $per_page = $limit ?? 10;


        $field = "{$a}id,{$a}name,{$a}user_id,{$a}logo,{$a}image,{$a}images,{$a}address_city,{$a}city,{$a}province,{$a}district,{$a}address,{$a}address_detail,{$a}longitude,{$a}latitude,{$a}type,{$a}tel,{$a}status,{$a}create_time,{$a}update_time,{$a}weigh";

        //得到距离
        if (isset($latitude) && isset($longitude) && $latitude && $longitude) {
            $field .= ', '.getDistanceBuilder($latitude, $longitude);
        }else{
            $field .= ', 0 as distance';
        }

        //得到每个


        $selfetch = $selfetch->field($field);
        if (isset($keyword) && $keyword) {
            $selfetch = $selfetch->where("{$a}name|{$a}address|{$a}address_detail|{$a}address_city", 'like', '%' . $keyword . '%');
        }

        if (isset($user_id) && $user_id) {
            $selfetch = $selfetch->where("{$a}user_id", 'in', ''.$user_id);
        }

        if (isset($my) && $my && isset($my_user_id) && $my_user_id) {
            $selfetch = $selfetch->where("{$a}user_id", 'in', ''.$my_user_id);
        }


        if (isset($id) && $id) {
            $selfetch = $selfetch->where("{$a}id", 'in', ''.$id);
        }


        if (isset($teacher_id) && $teacher_id) {
           $teacher = Teacher::where("id",$teacher_id)->find();
           if($teacher){
                $selfetch = $selfetch->where("{$a}id", 'in', ''.$teacher["shop_id"]);
           }
         }

        if (isset($type) && $type) {
            $selfetch = $selfetch->where("{$a}type", 'in', ''.$type);
        }

        if (isset($status) && $status) {
            $selfetch = $selfetch->where("{$a}status", 'in', ''.$status);
        }



        //区域搜索
        if (isset($province) && $province) {
            $selfetch = $selfetch->where("{$a}province", 'in', ''.$province);
        }


        if (isset($city) && $city) {
            $selfetch = $selfetch->where("{$a}city", 'in', ''.$city);
        }

        if (isset($district) && $district) {
            $selfetch = $selfetch->where("{$a}district", 'in', ''.$district);
        }




        //排序
        switch ($order) {
            case "normal": //综合排序（推薦優先）
                $selfetch = $selfetch->order("{$a}weigh desc,{$a}id desc");
                break;
            case "distance": //距离优先 权重
                $selfetch = $selfetch->order("distance asc,{$a}weigh desc,{$a}id desc");
                break;
            default:
                throw new \Exception("不支持的排序类型");
        }

        if(isset($nearby) &&  $nearby) {
            $selfetch = $selfetch->having("distance <= {$nearby}");
        }




        $selfetch = $selfetch->paginate($per_page);

        //额外附加数据
//         foreach ($selfetch as $row) { //迭代器魔术方法遍历，填值自动引用传值
//               //设置是否已收藏
//              $row->is_collect = in_array($row->id,$collect_classes_lib_ids) ? 1 : 0;
//         }

        return $selfetch;
    }

    /** 机构初始化数据
     * @param $shop_id
     * @return void
     */
  public static function initData($shop_id){

     //设置初始化课程
     $shop =  self::where("id",$shop_id)->find();
     if($shop){
         $user = $shop->user;

        $manystore =  Manystore::where("shop_id" ,$shop_id)->find();
         if($user && $manystore){
             //更新申请表单状态
             $shopApply = ShopApply::where("id",$manystore["shop_apply_id"])->find();
             if($shopApply){
                 $shopApply->shop_id = $shop_id;
                 $shopApply->store_id  = $manystore["id"];
                 $shopApply->save();
             }



             //授权认证成功
             $result = \app\common\model\manystore\UserAuth::auth(0,$shop["id"],$shop["user_id"],"1",'admin',0);
             //删除用户所有老师和核销员
             Teacher::where("user_id",$user["id"])->delete();
             Verification::where("user_id",$user["id"])->delete();
             //为用户初始化老师和核销员
             $teacherData = [
                 "manystore_id"=> $manystore["id"],
                 "shop_id" => $shop["id"],
                 "user_id" => $user["id"],
                 "name" => $shop["name"] . "讲师",
                 "head_image" => $user["avatar"],
                 "content" =>  $shop["name"] . "讲师".",为您提供授课,核销,专人指导等服务。",
                 "status"  => "2",
                 "weigh" => 0,
             ];
             Teacher::create($teacherData);

             $verification_data  =[
                 "manystore_id"=> $manystore["id"],
                 "shop_id" => $shop["id"],
                 "user_id" => $user["id"],
                 "status" => "1",
             ];
             Verification::create($verification_data);
         }
     }

  }

//  public static function deleteDataByShopId($shop_id){
//     $ids = ClassesLib::where("shop_id",$shop_id)->column("id");
//
//
//  }

    public function adminshopadd($admin_id,$trans=false){
        $admin = Admin::where("id",$admin_id)->find();
        if(!$admin){
            throw new \Exception("管理员不存在");
        }
//判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
            $shop =  $this->adminCreateShop($admin_id);
            $admin["admin_shop_id"] = $shop["id"];
             $admin->save();
            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage().$e->getFile().$e->getLine());
        }
        return $res;
    }


//根据总管理员创建机构
public function adminCreateShop($admin_id){
    $admin = Admin::where("id",$admin_id)->find();
    if(!$admin){
        throw new \Exception("管理员不存在");
    }
    if(!$admin["mobile"]) throw new \Exception("管理员手机号不存在");
    if(!$admin["nickname"]) throw new \Exception("管理员昵称不存在");
    if(!$admin['area_json']) throw new \Exception("管理员限定区域不存在");
    $admin['area_json'] = explode(",",$admin['area_json']);
    $searchCity = SearchCity::where( "id",$admin['area_json'][0] ?? 0)->find();
    if(!$searchCity) throw new \Exception("管理员限定区域不存在");
    //根据手机号生成机构用户
    $user = \app\common\model\User::where("mobile",$admin["mobile"])->find();
    $people_name = $admin["nickname"] ."专属机构";
    $people_mobile = $admin["mobile"];
    //检测更新教练下单学员账号创建状态 2022/8/27 new
    if(!$user)$user = (new \app\common\model\User)->addUserByMobile($people_mobile,$people_name);
    $type = '2';
    $shop = self::where( "user_id",$user["id"])->find();
    $params = [];
    $params["user_id"] = $user["id"];
    $params["name"] = $people_name;
    $params["logo"] = config("site.shop_default_image");
    $params["image"] = $admin["avatar"] ?:  config("site.shop_default_timage");
    $params["images"] = $admin["avatar"] ?:  config("site.shop_default_images");
    $params["address_city"] = $searchCity["address_city"];
    $params["province"] = $searchCity["province"];
    $params["city"] = $searchCity["city"];
    $params["district"] = $searchCity["district"];
    $params["address"] = "无";
    $params["address_detail"] = "无";
    $params["tel"] = $people_mobile;
    $params["content"] = "无";
    $params["desc"] = "总后台创建账号时自动生成";
    $params["status"]= 1;
    $params["auth_time"] = time();
    $params["admin_id"] = $admin_id;
    $params["password"]  = "a123456";

    if( !$shop) $shop = $this->creatShop($type,$user["id"],$params);

    return $shop;
}


    public static function getPath($id){
        return Virtual::getPath("shop",["shop_id"=>$id]);
    }

    public static function getMiniQrcodeLink($id){
        return Virtual::getMiniQrcodeLink("shop",["shop_id"=>$id]);
    }


}
