<?php

namespace app\controller\admin;

use laytp\controller\Backend;
use think\facade\Config;
use laytp\library\CommonFun;
use app\validate\admin\bot\Add;
use app\validate\admin\bot\Edit;
use laytp\library\Str;
use laytp\library\UploadDomain;
use app\service\Telegram as Telegrambot;
use think\facade\Request;

/**
 * 会员管理
 */
class Order extends Backend
{

    /**
     * member模型对象
     * @var \app\model\Bot
     */
    protected $model;
	protected $hasSoftDel=1;//是否拥有软删除功能

    protected $noNeedLogin = []; // 无需登录即可请求的方法
    protected $noNeedAuth = ['index', 'info']; // 无需鉴权即可请求的方法

    public function _initialize()
    {
        $this->model = new \app\model\Order();
    }

    
    //查看和搜索列表
    public function index(){
        $where  = $this->buildSearchParams();
        $order  = $this->buildOrder();
        //var_dump($where,$order);
        $data   = $this->model->where($where)->order($order)->with(['avatar_pic_file']);
        $paging = $this->request->param('paging', false);
        if ($paging) {
            $limit        = $this->request->param('limit', Config::get('paginate.limit'));
            $data         = $data->paginate($limit)->toArray();
            $data['data'] = $this->getSelectedData($data['data']);
        } else {
            $data = $data->select()->toArray();
        }
        return $this->success('数据获取成功', $data);
    }

    
    //添加
    public function add()
    {
        $post = CommonFun::filterPostData($this->request->post());
		$validate = new Add();
		if(!$validate->check($post)){
			return $this->error($validate->getError());
		}
        try {
            if ($this->model->create($post)) {
                return $this->success('添加成功', $post);
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    
    //查看详情
    public function info()
    {
        $id   = $this->request->param('id');
        $info = $this->model->find($id);
        return $this->success('获取成功', $info);
    }

    //webhook
    public function webhook(){
         $botkey = $this->request->param('botkey');
          $id = $this->request->param('id');
         $botid = explode(":", $botkey)[0];
          $webhookdm = Request::domain() . '/api.Telegram/callback?botid='.$botid;
         $Telegrambot=new Telegrambot($botkey);
         $Telegrambot->setWebhook($webhookdm);
         $me=$Telegrambot->getme();
         $first_name=isset($me["result"]['first_name'])?$me["result"]['first_name']:"";
         $username=isset($me["result"]['username'])?$me["result"]['username']:"";
         
         
          $updateRes = $this->model->where('id', '=', $id)->update(['botid'=>$botid,'botuser'=>$username,'first_name'=>$first_name]);
         if ($updateRes) {
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
    }
    //编辑
    public function edit(){
        $id = $this->request->param('id');
        $info = $this->model->find($id);
        //var_dump($info);
        $post = CommonFun::filterPostData($this->request->post());
		$validate = new Edit();
		if(!$validate->check($post)){
			return $this->error($validate->getError());
		}
		
        foreach ($post as $k => $v) {
            $info->$k = $v;
        }
        try {
            $updateRes = $info->save();
            if ($updateRes) {
                return $this->success('编辑成功');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->exceptionError($e);
        }
    }

    

    
    //设置账号状态
    public function setStatus()
    {
        $id       = $this->request->post('id');
        $fieldVal = $this->request->post('field_val');
        $isRecycle = $this->request->post('is_recycle');
        $update['status'] = $fieldVal;
        try {
            if($isRecycle) {
                $updateRes = $this->model->onlyTrashed()->where('id', '=', $id)->update($update);
            } else {
                $updateRes = $this->model->where('id', '=', $id)->update($update);
            }
            if ($updateRes) {
                return $this->success('操作成功');
            } else if ($updateRes === 0) {
                return $this->success('未作修改');
            } else {
                return $this->error('操作失败');
            }
        } catch (\Exception $e) {
            return $this->error('数据库异常，操作失败');
        }
    }
}
