<?php
/**
 * VR票务插件 - 座位模板管理
 *
 * @package vr_ticket\admin\controller
 */

namespace app\plugins\vr_ticket\admin\controller;

class Seattemplate extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 座位模板列表
     */
    public function list()
    {
        $where = [];

        // 搜索
        $name = input('name', '', null);
        if ($name !== '') {
            $where[] = ['name', 'like', "%{$name}%"];
        }

        $status = input('status', '', null);
        if ($status !== '' && $status !== null) {
            $where[] = ['status', '=', intval($status)];
        }

        $list = \Db::name('plugins_vr_seat_templates')
            ->where($where)
            ->order('id', 'desc')
            ->paginate(20)
            ->toArray();

        // 关联分类名
        $category_ids = array_column($list['data'], 'category_id');
        if (!empty($category_ids)) {
            $categories = \Db::name('GoodsCategory')
                ->where('id', 'in', $category_ids)
                ->column('name', 'id');
            foreach ($list['data'] as &$item) {
                $item['category_name'] = $categories[$item['category_id']] ?? '未知分类';
                $item['seat_count'] = self::countSeats($item['seat_map']);
            }
            unset($item);
        }

        return view('', [
            'list'  => $list['data'],
            'page'  => $list['page'],
            'count' => $list['total'],
        ]);
    }

    /**
     * 添加/编辑座位模板
     */
    public function save()
    {
        $id = input('id', 0, 'intval');

        if (IS_AJAX_POST) {
            $data = [
                'name'         => input('name', '', null, 'trim'),
                'category_id'  => input('category_id', 0, 'intval'),
                'seat_map'     => input('seat_map', '', null, 'trim'),
                'spec_base_id_map' => input('spec_base_id_map', '', null, 'trim'),
                'status'       => input('status', 1, 'intval'),
                'upd_time'     => time(),
            ];

            if (empty($data['name'])) {
                return DataReturn('模板名称不能为空', -1);
            }
            if (empty($data['category_id'])) {
                return DataReturn('请选择绑定的分类', -1);
            }

            // 验证 seat_map 为合法 JSON
            $seat_map = json_decode($data['seat_map'], true);
            if (empty($seat_map) && $data['seat_map'] !== '[]' && $data['seat_map'] !== '{}') {
                return DataReturn('座位地图JSON格式错误', -1);
            }

            if ($id > 0) {
                // 更新
                $data['upd_time'] = time();
                \Db::name('plugins_vr_seat_templates')->where('id', $id)->update($data);
                return DataReturn('更新成功', 0, ['url' => MyUrl('plugins_vr_ticket/admin/seat_template/list')]);
            } else {
                // 新增
                $data['add_time'] = time();
                $data['upd_time'] = time();
                \Db::name('plugins_vr_seat_templates')->insert($data);
                return DataReturn('添加成功', 0, ['url' => MyUrl('plugins_vr_ticket/admin/seat_template/list')]);
            }
        }

        // 编辑时加载数据
        $info = [];
        if ($id > 0) {
            $info = \Db::name('plugins_vr_seat_templates')->find($id);
        }

        // 加载分类列表（用于下拉选择）
        $categories = \Db::name('GoodsCategory')
            ->where('is_delete', 0)
            ->order('id', 'asc')
            ->select();

        return view('', [
            'info'       => $info,
            'categories' => $categories,
        ]);
    }

    /**
     * 删除座位模板
     */
    public function delete()
    {
        if (!IS_AJAX_POST) {
            return DataReturn('非法请求', -1);
        }

        $id = input('id', 0, 'intval');
        if ($id <= 0) {
            return DataReturn('参数错误', -1);
        }

        // 软删除：改为 status=0 而非物理删除，保留数据审计
        $template = \Db::name('plugins_vr_seat_templates')->where('id', $id)->find();
        \Db::name('plugins_vr_seat_templates')
            ->where('id', $id)
            ->update(['status' => 0, 'upd_time' => time()]);

        // 审计日志
        \app\plugins\vr_ticket\service\AuditService::log(
            \app\plugins\vr_ticket\service\AuditService::ACTION_DISABLE_TEMPLATE,
            \app\plugins\vr_ticket\service\AuditService::TARGET_TEMPLATE,
            $id,
            ['before_status' => $template['status'] ?? 1],
            $template ? "模板: {$template['name']}" : "ID:{$id}"
        );

        return DataReturn('删除成功', 0);
    }

    /**
     * 统计座位数
     */
    private static function countSeats($seat_map_json)
    {
        if (empty($seat_map_json)) {
            return 0;
        }
        $map = json_decode($seat_map_json, true);
        if (empty($map['seats']) || empty($map['map'])) {
            return 0;
        }
        // 遍历每一行，统计非'_'且在 seats 映射中的座位字符数量
        $count = 0;
        foreach ($map['map'] as $row) {
            foreach (str_split($row) as $char) {
                if ($char !== '_' && isset($map['seats'][$char])) {
                    $count++;
                }
            }
        }
        return $count;
    }
}
