<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\DistMessage;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Admin;

use App\Distributor\Repositories\DistAdminDistributor;

class DistMessageController extends AdminController
{
    public function title()
    {
        return admin_trans('admin.messages');

    }
    /**
     * page index
     */
    public function index(Content $content)
    {
        return $content
            ->header(admin_trans( 'admin.messages'))
            ->description(admin_trans('admin.all'))
            ->breadcrumb(['text'=>'list','url'=>''])
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new DistMessage(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('title', admin_trans_field('message_title'));
            $grid->column('content');
            //$grid->column('sender_id');
            $grid->column('target_type')->display(function ($value) {
                if ($value === 'all') {
                    return admin_trans_label('all_users');
                } elseif ($value === 'users') {
                    return admin_trans_label('specified_users');
                }
                return $value;
            });
            //$grid->column('target_ids');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new DistMessage(), function (Show $show) use ($id) {
            $show->field('id');
            $show->field('title');
            $show->field('content');
            //$show->field('sender_id');
            $show->field('target_type')->as(function ($value) {
                if ($value === 'all') {
                    return admin_trans_label('all_users');
                } elseif ($value === 'users') {
                    return admin_trans_label('specified_users');
                }
                return $value;
            });
            //$show->field('target_ids');
//            $show->field('target_ids');
            // 获取 target_ids 并显示对应的 company_name
            $message = DistMessage::find($id);
            $targetIds = json_decode($message->target_ids, true);

            if ($targetIds) {
                $companyNames = DistAdminDistributor::getCompanyNamesByIds($targetIds);
                $show->field('target_ids')->as(function () use ($companyNames) {
                    return implode(', ', $companyNames);
                });
            } else {
               // $show->field('target_ids', 'Target IDs')->as('No specified users');
            }
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        //插入JS
        Admin::script(
            <<<JS
    $(document).ready(function() {
                var targetType = $('select[name="target_type"]');
                var targetIds = $('div.form-group.row.form-field:has(select[name="target_ids[]"])');

                // 初始化时根据 target_type 的值显示或隐藏 target_ids
                toggleTargetIds(targetType.val());

                // 监听 target_type 的变化
                targetType.change(function() {
                    toggleTargetIds($(this).val());
                });

                function toggleTargetIds(value) {
                   // alert(value);
                    if (value === 'users') {
                        targetIds.show();
                    } else {
                        targetIds.hide();
                    }
                }
            });

JS
        );

        return Form::make(new DistMessage(), function (Form $form) {
            $form->display('id')->rules('required');;
            $form->text('title',admin_trans_field('message_title'))->rules('required');;
            $form->textarea('content')->rules('required');;
//            $form->text('sender_id')->rules('required');

// 检查当前操作是创建还是编辑
            if ($form->isEditing()) {
                // 如果是编辑操作，设置 target_type 为只读
                $form->select('target_type')->options([
                    'all' => admin_trans_label('all_users'),
                    'users' => admin_trans_label('specified_users'),
                ])->rules('required')->readonly();
            } else {
                // 如果是创建操作，正常显示 target_type
                $form->select('target_type')->options([
                    'all' => admin_trans_label('all_users'),
                    'users' => admin_trans_label('specified_users'),
                ])->rules('required');
            }

            $form->multipleSelect('target_ids')
               ->options(DistAdminDistributor::tags_all())
                ->saving(function ($value) {

                    return $value;
                    //dd($value);
                    // 转化成json字符串保存到数据库
                    //return json_encode($value);
                });

            $form->display('created_at');
            $form->display('updated_at');
            $form->disableViewCheck();
            $form->disableCreatingCheck();
            $form->disableEditingCheck();


        });
    }
}
