<?php

namespace app\admin\controller\sys_manage;

use app\controller\Curd;
use app\model\SysDept;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use support\Response;

class RestaurantController extends Curd{
    public function __construct()
    {
        $this->model = new SysDept();
    }


    public function select(Request $request):Response
    {        
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['dept_category'] = '餐厅';
        $order = $request->get('order', 'desc');
        $field = $field ?? 'dept_sort';
        $query = $this->doSelect($where, $field, $order);
        
        return $this->doFormat($query, $format, $limit);
    }

    protected function doSelect(array $where, string $field = null, string $order = 'desc')
    {
        $model = $this->model->with([
            'premises' => function ($query) {
                $query->select('dept_id', 'dept_name');
            },
        ]);
        foreach ($where as $column => $value) {
            if (is_array($value)) {
                if ($value[0] === 'like' || $value[0] === 'not like') {
                    $model = $model->where($column, $value[0], "%$value[1]%");
                } elseif (in_array($value[0], ['>', '=', '<', '<>'])) {
                    $model = $model->where($column, $value[0], $value[1]);
                } elseif ($value[0] == 'in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereIn($column, $valArr);
                } elseif ($value[0] == 'not in' && !empty($value[1])) {
                    $valArr = $value[1];
                    if (is_string($value[1])) {
                        $valArr = explode(",", trim($value[1]));
                    }
                    $model = $model->whereNotIn($column, $valArr);
                } elseif ($value[0] == 'null') {
                    $model = $model->whereNull($column);
                } elseif ($value[0] == 'not null') {
                    $model = $model->whereNotNull($column);
                } elseif ($value[0] !== '' || $value[1] !== '') {
                    $model = $model->whereBetween($column, $value);
                }
            } else {
                $model = $model->where($column, $value);
            }
        }
        if ($field) {
            $model = $model->orderBy($field, $order);
        }
        return $model;
    }

    public function insert(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('add_premises')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }
        // 验证编号是否存在
        if (!empty($request->post('dept_code')) && SysDept::checkExist('餐厅', 'dept_code', $request->post('dept_code'))) {
            return json_fail('编号重复,请重新输入');
        }


        Db::beginTransaction();
        try {
            $data = $this->insertInput($request);
            $premises = SysDept::where('dept_id',$data['dept_super_id'])->where('dept_category','营业场所')->first();
            if (!$premises){
                Db::rollBack();
                return json_fail('营销场所不存在');
            }
            $data['dept_category'] = '餐厅';
            $deptId = $this->doInsert($data);
            if (!$deptId) {
                throw new BusinessException('创建餐厅失败');
            }
            // 更新部门path
            $path = $premises-> dept_super_path . $deptId . '/';
            if (!SysDept::where('dept_id', $deptId)->update(['dept_super_path' => $path])) {
                throw new BusinessException('创建餐厅失败');
            }
            Db::commit();
        } catch (BusinessException $customException) {
            Db::rollBack();
            return json_fail($customException->getMessage());
        } catch (\Exception $exception) {
            dump($exception->getMessage());
            Db::rollBack();
            return json_fail('创建餐厅失败');
        }
        return json_success('success');
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     */
    public function update(Request $request): Response
    {
        if ($this->validate && !$this->validateClass->scene('update_premises')->check($request->post())) {
            return json_fail($this->validateClass->getError());
        }

        try {
            [$id, $data] = $this->updateInput($request);
            $premises = SysDept::where('dept_id',$data['dept_super_id'])->where('dept_category','营业场所')->first();
            if (!$premises){
                Db::rollBack();
                return json_fail('营销场所不存在');
            }
            // 更新部门path
            $data['dept_super_path'] = $premises-> dept_super_path . $id . '/';

            $this->doUpdate($id, $data);
        } catch (BusinessException $customException) {
            return json_fail($customException->getMessage());
        } catch (\Exception $e) {
            return json_fail('数据更新失败');
        }

        return json_success('success');
    }
}