<?php
declare(strict_types=1);

namespace app\manager\controller;

use think\admin\Controller;
use think\admin\service\AdminService;

/**
 * 包名回传配置管理
 * @auth true
 * @menu true
 */
class PackageCallback extends Controller
{
    /**
     * 绑定数据表
     * @var string
     */
    protected $table = 'offer_package_callback';

    /**
     * 回传配置列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        // 设置页面标题
        $this->title = '回传配置管理';
        $this->fetch();
    }

    /**
     * 获取回传配置列表数据
     * @auth true
     */
    public function get_list()
    {
        try {
            // 获取请求参数
            $page = input('page/d', 1);
            $limit = input('limit/d', 15);
            $where = [];
            
            // 包名搜索
            if ($package_name = input('package_name/s', '')) {
                $where[] = ['package_name', 'like', "%{$package_name}%"];
            }
            
            // 事件名称搜索
            if ($event_name = input('event_name/s', '')) {
                $where[] = ['event_name', 'like', "%{$event_name}%"];
            }
            
            // 状态筛选
            if ($status = input('status/s', '')) {
                $where[] = ['status', '=', $status];
            }

            // 非超级管理员需要进行权限过滤
            if (!AdminService::instance()->isSuper()) {
                // 检查包名管理模块权限
                if (!AdminService::instance()->check('package/index')) {
                    return json([
                        'code' => 0,
                        'msg' => '',
                        'count' => 0,
                        'data' => []
                    ]);
                }
                
                $userId = AdminService::instance()->getUserId();
                // 获取有权限的包名ID列表
                $packageIds = $this->app->db->name('offer_package_auth')
                    ->where('user_id', $userId)
                    ->column('package_id');
                
                if (empty($packageIds)) {
                    return json([
                        'code' => 0,
                        'msg' => '',
                        'count' => 0,
                        'data' => []
                    ]);
                }
                
                $where[] = ['package_id', 'in', $packageIds];
            }

            // 查询数据
            $query = $this->app->db->name($this->table);
            
            // 先获取总数
            $total = $query->where($where)->count();
            
            // 分页查询数据
            $list = $query->where($where)
                ->field('*')
                ->order('id desc')
                ->limit(($page - 1) * $limit, $limit)
                ->select()
                ->toArray();

            return json([
                'code' => 0,
                'msg' => '',
                'count' => $total,
                'data' => $list
            ]);
            
        } catch (\Exception $e) {
            trace("获取回传配置列表异常：" . $e->getMessage());
            return json([
                'code' => 1,
                'msg' => '获取数据失败，请稍后重试',
                'count' => 0,
                'data' => []
            ]);
        }
    }

    /**
     * 添加回传配置
     * @auth true
     */
    public function add()
    {
        if ($this->request->isGet()) {
            // 设置页面标题
            $this->title = '添加回传配置';
            $this->fetch('add');  // 明确指定渲染 add.html
        }
        
        if ($this->request->isPost()) {
            try {
                $data = $this->_vali([
                    'package_id.require' => '包名ID不能为空！',
                    'package_name.require' => '包名不能为空！',
                    'event_name.require' => '事件名称不能为空！',
                    'callback_url.require' => '回传地址不能为空！',
                    'status.in:0,1' => '状态值不正确！'
                ]);

                // 检查权限
                if (!$this->checkPackageAuth($data['package_id'])) {
                    return json(['code' => 0, 'info' => '您没有操作此包名的权限！']);
                }

                // 检查是否已存在相同配置
                $exists = $this->app->db->name($this->table)
                    ->where([
                        'package_id' => $data['package_id'],
                        'event_name' => $data['event_name']
                    ])
                    ->find();
                    
                if ($exists) {
                    return json(['code' => 0, 'info' => '该包名下已存在相同事件名称的配置！']);
                }

                // 添加创建信息
                $data['create_by'] = AdminService::instance()->getUserId();
                $data['create_at'] = date('Y-m-d H:i:s');
                $data['update_at'] = date('Y-m-d H:i:s');

                $result = $this->app->db->name($this->table)->insert($data);
                if ($result === false) {
                    return json(['code' => 0, 'info' => '添加失败，请重试！']);
                }
                sysoplog('积分墙包名回传', '添加成功！');

                return json(['code' => 1, 'info' => '添加成功！']);
            } catch (\Exception $e) {
                trace("添加回传配置异常：" . $e->getMessage());
                return json(['code' => 0, 'info' => '系统异常，请稍后重试！']);
            }
        }
    }

    /**
     * 编辑回传配置
     * @auth true
     */
    public function edit()
    {
        if ($this->request->isGet()) {
            $id = $this->request->get('id/d', 0);
            if (empty($id)) {
                $this->error('参数错误');
            }

            // 获取配置信息
            $vo = $this->app->db->name($this->table)->where('id', $id)->find();
            if (empty($vo)) {
                $this->error('配置不存在');
            }

            // 检查权限
            if (!$this->checkPackageAuth($vo['package_id'])) {
                $this->error('您没有操作此包名的权限！');
            }
            
            $this->assign('vo', $vo);
            $this->fetch();  // 直接渲染 edit.html
        }
        
        if ($this->request->isPost()) {
            try {
                $data = $this->_vali([
                    'id.require' => '配置ID不能为空！',
                    'package_id.require' => '包名ID不能为空！',
                    'package_name.require' => '包名不能为空！',
                    'event_name.require' => '事件名称不能为空！',
                    'callback_url.require' => '回传地址不能为空！',
                    'status.in:0,1' => '状态值不正确！'
                ]);

                // 检查权限
                if (!$this->checkPackageAuth($data['package_id'])) {
                    return json(['code' => 0, 'info' => '您没有操作此包名的权限！']);
                }

                // 检查是否已存在相同配置（排除自身）
                $exists = $this->app->db->name($this->table)
                    ->where([
                        ['package_id', '=', $data['package_id']],
                        ['event_name', '=', $data['event_name']],
                        ['id', '<>', $data['id']]
                    ])
                    ->find();
                    
                if ($exists) {
                    return json(['code' => 0, 'info' => '该包名下已存在相同事件名称的配置！']);
                }

                // 更新时间
                $data['update_at'] = date('Y-m-d H:i:s');

                $result = $this->app->db->name($this->table)
                    ->where(['id' => $data['id']])
                    ->update($data);

                if ($result === false) {
                    return json(['code' => 0, 'info' => '更新失败，请重试！']);
                }
                sysoplog('积分墙包名回传', '更新成功！');

                return json(['code' => 1, 'info' => '更新成功！']);
            } catch (\Exception $e) {
                trace("编辑回传配置异常：" . $e->getMessage());
                return json(['code' => 0, 'info' => '系统异常，请稍后重试！']);
            }
        }
    }

    /**
     * 删除回传配置
     * @auth true
     */
    public function remove()
    {
        if ($this->request->isPost()) {
            try {
                $id = $this->request->param('id/d');
                if (empty($id)) {
                    return json(['code' => 0, 'info' => '参数错误！']);
                }

                // 获取配置信息
                $config = $this->app->db->name($this->table)->where('id', $id)->find();
                if (empty($config)) {
                    return json(['code' => 0, 'info' => '配置不存在！']);
                }

                // 检查权限
                if (!$this->checkPackageAuth($config['package_id'])) {
                    return json(['code' => 0, 'info' => '您没有操作此包名的权限！']);
                }

                $result = $this->app->db->name($this->table)->where('id', $id)->delete();
                if ($result === false) {
                    return json(['code' => 0, 'info' => '删除失败，请重试！']);
                }
                sysoplog('积分墙包名回传', '删除成功！');

                return json(['code' => 1, 'info' => '删除成功！']);
            } catch (\Exception $e) {
                trace("删除回传配置异常：" . $e->getMessage());
                return json(['code' => 0, 'info' => '系统异常，请稍后重试！']);
            }
        }
    }

    /**
     * 检查包名权限
     * @param int $packageId 包名ID
     * @return bool
     */
    protected function checkPackageAuth($packageId)
    {
        // 超级管理员直接放行
        if (AdminService::instance()->isSuper()) {
            return true;
        }
        
        // 检查用户是否有包名管理模块的权限
        if (!AdminService::instance()->check('package/index')) {
            return false;
        }

        // 检查具体包名权限
        $userId = AdminService::instance()->getUserId();
        $exists = $this->app->db->name('offer_package_auth')
            ->where(['package_id' => $packageId, 'user_id' => $userId])
            ->find();
            
        return !empty($exists);
    }

    /**
     * 修改状态
     * @auth true
     */
    public function state()
    {
        if ($this->request->isPost()) {
            try {
                $data = $this->_vali([
                    'id.require' => '配置ID不能为空！',
                    'status.in:0,1' => '状态值不正确！'
                ]);

                // 获取配置信息
                $config = $this->app->db->name($this->table)->where('id', $data['id'])->find();
                if (empty($config)) {
                    return json(['code' => 0, 'info' => '配置不存在！']);
                }

                // 检查权限
                if (!$this->checkPackageAuth($config['package_id'])) {
                    return json(['code' => 0, 'info' => '您没有操作此包名的权限！']);
                }

                // 更新状态
                $result = $this->app->db->name($this->table)
                    ->where(['id' => $data['id']])
                    ->update([
                        'status' => $data['status'],
                        'update_at' => date('Y-m-d H:i:s')
                    ]);

                if ($result === false) {
                    return json(['code' => 0, 'info' => '状态更新失败！']);
                }
                sysoplog('积分墙包名回传', '状态更新成功！');

                return json(['code' => 1, 'info' => '状态更新成功！']);
            } catch (\Exception $e) {
                trace("修改状态异常：" . $e->getMessage());
                return json(['code' => 0, 'info' => '系统异常，请稍后重试！']);
            }
        }
    }

    /**
     * 搜索包名
     * @auth true
     */
    public function searchPackages()
    {
        try {
            $keyword = input('keyword/s', '');
            $init = input('init/d', 0);  // 是否是初始化加载
            $event_name = input('event_name/s', '');  // 事件名称，用于排除已配置的包名
            $edit_id = input('edit_id/d', 0);  // 编辑时的ID，用于排除自身

            // 构建查询
            $query = $this->app->db->name('offer_package')
                ->alias('p')
                ->where('p.status', 1);

            // 非超级管理员需要进行权限过滤
            if (!AdminService::instance()->isSuper()) {
                $userId = AdminService::instance()->getUserId();
                $query->join('offer_package_auth a', 'p.id = a.package_id')
                    ->where('a.user_id', $userId);
            }

            // 排除已经配置过此事件的包名
            if (!empty($event_name)) {
                $existsQuery = $this->app->db->name($this->table)
                    ->where('event_name', $event_name);
                
                // 编辑时排除自身
                if ($edit_id > 0) {
                    $existsQuery->where('id', '<>', $edit_id);
                }
                
                $existsPackageIds = $existsQuery->column('package_id');
                
                if (!empty($existsPackageIds)) {
                    $query->whereNotIn('p.id', $existsPackageIds);
                }
            }

            // 如果是搜索则添加搜索条件
            if (!$init && !empty($keyword)) {
                $query->where(function($query) use ($keyword) {
                    $query->whereOr([
                        ['p.package_name', 'like', "%{$keyword}%"],
                        ['p.name', 'like', "%{$keyword}%"]
                    ]);
                });
            }

            // 限制返回数量
            $list = $query->field(['p.id', 'p.package_name', 'p.name'])  // 明确指定字段
                ->group('p.id')  // 防止重复
                ->order('p.id desc')  // 按ID倒序
                ->limit(20)
                ->select()
                ->toArray();

            return json(['code' => 1, 'msg' => '获取成功', 'data' => $list]);
        } catch (\Exception $e) {
            trace("搜索包名异常：" . $e->getMessage() . "\n" . $e->getTraceAsString());
            return json(['code' => 0, 'msg' => '系统异常，请稍后重试']);
        }
    }

    /**
     * 检查配置是否存在
     * @auth true
     */
    public function checkExists()
    {
        if ($this->request->isPost()) {
            try {
                $data = $this->_vali([
                    'package_id.require' => '包名ID不能为空！',
                    'event_name.require' => '事件名称不能为空！'
                ]);

                // 检查是否已存在相同配置
                $exists = $this->app->db->name($this->table)
                    ->where([
                        'package_id' => $data['package_id'],
                        'event_name' => $data['event_name']
                    ])
                    ->find();

                return json([
                    'code' => 1,
                    'msg' => '检查成功',
                    'data' => !empty($exists)
                ]);
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => '检查失败']);
            }
        }
    }

    /**
     * 获取已存在的配置详情
     * @auth true
     */
    public function getExistingConfig()
    {
        if ($this->request->isPost()) {
            try {
                $data = $this->_vali([
                    'package_id.require' => '包名ID不能为空！',
                    'event_name.require' => '事件名称不能为空！'
                ]);

                // 获取已存在的配置
                $config = $this->app->db->name($this->table)
                    ->where([
                        'package_id' => $data['package_id'],
                        'event_name' => $data['event_name']
                    ])
                    ->find();

                return json([
                    'code' => 1,
                    'msg' => '获取成功',
                    'data' => $config
                ]);
            } catch (\Exception $e) {
                return json(['code' => 0, 'msg' => '获取失败']);
            }
        }
    }
} 