<?php

namespace app\admin\controller\sys_manage;

use app\common\Qrcode;
use app\controller\Curd;
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 RestaurantTableController extends Curd
{
    public function __construct()
    {
        $this->model = new SysDept();
    }


    public function select(Request $request): Response
    {
        $uid = JwtToken::getCurrentId();
        $user = SysUser::where('user_id', $uid)->first();
        $restaurant = SysDept::where('dept_category', '餐厅')->where(function ($query) use ($user) {
            $query->where('dept_id', $user->join_user_dept_id)->orWhere('dept_super_id', $user->join_user_dept_id);
        })->first();
        // $restaurant = SysDept::where('dept_category','餐厅')->where('dept_super_id',$user->join_user_dept_id)->first();
        if (!$restaurant) {
            return json_fail('您所在的营业场所没有餐厅，请联系管理员添加！');
        }

        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['dept_category'] = '桌台';
        $where['dept_super_id'] = $restaurant->dept_id;
        $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;
    }

    /**
     * @Desc 桌台管理顶部统计
     * @Author Gorden
     * @Date 2024/11/1 13:15
     *
     * @param Request $request
     * @return Response
     */
    public function statistics(Request $request)
    {
        $uid = JwtToken::getCurrentId();
        $user = SysUser::where('user_id', $uid)->first();
        $restaurant = SysDept::where('dept_category', '餐厅')->where(function ($query) use ($user) {
            $query->where('dept_id', $user->join_user_dept_id)->orWhere('dept_super_id', $user->join_user_dept_id);
        })->first();
        $restaurantId = !empty($restaurant) ? $restaurant->dept_id : '';
        $total = SysDept::where('dept_super_id', $restaurantId)->where('dept_category', '桌台')->count('dept_id');
        $activedTotal = SysDept::where('dept_super_id', $restaurantId)->where('dept_category', '桌台')->where('dept_status', 'ACTIVED')->count('dept_id');
        $pendingTotal = SysDept::where('dept_super_id', $restaurantId)->where('dept_category', '桌台')->where('dept_status', 'PENDING')->count('dept_id');
        $usingTotal = SysDept::where('dept_super_id', $restaurantId)->where('dept_category', '桌台')->where('dept_status', 'USING')->count('dept_id');
        $disabledTotal = SysDept::where('dept_super_id', $restaurantId)->where('dept_category', '桌台')->where('dept_status', 'DISABLED')->count('dept_id');

        return json_success('success', [
            'total' => $total,
            'activedTotal' => $activedTotal,
            'pendingTotal' => $pendingTotal,
            'usingTotal' => $usingTotal,
            'disabledTotal' => $disabledTotal,
        ]);
    }

    public function insert(Request $request): Response
    {
        $uid = JwtToken::getCurrentId();
        $user = SysUser::where('user_id', $uid)->first();
        $restaurant = SysDept::where('dept_category', '餐厅')->where(function ($query) use ($user) {
            $query->where('dept_id', $user->join_user_dept_id)->orWhere('dept_super_id', $user->join_user_dept_id);
        })->first();
        if (!$restaurant) {
            return json_fail('您所在的营业场所没有餐厅，请联系管理员添加！');
        }

        Db::beginTransaction();
        try {
            $data = $this->insertInput($request);

            $data['dept_category'] = '桌台';
            $data['dept_super_id'] = $restaurant->dept_id;
            $data['dept_city'] = $restaurant->dept_city;
            $data['dept_telephone'] = $restaurant->dept_telephone;
            $data['dept_position'] = $restaurant->dept_position;
            $data['dept_address'] = $restaurant->dept_address;
            $data['dept_if_dishes'] = $restaurant->dept_if_dishes;
            $deptId = $this->doInsert($data);
            if (!$deptId) {
                throw new BusinessException('创建桌台失败');
            }
            // 更新部门path
            $path = $restaurant->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');
    }

    public function batchInsert(Request $request)
    {
        $params = $request->post();
        if (intval($params['dept_code_nbr']) < 1) {
            return json_fail('数量不足，无法批量生成！');
        }
        if (intval($params['dept_code']) < 1 || intval($params['dept_code']) + intval($params['dept_code']) > 999) {
            return json_fail('请填写数字，且生成后不可大于999！');
        }

        $uid = JwtToken::getCurrentId();
        $user = SysUser::where('user_id', $uid)->first();
        $restaurant = SysDept::where('dept_category', '餐厅')->where(function ($query) use ($user) {
            $query->where('dept_id', $user->join_user_dept_id)->orWhere('dept_super_id', $user->join_user_dept_id);
        })->first();
        if (!$restaurant) {
            return json_fail('您所在的营业场所没有餐厅，请联系管理员添加！');
        }

        Db::beginTransaction();
        try {
            $data = $this->insertInput($request);
            for ($i = 0; $i < $params['dept_code_nbr']; $i++) {
                $number = $i + intval($params['dept_code']);
                $data['dept_category'] = '桌台';
                $data['dept_name'] = $number . '号桌';
                $data['dept_code'] = $restaurant->dept_code . '-' . $number;
                $data['dept_super_id'] = $restaurant->dept_id;
                $data['dept_city'] = $restaurant->dept_city;
                $data['dept_telephone'] = $restaurant->dept_telephone;
                $data['dept_position'] = $restaurant->dept_position;
                $data['dept_address'] = $restaurant->dept_address;
                $data['dept_if_dishes'] = $restaurant->dept_if_dishes;
                $data['dept_sort'] = $number;
                $deptId = $this->doInsert($data);
                if (!$deptId) {
                    throw new BusinessException('批量创建桌台失败');
                }
                // 更新部门path
                $path = $restaurant->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
    {
        try {
            [$id, $data] = $this->updateInput($request);

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

        return json_success('success');
    }

    public function exportTable(Request $request)
    {
        $uid = JwtToken::getCurrentId();
        $user = SysUser::where('user_id', $uid)->first();
        $restaurant = SysDept::where('dept_category', '餐厅')->where(function ($query) use ($user) {
            $query->where('dept_id', $user->join_user_dept_id)->orWhere('dept_super_id', $user->join_user_dept_id);
        })->first();
        if (!$restaurant) {
            return json_fail('您所在的营业场所没有餐厅，请联系管理员添加！');
        }

        $premisesId = '';
        if ($restaurant->dept_category == '营业场所') {
            $premisesId = $restaurant->dept_id;
        } else {
            $dept = SysDept::where('dept_id', $restaurant->dept_super_id)->first();
            if ($dept && $dept->dept_category == '营业场所') {
                $premisesId = $dept->dept_id;
            }
        }
        if (empty($premisesId)) {
            return json_fail('没有查找到营业场所');
        }

        $deptId = $request->get('dept_id', []);
        $deptName = $request->get('dept_name', '');

        $tables = SysDept::where('dept_category', '桌台')
            ->where('dept_super_id', $restaurant->dept_id)
            ->when(!empty($deptId), function ($query) use ($deptId) {
                $query->whereIn('dept_id', $deptId);
            })->when(!empty($deptName), function ($query) use ($deptName) {
                $query->where('dept_name', 'like', $deptName);
            })->get()
            ->toArray();
        $data = [];
        foreach ($tables as $table) {
            $data[] = [
                'dept_name' => $table['dept_name'],
                'dept_code' => $table['dept_code'],
                'qrcode_content' => json_encode([
                    'action' => 'scan-dishes',
                    'data' => [
                        'premises' => $premisesId,
                        'table' => $table['dept_name'],
                        'dept' => $table['dept_id']
                    ]
                ], JSON_UNESCAPED_UNICODE),
            ];
        }

        return json_success('', $data);
    }

    public function downloadQrcode(Request $request)
    {
        $tableId = $request->get('table_id', '');
        $uid = JwtToken::getCurrentId();
        $user = SysUser::where('user_id', $uid)->first();
        $restaurant = SysDept::where('dept_category', '餐厅')->where(function ($query) use ($user) {
            $query->where('dept_id', $user->join_user_dept_id)->orWhere('dept_super_id', $user->join_user_dept_id);
        })->first();
        if (!$restaurant) {
            return json_fail('您所在的营业场所没有餐厅，请联系管理员添加！');
        }
        $fileName = 'table-' . md5($tableId);
        // 图片已存在，删除之前的
        if (file_exists(public_path() . "/storage/qrcode/" . $fileName . '.png')) {
            unlink(public_path() . "/storage/qrcode/" . $fileName . '.png');
        }

        $table = SysDept::where('dept_id', $tableId)->where('dept_category', '桌台')->first();
        $restaurant = SysDept::where('dept_id', $table->dept_super_id)->first();
        // $premises = SysDept::where('dept_id',$restaurant->dept_super_id)->first();
        // if (!$premises){
        //     return json_fail('营业场所不存在');
        // }
        // $qrcodeContent = [
        //     'action'=>'scan-dishes',
        //     'data'=>[
        //         'premises'=>$table->dept_super_id,
        //         'table'=>$table->dept_name,
        //         'dept'=>$table->dept_id
        //     ]
        // ];
        // $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc6274da7198e3eb4&redirect_uri=https%3A%2F%2Fh5.wanyuewellness.com.cn%2F%23%2Fpages%2Findex%2FWeChatGuide?scan="
        // . urlencode(json_encode($qrcodeContent)).
//        "%7B%22action%22%3A%22scan-dishes%22%2C%22data%22%3A%7B%22premises%22%3A15%2C%22table%22%3A%221%E5%8F%B7%E5%8F%B0%22%2C%22tableid%22%3A16%7D%7D
        // "&response_type=code&scope=snsapi_base&connect_redirect=1&state=#wechat_redirect";
        $url = getenv('TABLE_QRCODE_DOMAIN') . "/qr?tid=" . $table->dept_id;
        $qrcode = new Qrcode();
        $qrcode->setLabel($restaurant->dept_name . "（" . $table->dept_name . "）");
        $qrcode = $qrcode->create($url, $fileName);
        if ($qrcode !== false) {
            return json_success('success', ['url' => getenv('STORAGE_DOMAIN') . '/storage/qrcode/' . $fileName . '.png']);
        }
    }

    public function batchDownloadQrcode(Request $request)
    {
        $uid = JwtToken::getCurrentId();
        $user = SysUser::where('user_id', $uid)->first();
        $restaurant = SysDept::where('dept_category', '餐厅')->where(function ($query) use ($user) {
            $query->where('dept_id', $user->join_user_dept_id)->orWhere('dept_super_id', $user->join_user_dept_id);
        })->first();

        $tables = SysDept::where('dept_super_id', $restaurant->dept_id)
            ->where('dept_category', '桌台')
            ->where('dept_status', '<>', 'DISABLED')
            ->get()
            ->toArray();
        $zip = new \ZipArchive();
        $filename = public_path() . '/storage/qrcode/zip/' . $restaurant->dept_name . '-桌台.zip';
        if (file_exists($filename)) {
            unlink($filename);
        }

        if ($zip->open($filename, \ZipArchive::CREATE) !== TRUE) {
            return json_fail("创建压缩文件失败");
        }
        foreach ($tables as $table) {
            $fileName = $restaurant->dept_name . '-' . $table['dept_name'];
            $url = getenv('TABLE_QRCODE_DOMAIN') . "/qr?tid=" . $table['dept_id'];
            $qrcode = new Qrcode();
            $qrcode->setLabel($restaurant->dept_name . "（" . $table['dept_name'] . "）");
            $qrcode = $qrcode->create($url, $fileName);
            if ($qrcode !== false) {
                $zip->addFile(public_path() . '/storage/qrcode/' . $fileName . '.png', $fileName . '.png');
//                return json_success('success', ['url' => getenv('STORAGE_DOMAIN') . '/storage/qrcode/' . $fileName . '.png']);
            }
        }
        $zip->close();

        return json_success('success', ['url' => getenv('STORAGE_DOMAIN') . '/storage/qrcode/zip/' . $restaurant->dept_name . '-桌台.zip']);
    }

    /**
     * 桌台列表
     */
    public function selectListByPremiseName(Request $request)
    {
        $premiseName = $request->get('premise', '');

        $tableList = [];
        try {

            $restaurant = SysDept::where('dept_name', $premiseName)->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first();
            if (!$restaurant) {
                $premise = SysDept::where('dept_name', $premiseName)->where('dept_category', '营业场所')->where('dept_status', 'ACTIVED')->first();

                $restaurant = SysDept::where('dept_super_id', $premise->dept_id)->where('dept_category', '餐厅')->where('dept_status', 'ACTIVED')->first();
            }

            $tables = SysDept::where('dept_super_id', $restaurant->dept_id)->where('dept_category', '桌台')->orderBy('dept_sort', 'ASC')->get()->toArray();

            foreach ($tables as $table) {
                $tableList[] = [
                    'key' => $table['dept_id'],
                    'label' => $table['dept_name'],
                    'disabled' => $table['dept_status'] == 'ACTIVED' ? false : true,
                ];
            }

            return json_success('', $tableList);
        } catch (\Exception $e) {
            return json_success('', $tableList);
        }

    }
}