<?php

namespace App\Admin\Controllers;

use App\Models\Merchant;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use App\Models\City;
use Illuminate\Http\Request;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\DB;
use App\Admin\Renderable\StoreList;
use App\Models\StoreAdminUsers;

class MerchantController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Merchant(), function (Grid $grid) {
            $grid->model()->orderBy('created_at', 'DESC');
            $grid->column('id')->sortable();
            $grid->column('name');
            $grid->column('cityinfo', '所在省市')->display(function ($val) {
                $proObj = City::where("city_id", $this->province_id)->first();
                $cityObj = City::where("city_id", $this->city_id)->first();
                $proname = $proObj->name ?? '';
                $cityname = $cityObj->name ?? '';
                return $proname . " " . $cityname;
            });
            $grid->column('store', '门店信息')->expand(function (Grid\Displayers\Expand $expand) {
                $expand->button('查看');
                return StoreList::make(['merchant_id' => $this->id]);
            })->width(100);
            $grid->column('contacts', '联系人');
            $grid->column('phone');
            $grid->column('account', '登录账号');
            $grid->column('buycode', '直购码');
            // $grid->column('created_at');
            // $grid->column('updated_at')->sortable();
            $grid->disableViewButton();
            $grid->filter(function (Grid\Filter $filter) {
                // 更改为 panel 布局
                $filter->panel();
                $filter->like('name')->width(3);
                $filter->equal('province_id', '省份')->select(City::where('parent_id', 0)->get()->pluck('name', 'city_id'))->load('city_id', '/city')->width(3);
                // 城市
                $filter->equal('city_id', '城市')->select()->width(3);
                $filter->like('contacts', '联系人')->width(3);
                $filter->like('phone')->width(3);
                $filter->like('buycode')->width(3);
            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new Merchant(), function (Show $show) {
            $show->field('id');
            $show->field('name');
            $show->field('contacter');
            $show->field('phone');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = Form::make(Merchant::with(['store_desc']), function (Form $form) {
            $form->display('id');
            $form->text('name')->required();
            $form->text('contacts', '联系人');
            $form->text('phone');
            $form->text('account')->required();
            $form->text('pwd')->help('字母数字组合,长度大于5个字符');
            $form->select('province_id', '省份')->options(City::where('parent_id', 0)->get()->pluck('name', 'city_id'))->rules('required')->load('city_id', '/city');
            // 城市
            $form->select('city_id', '城市');
            $form->hasMany('store_desc', '添加门店', function (\Dcat\Admin\Widgets\Form $forms) {
                $forms->text('title', '门店名称')->required();
                $forms->select('provinceId', '省份')->options(City::where('parent_id', 0)->get()->pluck('name', 'city_id'))->rules('required')->load('cityId', '/city');
                $forms->select('cityId', '城市');
                $forms->text('contacts', '联系人');
                $forms->text('phone', '手机号');
                $forms->text('lat_lng', '经纬度')->help('<a href="https://lbs.qq.com/getPoint/" target="_blank">点击获取腾讯地图坐标</a>');
                $forms->text('address', '详细地址');
                $forms->text('distance', '配送范围(Km)');
                $forms->image('business_license', '营业执照')
                    ->accept('jpg,jpeg,png')
                    ->maxSize(4096)
                    ->url('upload/merchant')
                    ->help('仅支持jpg、jpeg、png格式图片上传')
                    ->autoUpload();
            });

            $form->disableCreatingCheck();
            $form->disableEditingCheck();
            $form->disableViewCheck();
            $form->disableDeleteButton();
            $form->disableViewButton();
        });

        //副表保存规格
        $form->saved(
            function (Form $form, $result) {
                $merchant_id = $form->getKey();
                $account = isset($_POST['account']) ? trim($_POST['account']) : '';
                $pwd = isset($_POST['pwd']) ? trim($_POST['pwd']) : '123456';

                //生成商城后台账号
                $admin_users = StoreAdminUsers::where("username", $account)->first();
                $time = time();
                if (!$admin_users) {
                    if ($account) {
                        $storeAdmin_id = DB::table('store_admin_users')->insertGetId(
                            ['username' => $account, 'password' => bcrypt($pwd), 'name' => $account, 'merchant_id' => $merchant_id, 'created_at' => date('Y-m-d H:i:s', $time), 'updated_at' => date('Y-m-d H:i:s', $time)]
                        );
                        DB::table('store_admin_role_users')->insert([
                            'role_id' => 1,
                            'user_id' => $storeAdmin_id,
                            'created_at' => date('Y-m-d H:i:s', $time),
                            'updated_at' => date('Y-m-d H:i:s', $time)
                        ]);
                    }
                } else {
                    $storeAdmin_id = $admin_users->id;
                    if ($pwd != '123456') { //更新密码
                        $admin_users->password = bcrypt($pwd);
                        $admin_users->save();
                    }
                }
                //首次写入直购码
                $merObj = Merchant::where("id", $merchant_id)->first();
                if (!$merObj->buycode) {
                    $flag = 0;
                    $code = '';
                    do {
                        $code = mt_rand(1000, 9999);
                        $exist = Merchant::where("buycode", $code)->count();
                        if (!$exist) {
                            $flag = 1;
                        }
                    } while ($flag < 1);
                    //保存直购码
                    $merObj->buycode = $code;
                    $merObj->save();
                }
            }
        );

        return $form;
    }
}