<?php

namespace app\manystoreapi\controller;

use app\common\controller\ManystoreApiBase;
use app\common\library\Virtual;
use app\manystore\model\Manystore;
use app\manystore\model\ManystoreShop;
use app\manystoreapi\model\ManystoreApiLog;
use fast\Random;
use think\Session;
use think\Url;
use think\Validate;


/**
 * 机构API后台：机构个人管理接口
 */
class Shop extends ManystoreApiBase
{
//    protected $noNeedLogin = [];
//    protected $noNeedRight = ['index'];
    protected $layout = '';
    protected $model = null;
    protected $shopModel = null;


    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
//        $this->request->filter('trim,strip_tags,htmlspecialchars');

        $this->model = Manystore::where(array('id'=>STORE_ID))->find();
        $this->shopModel = ManystoreShop::where(array('id'=>SHOP_ID))->find();

    }

    /**
     * 机构信息查询
     */
    public function index(){
        $res  = [];
        $res['statusList']=[0=>'待审核',1=>'审核通过',2=>'审核拒绝'];
        $res['typeList']=$this->shopModel->getTypeList();

        $res['shop_info']=$this->shopModel;
        $res['manystore_info']=$this->model;
        $res['check_full']=(new \app\common\model\dyqc\ManystoreShop)->checkFull(SHOP_ID);
        $res['check_full_msg']=(new \app\common\model\dyqc\ManystoreShop)->checkFullMsg(SHOP_ID);
        $res['now_city']= Virtual::getNowCity();
        $res['miniqrcode_link']=Url::build("/manystoreapi/shop/miniqrcode", ["ids" => SHOP_ID]);
        $this->apisuccess("查询成功！",$res);
    }


    /**
     * 更新账号密码，邮件，头像信息
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮件")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="avatar", type="string", required=true, description="头像")
     * @ApiParams (name="password", type="string", required=false, description="密码（非必填）")
     */
    public function update()
    {
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post();
            $params = array_filter(array_intersect_key(
                $params,
                array_flip(array('email', 'nickname', 'password', 'avatar'))
            ));
            unset($v);
            if (!Validate::is($params['email'], "email")) {
                $this->apierror(__("Please input correct email"));
            }
//            if (!Validate::is($params['nickname'], "/^[\x{4e00}-\x{9fa5}a-zA-Z0-9_-]+$/u")) {
//                $this->error(__("Please input correct nickname"));
//            }
            if (isset($params['password'])) {
                if (!Validate::is($params['password'], "/^[\S]{6,16}$/")) {
                    $this->apierror(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }
            $exist = Manystore::where('email', $params['email'])->where('id', '<>', $this->auth->id)->find();
            if ($exist) {
                $this->apierror(__("Email already exists"));
            }
            if ($params) {
                $manystore = Manystore::get($this->auth->id);
                $manystore->save($params);

                Session::set("manystoreapi", $manystore->toArray());


                $this->apisuccess();
            }
            $this->apierror();
        }
        return;
    }


    /** 编辑机构认证信息
     * @ApiTitle( 编辑机构认证信息)
     * @ApiSummary(编辑机构认证信息)
     * @ApiMethod(POST)
     * @ApiParams(name = "name", type = "string",required=true,description = "机构名称")
     * @ApiParams(name = "logo", type = "string",required=true,description = "logo单图")
     * @ApiParams(name = "image", type = "string",required=true,description = "封面单图")
     * @ApiParams(name = "content", type = "string",required=true,description = "店铺详情")
     * @ApiParams(name = "tel", type = "string",required=true,description = "服务电话(非必填)")
     * @ApiParams(name = "desc", type = "string",required=false,description = "申请备注(非必填)")
     * @ApiParams(name = "front_idcard_image", type = "string",required=true,description = "法人身份证正面")
     * @ApiParams(name = "reverse_idcard_image", type = "string",required=true,description = "法人身份证反面")
     * @ApiParams(name = "images", type = "string",required=true,description = "环境照片（多个逗号拼接）")
     * @ApiParams(name = "yyzzdm", type = "string",required=true,description = "社会统一信用代码")
     * @ApiParams(name = "yyzz_images", type = "string",required=true,description = "营业执照照片（多个逗号拼接）")
     * @ApiParams(name = "address", type = "string",required=true,description = "店铺地址")
     * @ApiParams(name = "address_detail", type = "string",required=true,description = "店铺详细地址")
     * @ApiParams(name = "longitude", type = "string",required=true,description = "经度")
     * @ApiParams(name = "latitude", type = "string",required=true,description = "纬度")
     * @ApiParams(name = "province", type = "int",required=true,description = "省编号")
     * @ApiParams(name = "city", type = "int",required=true,description = "市编号")
     * @ApiParams(name = "district", type = "int",required=true,description = "县区编号")
     * @ApiParams(name = "establish_time", type = "int",required=true,description = "成立时间10位秒级时间戳")
     * @ApiParams(name = "people", type = "int",required=true,description = "员工人数")
     * @ApiParams(name = "legal_entity", type = "string",required=true,description = "法人姓名")
     * @ApiParams(name = "gender", type = "int",required=true,description = "法人性别:0=女,1=男")
     * @ApiParams(name = "nation", type = "string",required=true,description = "法人民族")
     * @ApiParams(name = "out_look", type = "string",required=true,description = "法人政治面貌")
     * @ApiParams(name = "birthtime", type = "int",required=true,description = "法人出生日期10位秒级时间戳")
     * @ApiParams(name = "native_place", type = "string",required=true,description = "法人籍贯")
     * @ApiParams(name = "card_number", type = "string",required=true,description = "法人身份证号码")
     * @ApiParams(name = "diploma", type = "string",required=true,description = "法人学历")
     * @ApiParams(name = "post", type = "string",required=true,description = "法人职务")
     * @ApiParams(name = "social_position", type = "string",required=true,description = "法人社会职务")
     *
     *
     * @ApiReturn({
     *
     *})
     */
    public function shop_update(){
        $params=[];
        $params["name"] = $this->request->post('name/s','');
        $params["logo"] = $this->request->post('logo/s','');
        $params["image"] = $this->request->post('image/s','');
        $params["content"] = $this->request->post('content/s','');

        $params["tel"] = $this->request->post('tel/s','');
        $params["desc"] = $this->request->post('desc/s','');
        $params["front_idcard_image"] = $this->request->post('front_idcard_image/s','');
        $params["reverse_idcard_image"] = $this->request->post('reverse_idcard_image/s','');

        $params["images"] = $this->request->post('images/s','');
        $params["yyzz_images"] = $this->request->post('yyzz_images/s','');
        $params["yyzzdm"] = $this->request->post('yyzzdm/s','');


        $params["address"] = $this->request->post('address/s','');
        $params["address_detail"] = $this->request->post('address_detail/s','');
        $params["longitude"] = $this->request->post('longitude/s','');
        $params["latitude"] = $this->request->post('latitude/s','');




        $params["province"] = $this->request->post('province/d','');
        $params["city"] = $this->request->post('city/d','');
        $params["district"] = $this->request->post('district/d','');



        $params["establish_time"] = $this->request->post('establish_time/d','');
        $params["people"] = $this->request->post('people/d','');
        $params["legal_entity"] = $this->request->post('legal_entity/s','');
        $params["gender"] = $this->request->post('gender/d','');
        $params["nation"] = $this->request->post('nation/s','');
        $params["out_look"] = $this->request->post('out_look/s','');
        $params["birthtime"] = $this->request->post('birthtime/d','');
        $params["native_place"] = $this->request->post('native_place/s','');
        $params["card_number"] = $this->request->post('card_number/s','');
        $params["diploma"] = $this->request->post('diploma/s','');
        $params["post"] = $this->request->post('post/s','');
        $params["social_position"] = $this->request->post('social_position/s','');




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

        $user_id = 0;
        $user = $this->auth->getUser();//登录用户
        if($user)$user_id = $user['id'];
        try {
            $res =  (new \app\common\model\dyqc\ManystoreShop)->updateData($user_id,$params,true,true);
        } catch (\Exception $e){
//            Log::log($e->getMessage());
            $this->error($e->getMessage(),['errcode'=>$e->getCode()]);
        }
        $this->success('编辑成功', ['detail' => $res]);
    }




    /**
     * @ApiTitle( 微信小程序码)
     * @ApiSummary(微信小程序码)
     * @ApiMethod(GET)
     * @ApiParams(name = "ids", type = "int",required=true,description = "机构店铺id")
     * @ApiReturn({
     *  微信小程序码图片流
     *})
     */
    public function miniqrcode($ids = ''){
        $param = $this->request->param();
        try{
            if(isset($param['ids']))$ids = $param['ids'];
            //设置模拟资格
            $url =  \app\common\model\dyqc\ManystoreShop::getMiniQrcodeLink($ids);

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

        return $url["response"];
    }








    /**
     * @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 = "shop_id", type = "string",required=false,description = "机构店铺id")
     * @ApiParams(name = "store_id", type = "string",required=false,description = "机构账号ID")
     * @ApiParams(name = "user_id", type = "string",required=false,description = "机构用户ID")
     * @ApiParams(name = "ip", type = "string",required=false,description = "请求ip")
     * @ApiParams(name = "time", type = "string",required=false,description = "操作时间查询:today今天,week本周,month本月,year本年,yesterday昨天,last year上一年,last week上周，last month上個月，lately7最近7天 ， lately30最近30天，按开始时间区间查传值格式：Y/m/d H:M:S-Y/m/d H:M:S")
     *
     * @ApiReturn({
     *
     *})
     */
    public function log_list()
    {
        $params = [];
        $page  =  $this->request->get('page/d', 0); //页数
        $limit =  $this->request->get('limit/d', 0); //条数
        $params["keywords"] = $this->request->get('keywords/s', ''); //搜索关键字
        $params["shop_id"] = $this->request->get('shop_id/d', ''); //搜索关键字
        $params["store_id"] =  $this->request->get('store_id/d', ''); //搜索关键字
        $params["user_id"] =  $this->request->get('user_id/d', ''); //搜索关键字
        $params["ip"] =  $this->request->get('ip/d', ''); //时间
        if($params["ip"]) $params["ip"] = ["LIKE","%".$params["ip"] ."%"];
        $params["time"] =  $this->request->get('time/s', ''); //时间
        if(!$params["shop_id"]) $params["shop_id"] = $this->auth->shop_id;
        if(!$params["store_id"]) $params["store_id"] = $this->auth->id;
        try{
            //当前申请状态
            $res = ManystoreApiLog::logList($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(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 =  ManystoreApiLog::detail($id);
        } catch (\Exception $e){
//            Log::log($e->getMessage());
            $this->apierror($e->getMessage(),['errcode'=>$e->getCode()]);
        }
        $this->apisuccess('获取成功', ['detail' => $res]);
    }



}