<?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('', true);
            $grid->column('is_open')->using(PharmacyModel::IS_OPEN_MAP)->help('药店控制')->dot(PharmacyModel::IS_OPEN_MAP_COLOR);
            $grid->column('is_auto')->using(PharmacyModel::IS_AUTO_MAP)->dot(PharmacyModel::IS_AUTO_MAP_COLOR);
            $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);
                $filter->in('status', '平台启用状态')->checkbox(PharmacyModel::STATUS_MAP)->width(3);
                $filter->in('is_open', '开店状态')->checkbox(PharmacyModel::IS_OPEN_MAP)->width(3);
                $filter->in('is_auto', '自动审方')->checkbox(PharmacyModel::IS_AUTO_MAP)->width(3);
            });

            $grid->setActionClass(Grid\Displayers\Actions::class);
            // 行按钮控制
            $grid->disableDeleteButton(); // 禁用删除按钮
            $grid->disableViewButton(); // 禁用详情按钮

            // 工具栏按钮控制
            $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->column(6, function (Form $form) {
                $form->display('id');
                $form->text('name')->required()->maxLength(64, '最多输入64个字符');
                $form->text('area')->maxLength(64, '最多输入64个字符');
                $form->text('address')->maxLength(128, '最多输入128个字符');
                $form->mobile('mobile')->required()->help('药店登录账号')->rules(function (Form $form) {
                    // 如果不是编辑状态，则添加字段唯一验证
                    if (! $id = $form->model()->id) {
                        return 'unique:App\Models\PharmacyModel,mobile';
                    }
                });
                $form->timeRange('business_start', 'business_end', '营业时间')->required();
                $form->map('lat', 'lng', '经纬度坐标');
                // $form->select('user_id')->options(User::all()->pluck('openid', 'id'))->width(6)->help('实际后台操作可以不用关联');
                if ($form->isEditing()) {
                    $form->switch('status');
                }
                $form->switch('is_auto');

                $form->display('created_at');
                $form->display('updated_at');
            });
            $form->column(6, function (Form $form) {
                $form->image('business_license')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false)->required();
                $form->image('drug_biz_license')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false);
                $form->image('food_biz_license')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false);
                $form->image('med_device_biz_license')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false);
                $form->image('drug_info_service_cert')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false);
                $form->image('pre_packaged_food')->accept('jpg,png,jpeg')->uniqueName()->autoUpload()->retainable()->removable(false);
            });
            $form->saving(function (Form $form) {
                $status = $form->status;
                $pharmacyId = $form->getKey();
                $pharmacistNum = PharmacistModel::where('status', PharmacyModel::STATUS_TRUE)->where('pharmacy_id', $pharmacyId)->count();

                if ($status == 1 && $pharmacistNum <= 0) {
                    return $form->response()->error('开启失败，至少添加并且启用一个药师才可以开启药店~');
                }
                if ($form->mobile && ! preg_match('/^1[3456789]{1}[0-9]{9}$/', $form->mobile)) {
                    return $form->response()->error('手机号格式错误');
                }
            });

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

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

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

                    if ($admin) {
                        if ($mobile && $name) {
                            $admin->username = $mobile; // 更新账号
                            $admin->name = $name; // 更新账号姓名
                            $admin->save();
                        }
                    } else {
                        if ($mobile && $name && $pharmacyId) {
                            $admin = new Administrator();
                            $admin->username = $mobile; // 药店手机号作为管理员账号
                            $admin->name = $name; // 药店名称当做用户的姓名
                            $admin->password = bcrypt(Str::random(10)); // 设置管理员密码
                            $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(); // 去掉删除按钮
            $form->disableViewButton(); // 去掉跳转详情页按钮
        });
    }
}
