<?php

namespace App\Admin\Controllers;

use App\Good;

use App\Trace;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Illuminate\Support\Facades\Artisan;
use Maatwebsite\Excel\Facades\Excel;
use Vinkla\Hashids\Facades\Hashids;

class GoodController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('产品管理');
            $content->description('列表');

            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('产品管理');
            $content->description('编辑');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('产品管理');
            $content->description('创建');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        return Admin::grid(Good::class, function (Grid $grid) {

            $grid->id('ID')->sortable();

            $grid->name('品种名称');
            $grid->operator('生产经营者');
            $grid->product_name('产品类型');
            $grid->product_pici('产品批次');
            $grid->number('数量');
            $grid->group('分组单位');
            $grid->trace('防伪码数量');
            $grid->is_key('防伪码状态')->display(function ($v) {
                switch ($v) {
                    case 'F':
                        return '未生成';
                        break;
                    case 'D':
                        return '正在生成';
                        break;
                    case 'T':
                        return '已生成';
                        break;
                }
            });

            $grid->created_at();
            $grid->updated_at();


            $grid->disableFilter();
            $grid->disableExport();

            $grid->actions(function ($actions) {
                if ($actions->row->group) {
                    $actions->prepend('<a style="margin-right:3px;" href="/admin/code?gid=' . $actions->getKey() . '"><i class="fa fa-bullseye"></i></a>');
                }

                // append一个操作
                if ($actions->row->is_key !== 'G') {
                    $actions->append('<a href="/admin/key/' . $actions->getKey() . '"><i class="fa fa-sitemap"></i></a>');
                }

                if ($actions->row->is_key === 'T') {
                    $actions->append('<a target="_blank" style="margin-left:5px;" href="/admin/export/' . $actions->getKey() . '"><i class="fa fa-share"></i></a>');
                }

            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(Good::class, function (Form $form) {

            $form->display('id', 'ID');
            //产品信息
            $form->text('name', '产品名称')->rules('required');
            $form->text('product_name', '产品类型');
            $form->text('product_pici', '产品批次');
            $form->text('standard', '包装规格');
            $form->text('package', '包装比例');

            $form->divide();

            //厂商
            $form->text('operator', '生产经营者')->rules('required');
            $form->text('product_area', '产地');
            $form->text('process_pici', '加工批次');

            $form->divide();

            //发货信息
            $form->text('consignor', '发货商');
            $form->date('delivery_time', '发货时间');
            $form->text('dealer', '经销商');

            $form->divide();

            //生产设置
            $form->text('higher_key', '上级码');
//            $form->textarea('data','扩展字段');
            $form->number('number', '数量');
            $form->text('skey', '首部添加关键码');
            $form->number('bit', '单元识别码的位数')->default(16);
            $form->number('group', '多少个分组一组')->help('[注:不分组不用填]');
            $form->select('templet', '前端模板')->options(collect(Good::$templetOption)->pluck('name', 'id'));

            $form->textarea('remark', '备注');

            $form->display('created_at', '创建时间');
            $form->display('updated_at', '更新时间');
        });
    }

    /**
     * 生成key
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     * User: Mead
     */
    public function key($id)
    {
        admin_toastr('正在生成！请稍后！', 'success');
        Artisan::call("generate:key", ['gid' => $id]);
        return redirect()->back();
    }

    /**
     * 导出excel
     * @param $id
     * @return mixed
     * User: Mead
     */
    public function export($id)
    {
        ini_set('memory_limit', '3072M');
        set_time_limit(0);

        return Excel::create(time(), function ($excel) use ($id) {

            $excel->sheet('Sheet1', function ($sheet) use ($id) {
                $sheet->setAutoSize(true);
                $sheet->cells('A', function ($cells) {
                    $cells->setAlignment('center');
                });
                $sheet->cells('B', function ($cells) {
                    $cells->setAlignment('center');
                });
                $sheet->cells('C', function ($cells) {
                    $cells->setAlignment('center');
                });
                $sheet->cells('D', function ($cells) {
                    $cells->setAlignment('center');
                });
                $sheet->setColumnFormat(array(
                    'B' => '0',
                    'A' => '0'
                ));

                $g = Trace::where('gid', $id)->distinct()->count();
                $info = Good::where('id', $id)->first();

                if ($g == 1) {
                    Trace::where('gid', $id)->select('id', 'key', 'group')->chunk(1000, function ($trace) use ($sheet) {
                        $sheet->rows($trace->toArray());
                    });
                } else {
                    $num = $info->group;
                    Trace::where('gid', $id)->select('id', 'key', 'group', 'slug')->chunk($num, function ($trace) use ($sheet) {
//                        $data = $trace->map(function ($v) {
//                            $v['id'] = number_format(10000000 + $v['id'], 0, '', '');
//
////                            $v['b'] = bcadd('1000000000000000', "{$v['id']}");
//
//                            return $v;
//                        });
                        $data = $trace->toArray();
                        $data[] = ['', '', '', ''];
                        $sheet->rows($data);
                    });
                }

                $sheet->prependRow(1, ['序号', '编码', '分组', '网址']);

            });

        })->download('xls');
    }
}
