<?php

namespace app\admin\controller\sys_manage;

use app\controller\Curd;
use app\model\Device;
use app\model\Supplier;
use app\model\SysDept;
use app\model\SysUser;
use support\Db;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;

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 afterQuery($items)
    {
        foreach ($items as &$item) {
            if (!empty($item->dept_extend_json)) {
                $extendJson = json_decode($item->dept_extend_json, true);
                $item->dept_week = $extendJson['week'] ?? [];
                $item->dept_work = [];
                $deptWork = [];
                if (!empty($extendJson['times'])) {
                    $times = explode('~', $extendJson['times']);
                    $deptWork[] = date('Y-m-d H:i:s', strtotime(date('Y-m-d ') . $times[0]));
                    $deptWork[] = date('Y-m-d H:i:s', strtotime(date('Y-m-d ') . $times[1]));
                }

                $item->dept_work = $deptWork;
                if (!empty($extendJson['printer'])) {
                    $devices = Device::whereIn('device_id', $extendJson['printer'])
                        ->select('device_id', 'device_name', 'device_config_json')
                        ->get()
                        ->toArray();
                    $deviceName = [];
                    foreach ($devices as $printer) {
                        if (empty($printer['device_config_json'])) {
                            continue;
                        }
                        $deviceConfigJson = json_decode($printer['device_config_json'], true);
                        $deviceName[] = (isset($deviceConfigJson['dept_name']) ? $deviceConfigJson['dept_name'] . '-' : '') . $printer['device_name'];
                    }
                    $item->printer = implode(', ', $deviceName);
                }
            }
        }

        return $items;
    }

    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('创建餐厅失败');
            }
            // 新餐厅到供应商里
            $supplierData = [
                'join_supplier_category_id' => 55,
                'join_supplier_dept_id' => $deptId,
                'supplier_status' => 'ACTIVED',
                'supplier_category' => 'DEPT',
                'supplier_name' => $data['dept_name'],
                'supplier_addtimes' => time()
            ];
            Supplier::insert($supplierData);

            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');
    }

    protected function insertInput(Request $request): array
    {
        $data = $this->inputFilter($request->post());

        $work = $request->post('dept_work', []);
        $dateWeek = $request->post('dept_week', []);
        $printerIds = $request->post('printer_id', []);
        $extendJson = [];
        if (isset($work[0]) && isset($work[1])) {
            $start = date('H:i', strtotime($work[0]));
            $end = date('H:i', strtotime($work[1]));
            $extendJson['times'] = $start . '~' . $end;
        } elseif (!isset($work[0]) && isset($extendJson['times'])) {
            unset($extendJson['times']);
        }

        if ($dateWeek) {
            $newDates = [];
            foreach ($dateWeek as $date) {
                $key = self::$week[$date];
                $newDates[$key] = $date;
            }
            ksort($newDates);

            $currentDate = current($newDates);
            $lastDate = end($newDates);

            $weekStr = '';
            if (self::$week[$lastDate] - self::$week[$currentDate] + 1 > count($newDates)) {
                $weekStr = implode(',', $newDates);
            } else if (self::$week[$lastDate] - self::$week[$currentDate] + 1 == count($newDates)) {
                $weekStr = $currentDate . '至' . $lastDate;
            }

            $extendJson['weeks'] = $weekStr;
            $extendJson['week'] = $dateWeek;
        }
        $extendJson['printer'] = $printerIds;

        $data['dept_extend_json'] = json_encode($extendJson);

        return $data;
    }


    /**
     * 更新
     * @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');
    }

    /**
     * 更新前置方法
     * @param Request $request
     * @return array
     * @throws BusinessException
     */
    protected function updateInput(Request $request): array
    {
        $work = $request->post('dept_work', []);
        $dateWeek = $request->post('dept_week', []);
        $printerIds = $request->post('printer_id', []);
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        $extendJson = [];
        if (!empty($model->dept_extend_json)) {
            $extendJson = json_decode($model->dept_extend_json, true);
        }
        if (isset($work[0]) && isset($work[1])) {
            $start = date('H:i', strtotime($work[0]));
            $end = date('H:i', strtotime($work[1]));
            $extendJson['times'] = $start . '~' . $end;
        } elseif (!isset($work[0]) && isset($extendJson['times'])) {
            unset($extendJson['times']);
        }

        if ($dateWeek) {
            $newDates = [];
            foreach ($dateWeek as $date) {
                $key = self::$week[$date];
                $newDates[$key] = $date;
            }
            ksort($newDates);

            $currentDate = current($newDates);
            $lastDate = end($newDates);

            $weekStr = '';
            if (self::$week[$lastDate] - self::$week[$currentDate] + 1 > count($newDates)) {
                $weekStr = implode(',', $newDates);
            } else if (self::$week[$lastDate] - self::$week[$currentDate] + 1 == count($newDates)) {
                $weekStr = $currentDate . '至' . $lastDate;
            }

            $extendJson['weeks'] = $weekStr;
            $extendJson['week'] = $dateWeek;
        }
        $extendJson['printer'] = $printerIds;

        $data['dept_extend_json'] = json_encode($extendJson);

        unset($data[$primary_key]);
        return [$id, $data];
    }

    public static $week = [
        '周一' => 1,
        '周二' => 2,
        '周三' => 3,
        '周四' => 4,
        '周五' => 5,
        '周六' => 6,
        '周日' => 7,
    ];

    /**
     * 场所名获取餐厅打印机
     */
    public function getPrinterByPremiseName(Request $request)
    {
        $premiseName = $request->get('premise', '');

        $printerList = [];
        try {

            $resraurant = SysDept::where('dept_name', $premiseName)->where('dept_category', '餐厅')->first();
            if (!$resraurant) {
                $premise = SysDept::where('dept_name', $premiseName)->where('dept_category', '营业场所')->first();
                $resraurant = SysDept::where('dept_super_id', $premise->dept_id)->where('dept_category', '餐厅')->first();
            }

            if (!empty($resraurant->dept_extend_json)) {
                $deptExtendJson = json_decode($resraurant->dept_extend_json, true);
                if (isset($deptExtendJson['printer'])) {
                    $printerList = $deptExtendJson['printer'];
                }
            }
        } catch (\Exception $e) {
        }

        return json_success('', $printerList);
    }

    /**
     * 获取用户所在餐厅
     */
    public function getByUser(Request $request)
    {
        $userId = $request->get('user_id', JwtToken::getCurrentId());

        $user = SysUser::where('user_id', $userId)->first();
        $restaurant = SysDept::where('dept_id', $user->join_user_dept_id)->where('dept_category', '餐厅')->get()->toArray();

        if (empty($restaurant)) {
            $premise = SysDept::where('dept_id', $user->join_user_dept_id)->where('dept_category', '营业场所')->first();
            if (!empty($premise)) {
                $restaurant = SysDept::where('dept_super_id', $premise->dept_id)->where('dept_category', '餐厅')->get()->toArray();
            }
        }

        $data = [];
        foreach ($restaurant as $item) {
            $data[] = [
                'key' => $item['dept_id'],
                'label' => $item['dept_name']
            ];
        }

        return json_success('success', $data);
    }
}