<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\ToolBar\Actions\PharmacyImportAction;
use App\Admin\Repositories\PharmacyRepository;
use App\Models\DosageModel;
use App\Models\PharmacistModel;
use App\Models\PharmacyDrugModel;
use App\Models\PharmacyModel;
use App\Models\User;
use Box\Spout\Common\Entity\Style\Color;
use Box\Spout\Writer\Common\Creator\Style\StyleBuilder;
use Box\Spout\Writer\Common\Creator\WriterEntityFactory;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Models\Administrator;
use Dcat\Admin\Models\Role;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Alert;
use Dcat\EasyExcel\Excel;
use Illuminate\Http\Request;

// 药店
class PharmacyController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new PharmacyRepository('user'), function (Grid $grid) {
            // 药店权限判断和数据过滤
            if (Admin::user()->isRole('pharmacy')) {
                $grid->model()->where('id', Admin::user()->pharmacy_id);
            }
            $grid->model()->orderBy('id', 'desc');

            if (Admin::user()->isRole('pharmacy')) {
                $grid->column('status')->using(PharmacyModel::STATUS_MAP);
            } else {
                $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('is_yb_open','医保开方')->using(PharmacyModel::IS_YB_OPEN_MAP)->dot(PharmacyModel::IS_AUTO_MAP_COLOR);
            $grid->column('name');
            $grid->column('药师数量')->display(function () {
                $num = PharmacistModel::where('pharmacy_id', $this->id)->count();

                return $num;
            });
            // $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('limit_buy_7', '1天限购');
            $grid->column('user.openid');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            if (Admin::user()->isRole('pharmacy')) {
                // 行按钮控制
                $grid->disableDeleteButton(); // 禁用删除按钮
                $grid->disableViewButton(); // 禁用详情按钮
                $grid->disableRowSelector(); // 禁止选中行

                // 工具栏按钮控制
                $grid->disableBatchActions(); // 禁用批量按钮
                $grid->disableCreateButton(); // 禁止创建按钮
            } else {
                // 工具栏普通按钮
                $grid->tools(function ($tools) {
                    $tools->append(new PharmacyImportAction()); // 导入药店信息
                });

                // 快捷搜索
                $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->disableDeleteButton(); // 禁用删除按钮
                $grid->disableViewButton(); // 禁用详情按钮

                // 工具栏按钮控制
                $grid->disableBatchActions(); // 禁用批量操作
            }
        });
    }

    /**
     * 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) {
            $pharmacyId = $form->getKey();
            if (Admin::user()->isRole('pharmacy') && Admin::user()->pharmacy_id != $pharmacyId) {
                admin_exit(
                    Content::make()
                        ->body(Alert::make('您无法进行此操作~', '无权操作')->danger())
                );
            }
            $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->text('lat')->help('举例：30.43836。江苏的纬度范围是：30.45到35.08');
                $form->text('lng')->help('举例：120.681244。江苏的经度范围是：116.18到121.57');
                // $form->select('user_id')->options(User::all()->pluck('openid', 'id'))->width(6)->help('实际后台操作可以不用关联');
                if ($form->isEditing() && ! Admin::user()->isRole('pharmacy')) {
                    $form->switch('status');
                }
                $form->switch('is_auto');
                $form->switch('is_yb_open','医保开方');
                $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) {
                if ($form->isCreating() && Admin::user()->isRole('pharmacy')) {
                    return $form->response()->error('您无法进行此操作~');
                }
                $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('手机号格式错误');
                }
                if (Admin::user()->isRole('pharmacy')) {
                    $form->deleteInput('status');
                }
            });

            $form->saved(function (Form $form, $result) {
                $pharmacyId = $form->getKey();
                // 从表单模型获取手机号和其他信息
                $mobile = $form->mobile;
                $name = $form->name;
                // 复制药店pharmacy_id=1的药店商品到新建药店
                if ($form->isCreating()) {
                    // 复制药品
                    $originalPharmacyModels = PharmacyDrugModel::where('pharmacy_id', 1)->get();
                    foreach ($originalPharmacyModels as $pharmacyModel) {
                        $pharmacyNewModel = $pharmacyModel->replicate();
                        $pharmacyNewModel->pharmacy_id = $pharmacyId;
                        $pharmacyNewModel->save();
                    }
                    // 复制用法用量
                    $originalDosageModels = DosageModel::where('pharmacy_id', 1)->get();
                    foreach ($originalDosageModels as $dosageModel) {
                        $dosageNewModel = $dosageModel->replicate();
                        $dosageNewModel->pharmacy_id = $pharmacyId;
                        $dosageNewModel->save();
                    }
                }

                // 获取店铺管理员角色
                $role = Role::where('slug', 'pharmacy')->first();
                // 查找当前是否已有管理员
                $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('123456'); // 设置药店管理员默认密码
                        $admin->pharmacy_id = $pharmacyId; // 药店ID
                        $admin->save(); // 保存新管理员

                        // 关联药店管理员角色
                        $admin->roles()->attach($role->id);
                    }
                }
            });

            // 右上角按钮控制
            $form->disableDeleteButton(); // 去掉删除按钮
            $form->disableViewButton(); // 去掉跳转详情页按钮
        });
    }

    /**
     * 药店导入模板
     *
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function exportPharmacyTemplate(Request $request)
    {
        $sheet1Head = ['药店名称', '地区', '详细地址', '药店管理员手机号', '营业开始时间', '营业结束时间'];
        $sheet1Data = [['江阴康麦医药有限公司', '江苏省/无锡市/江阴市', '利港街道 利南街41号', '13012345678', '06:30:00', '21:30:00']];

        $sheet1 = Excel::createSheet($sheet1Data, '药店信息', $sheet1Head)->row(function (array $row) {
            $style = (new StyleBuilder)
                ->setBackgroundColor(Color::YELLOW)
                ->build();

            return WriterEntityFactory::createRowFromArray($row, $style);
        });

        return Excel::export([$sheet1])->headings(false)->download('药店导入模板.xlsx');
    }
}
