<?php
/**
 * VR票务插件 - 电子票管理
 *
 * @package vr_ticket\admin\controller
 */

namespace app\plugins\vr_ticket\admin\controller;

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

    /**
     * 电子票列表
     */
    public function list()
    {
        $where = [];

        $keywords = input('keywords', '', null, 'trim');
        if (!empty($keywords)) {
            // 支持搜索：订单号、票码、观演人姓名、手机号
            $where[] = [
                'order_no|ticket_code|real_name|phone',
                'like',
                "%{$keywords}%"
            ];
        }

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

        $goods_id = input('goods_id', 0, 'intval');
        if ($goods_id > 0) {
            $where[] = ['goods_id', '=', $goods_id];
        }

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

        // 补充商品名称
        $goods_ids = array_filter(array_column($list['data'], 'goods_id'));
        if (!empty($goods_ids)) {
            $goods_map = \Db::name('Goods')
                ->where('id', 'in', $goods_ids)
                ->column('title', 'id');
            foreach ($list['data'] as &$item) {
                $item['goods_title'] = $goods_map[$item['goods_id']] ?? '已删除商品';
                $item['qr_code_url'] = \app\plugins\vr_ticket\service\TicketService::getQrCodeUrl($item['ticket_code']);
            }
            unset($item);
        }

        // 状态标签映射
        $status_map = [
            0 => ['text' => '未核销', 'color' => 'blue'],
            1 => ['text' => '已核销', 'color' => 'green'],
            2 => ['text' => '已退款', 'color' => 'red'],
        ];

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

    /**
     * 票详情
     */
    public function detail()
    {
        $id = input('id', 0, 'intval');
        if ($id <= 0) {
            return DataReturn('参数错误', -1);
        }

        $ticket = \Db::name('plugins_vr_tickets')->find($id);
        if (empty($ticket)) {
            return DataReturn('票不存在', -1);
        }

        // 商品信息
        $goods = \Db::name('Goods')->find($ticket['goods_id']);

        // 核销员信息
        $verifier = [];
        if ($ticket['verifier_id'] > 0) {
            $verifier = \Db::name('plugins_vr_verifiers')->find($ticket['verifier_id']);
        }

        // QR 码图片
        $ticket['qr_code_url'] = \app\plugins\vr_ticket\service\TicketService::getQrCodeUrl($ticket['ticket_code']);

        // 核销员列表（用于手动核销）
        $verifiers = \Db::name('plugins_vr_verifiers')
            ->where('status', 1)
            ->order('id', 'asc')
            ->select();

        return view('', [
            'ticket'    => $ticket,
            'goods'     => $goods,
            'verifier'  => $verifier,
            'verifiers' => $verifiers,
        ]);
    }

    /**
     * 手动核销票（仅 JSON）
     */
    public function verify()
    {
        if (!IS_AJAX_POST) {
            return DataReturn('非法请求', -1);
        }

        $ticket_code = input('ticket_code', '', null, 'trim');
        $verifier_id = input('verifier_id', 0, 'intval');

        if (empty($ticket_code)) {
            return DataReturn('票码不能为空', -1);
        }
        if ($verifier_id <= 0) {
            return DataReturn('请选择核销员', -1);
        }

        $result = \app\plugins\vr_ticket\service\TicketService::verifyTicket($ticket_code, $verifier_id);
        return DataReturn($result['msg'], $result['code'], $result['data'] ?? []);
    }

    /**
     * 导出票列表（CSV）
     * 需 POST 触发，防止链接被恶意分享
     */
    public function export()
    {
        if (!IS_AJAX_POST) {
            return DataReturn('非法请求', -1);
        }

        $where = [];
        $goods_id = input('goods_id', 0, 'intval');
        if ($goods_id > 0) {
            $where[] = ['goods_id', '=', $goods_id];
        }

        $header = ['ID', '订单号', '票码', '观演人', '手机', '座位', '核销状态', '发放时间'];
        $rows = \Db::name('plugins_vr_tickets')
            ->where($where)
            ->order('id', 'desc')
            ->cursor();

        $data = [];
        foreach ($rows as $item) {
            $status_text = $item['verify_status'] == 0 ? '未核销' : ($item['verify_status'] == 1 ? '已核销' : '已退款');
            $data[] = [
                $item['id'],
                $item['order_no'],
                $item['ticket_code'],
                $item['real_name'],
                $item['phone'],
                $item['seat_info'],
                $status_text,
                date('Y-m-d H:i:s', $item['issued_at']),
            ];
        }

        // 审计日志（记录导出操作）
        \app\plugins\vr_ticket\service\AuditService::logExport(
            $goods_id,
            ['verify_status' => null],
            count($data)
        );

        ExportCsv($header, $data, 'vr_tickets_' . date('Ymd'));
        return;
    }
}
