<?php

namespace App\Http\Controllers\Admin;

use App\Models\SemKeyword;
use Illuminate\Http\Request;

class SemKeywordController extends AdminController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = SemKeyword::all();

        return view('admin.sem_keyword', compact('data'));
    }

    //关键词导入
    public function import(Request $request)
    {
        $file = $request->file('file');
        $type = $file->getClientOriginalExtension();
        if (in_array($type, ['csv'])) {
            $res = [0 => ''];  
            \Excel::load($file, function($reader) use( &$res ) {  
                $reader = $reader->getSheet(0);  
                $res = $reader->toArray();  
            });
            SemKeyword::where('id', '>', 0)->delete();
            unset($res[0]);
            if (!empty($res)) {
                foreach ($res as $value) {
                    SemKeyword::create(['name' => $value[0]]);
                }
            }
            return response()->json(['status' => 'success', 'message' => '导入关键词成功']);
        }

        return response()->json(['status' => 'error', 'message' => '请上传 csv 文件！']);
    }

    //关键词导出
    public function export()
    {
        $temp = SemKeyword::all();

        $data = [];
        $data = array (
            ['关键词']
        );

        if (!$temp->isEmpty()) {
            foreach ($temp as $key => $value) {
                $data[] = [
                   $value->name
                ];
            }
        }
        return \Excel::create('谷歌推广关键词列表', function($excel) use ($data) {
            $excel->sheet('导出关键词列表', function($sheet) use ($data) {
                $sheet->setVerticalCentered(true);
                $sheet->setHorizontalCentered(true);
                $sheet->fromArray($data, null, 'A1', false, false);
            });
        })->export('xls');
    }
    
}
