<?php
namespace app\admin\controller;

use Curl\Curl;
use app\model\Qrcode as QrcodeModel;
use think\facade\View;

class Qrcode extends AdminController{

    public function index(){

        $list = QrcodeModel::where([])->order('id','desc')->paginate(20);
        $page = $list->render() ;

        View::assign('page',$page);
        View::assign('list',$list);
        return view();
    }

    /**
     * 二维码解码
     */
    public function qrcodeDecode(){

        $url = request()->post('qrcode/s','');
        if( empty($url) ){
            return $this->responseError('上传二维码不存在');
        }

//        $url = 'https://pay.69kz.com/csjs/yc88net/image/weixin.png';

        $curl = new Curl();
        $curl->get('https://cli.im/Api/Browser/deqr?data='.createOutFileUrl($url));

        if( $curl->error ){
            return $this->responseError('二维码识别错误');
        }

        $response = $curl->getResponse();
        $response = json_decode($response);

        if( $response->status == 1){
            return $this->responseSuccess($response->data->RawData);
        }

        return $this->responseError('二维码识别错误2');
    }

    public function add(){

        return view();
    }

    public function store(){

        $data = request()->post();
        $validated = $this->validate($data, 'Qrcode');

        if ($validated !== true) {
            return $this->responseError($validated);
        }

        $data['image'] = str_replace('temps/','',$data['qrcodeImage']) ;
        $file = getFilePath($data['qrcodeImage'],true);
        $movePath = str_replace('/temps','',$file) ;


        if( moveFile($file,$movePath) !== true  ){
            return $this->responseError('文件移动失败') ;
        }

        $rs = QrcodeModel::create($data) ;
        if( $rs !== false ){
            return $this->responseSuccess();
        }

        // 失败了把文件还回去
        moveFile($movePath,$file);

        return $this->responseError() ;

    }

    // 删除
    public function destroy($ids){

        if( empty( $ids ) ){
            return $this->responseError('删除id不存在');
        }

        $id = explode(',',$ids);

        $list   = QrcodeModel::select($id) ;
        $rs     = QrcodeModel::destroy($id);

        if( $rs !== false ){
            foreach( $list as $value ){
                removeFile(getFilePath($value->image ,1) );
            }
            return $this->responseSuccess();
        }
        return $this->responseError('删除失败');
    }
}
