<?php

namespace App\Admin\Controllers;

use App\Good;

use App\Jobs\ExportTraces;
use App\Jobs\GenerateCode;
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\Cache;
use Illuminate\Support\Facades\Storage;

class GoodController extends Controller
{
    use ModelForm;

    const NUMBER = 3000000;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        $f = $this->byIdGetOver();
        $number = self::NUMBER;
        return Admin::content(function (Content $content) use ($f, $number) {

            $content->header('产品管理');
            if ($f) {
                $content->description('列表');
            } else {
                $content->description("列表(您今年的已超【{$number}】个码，暂不能导出二维码！)");
            }


            $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()
    {
        $over_number = self::NUMBER;
        return Admin::grid(Good::class, function (Grid $grid) use ($over_number) {

            $grid->model()->orderBy('id', 'desc');

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

            $grid->name('品种名称');
            $grid->company('公司名称');
            $grid->number('数量');
            $grid->group('分组单位');
            $grid->trace_count('防伪码数量');
            $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) use ($over_number) {
                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>');
                }
                $id = $actions->getKey();

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

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

            $form->display('id', 'ID');
            //产品信息
            $form->html('<h4>基本信息</h4>');
            $form->text('name', '产品名称');
            $form->divide();

            $form->html('<h4>种子信息</h4>');
            $form->text('product_name', '产品类型');
            $form->text('product_pici', '产品批次');
            $form->text('standard', '包装规格');
            $form->text('package', '销售信息');

            $form->text('operator', '生产经营者');
            $form->text('product_area', '产地');
            $form->text('process_pici', '加工批次');
            $form->text('card_id', '检疫证号');

            $form->text('shengchan_id', "经营许可证号");
            $form->text('changpin_id', '检疫证编码号');
            $form->text('guige', '净含量');

            $form->text('feature', '特征特性');
            $form->text('performance', '产量表现');
            $form->text('gist', '栽培技术要点');
            $form->text('area', '适宜种植区域');
            $form->text('season', '适宜种植季节');
            $form->divide();

//            $form->html('<h4>农药信息</h4>');
//            $form->text('register_name', '登记名称');
//            $form->text('card_id', '农药登记证号');
//            $form->text('duxing', '毒性');
//            $form->text('jixing', '剂型');
//            $form->text('shengchan_id', '生产批准证号');
//            $form->text('changpin_id', '产品标准号');
//            $form->text('guige', '产品规格');
//            $form->text('baozhiqi', '保质期');
//            $form->textarea('yongtu', '产品性能');
//            $form->textarea('cuncu', '存储方法');
//            $form->textarea('zhongdu', '中毒急救');
//            $form->textarea('zhuyi', '注意事项');
//            $form->image('youxiao', '有效成分')->move('youxiao')->uniqueName()->removable();

            $form->divide();
            $form->html('<h4>公司信息</h4>');
            $form->text('company', '企业名称');
            $form->text('company_website', '公司网址');
            $form->text('tel', '技术热线');
            $form->text('address', '公司地址');

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

            $form->divide();

            $form->html('<h4>码信息</h4>');

            $form->text('data', '编号前八位')->help('八位数字(slug)');
            //生产设置
            $form->text('higher_key', '上级码/产品规格码')->help('slug');
            $form->number('number', '数量');
            $form->text('skey', '首部添加关键码')->help('key');
            $form->number('bit', '单元识别码的位数')->default(16);
            $form->number('group', '多少个分组一组')->help('[注:不分组不用填]');
            $form->number('slug_num', '标识长度')->default(16);
            $form->select('slug_type', '标识类型')->options([0 => '字符串', 1 => '数字']);
            $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)
    {
        $key = Cache::get("generate-code-{$id}", 0);
        if ($key) {
            admin_toastr('正常生成，请勿重复操作！', 'warning');
            return redirect()->back();
        }
        Cache::put("generate-code-{$id}", 1, now()->addMinute(5));
        admin_toastr('正在生成！请稍后！', 'success');
        $this->dispatch(new GenerateCode($id));
        return redirect()->back();
    }

    public function byIdGetOver($id = false)
    {
        if ($id === false) {
            $number = Trace::whereYear('created_at', '=', date('Y'))->count();
        } else {
            $number = Trace::where('gid', '<=', $id)->whereYear('created_at', '=', date('Y'))->count();
        }

        if ($number <= self::NUMBER) {
            return true;
        }
        return false;
    }


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

        if (!$this->byIdGetOver($id)) {
            admin_toastr('您今年生成的码数量已超过' . self::NUMBER . '！', 'error');
            return redirect()->back();
        }

        $good = Good::where('id', $id)->first();

        $name = $good->id . '.txt';
        if (Storage::disk('public')->exists($name) && $good->number == count(file(Storage::disk('public')->path($name)))) {
            return response()->download(Storage::disk('public')->path($name));
        } else {
            $key = Cache::get("traces{$id}", 0);
            if ($key) {
                admin_toastr('5分钟后再来！', 'success');
                return redirect()->back();
            }
            Cache::put("traces{$id}", 1, now()->addMinute(5));
            admin_toastr('正在生成！请稍后！', 'success');
            $this->dispatch(new ExportTraces($id));
            return redirect()->back();
        }
    }
}
