<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\PharmacyRepository;
use App\Models\PharmacistModel;
use App\Models\PharmacyModel;
use App\Models\User;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Models\Role;
use Dcat\Admin\Show;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

// 药店
class PharmacyController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new PharmacyRepository('user'), function (Grid $grid) {
            $grid->model()->orderBy('id', 'desc');

            $grid->column('id')->sortable();
            $grid->column('status')->switch();
            $grid->column('is_open')->using(PharmacyModel::IS_OPEN_MAP)->help('药店控制');
            $grid->column('name');
            // $grid->column('business_license')->image('', 50, 50);
            // $grid->column('drug_biz_license')->image('', 50, 50);
            // $grid->column('food_biz_license')->image('', 50, 50);
            // $grid->column('med_device_biz_license')->image('', 50, 50);
            // $grid->column('drug_info_service_cert')->image('', 50, 50);
            // $grid->column('pre_packaged_food')->image('', 50, 50);
            $grid->column('area');
            $grid->column('address');
            $grid->column('营业时间')->display(function () {
                $start = \Carbon\Carbon::parse($this->business_start)->format('H:i');
                $end = \Carbon\Carbon::parse($this->business_end)->format('H:i');

                return $start.'~'.$end;
            });
            $grid->column('mobile');
            // $grid->column('lng');
            // $grid->column('lat');
            $grid->column('user.openid');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            // 快捷搜索
            $grid->quickSearch(['name', 'mobile'])->placeholder('请输入[药店名称|管理员手机号]')->width(25);

            $grid->filter(function (Grid\Filter $filter) {
                $filter->panel(); // 更改为 panel 布局
                $filter->expand(); // 默认展开搜索框

                $filter->like('name')->width(3);
                $filter->like('mobile')->width(3);
            });

            // 行按钮控制
            $grid->disableDeleteButton(); // 禁用删除按钮

            // 工具栏按钮控制
            $grid->disableBatchDelete(); // 禁用批量删除
        });
    }

    /**
     * Make a show builder.
     *
     * @param  mixed  $id
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new PharmacyRepository(), function (Show $show) {
            $show->field('id')->width(4);
            $show->field('name')->width(4);
            $show->field('business_license')->width(4);
            $show->field('drug_biz_license')->width(4);
            $show->field('food_biz_license')->width(4);
            $show->field('med_device_biz_license')->width(4);
            $show->field('drug_info_service_cert')->width(4);
            $show->field('pre_packaged_food')->width(4);
            $show->field('area')->width(4);
            $show->field('address')->width(4);
            $show->field('mobile')->width(4);
            $show->field('lng')->width(4);
            $show->field('lat')->width(4);
            $show->field('status')->width(4);
            $show->field('created_at')->width(4);
            $show->field('updated_at')->width(4);

            $show->panel()->tools(function ($tools) {
                $tools->disableDelete(); // 禁止删除按钮
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new PharmacyRepository(), function (Form $form) {
            $form->display('id')->width(4);
            $form->text('name')->width(4)->required();
            $form->image('business_license')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false)->width(4);
            $form->image('drug_biz_license')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false)->width(4);
            $form->image('food_biz_license')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false)->width(4);
            $form->image('med_device_biz_license')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false)->width(4);
            $form->image('drug_info_service_cert')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false)->width(4);
            $form->image('pre_packaged_food')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false)->width(4);
            $form->text('area')->width(4);
            $form->text('address')->width(4);
            $form->mobile('mobile')->width(4)->required()->help('药店登录账号');
            $form->timeRange('business_start', 'business_end', '营业时间')->required();
            $form->map('lat', 'lng', '经纬度坐标');
            $form->select('user_id')->options(User::all()->pluck('openid', 'id'))->width(4)->help('实际后台操作可以不用关联');
            $form->switch('status')->width(4);

            $form->display('created_at')->width(4);
            $form->display('updated_at')->width(4);
            $form->saving(function (Form $form) {
                $status = $form->status;
                $pharmacistNum = PharmacistModel::where('status', 1)->count();
                if ($status == 1 && $pharmacistNum <= 0) {
                    return $form->response()->error('开启失败，至少启用一个药师才可以开启药店~');
                }
                // 中断后续逻辑
            });

            $form->saved(function (Form $form, $result) {
                DB::beginTransaction();
                try {
                    // 获取店铺管理员角色
                    $role = Role::where('slug', 'pharmacy')->first();

                    // 从表单模型获取手机号和其他信息
                    $mobile = $form->model()->mobile;
                    $name = $form->model()->name;
                    $pharmacyId = $form->getKey();

                    // 查找当前是否已有管理员
                    $admin = Administrator::where('pharmacy_id', $pharmacyId)->first();

                    if ($admin) {
                        // 如果存在，更新相应字段
                        $admin->username = $mobile; // 更新账号名
                        $admin->name = $name; // 更新账号名
                        $admin->save();
                    } else {
                        // 如果不存在，新增管理员
                        $admin = new Administrator();
                        $admin->username = $mobile; // 药店手机号作为管理员账号
                        $admin->name = $name; // 药店名称当做用户的姓名
                        // $admin->password = bcrypt(Str::random(10)); // 设置管理员密码
                        $admin->password = bcrypt($mobile); // 设置管理员密码
                        $admin->pharmacy_id = $pharmacyId; // 药店ID
                        $admin->save(); // 保存新管理员

                        // 关联药店管理员角色
                        $admin->roles()->attach($role->id);
                    }
                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollBack();
                    throw new \Exception($e->getMessage());
                }
            });

            // 右上角按钮控制
            $form->disableDeleteButton(); // 去掉删除按钮
        });
    }
}
