<?php
declare (strict_types = 1);

namespace app\manager\controller;

use app\manager\model\Member as MemberModel;
use think\admin\Controller;
use think\facade\Db;



/**
 * 会员管理
 * @auth true
 * @menu true
 */
class Member extends Controller
{
    /**
     * 会员列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        $this->title = '会员管理';
        if ($this->request->isGet() && $this->request->get('output') === 'layui.table') {
            $where = [];
            // 搜索条件
            $keyword = input('keyword', '', 'trim');
            if (!empty($keyword)) {
                $where[] = ['email|order_id', 'like', "%{$keyword}%"];
            }
            // 状态筛选
            $status = input('status', '', 'trim');
            if ($status !== '') {
                $where[] = ['status', '=', intval($status)];
            }
            
            // 查询数据
            $query = MemberModel::where($where)->order('id desc');
            $result = $query->paginate([
                'list_rows' => input('limit', 20),
                'page' => input('page', 1),
            ]);
            
            return json([
                'code' => 0,
                'msg' => '',
                'count' => $result->total(),
                'data' => $result->items()
            ]);
        }
        
        return $this->fetch();
    }

    /**
     * 添加会员
     * @auth true
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->_vali([
                'email.require' => '邮箱不能为空！',
                'email.email' => '邮箱格式错误！',
                'order_id.require' => '闲鱼订单号不能为空！',
                'expire_time.require' => '有效期不能为空！',
                'usage_limit.require' => '可用次数不能为空！',
                'usage_limit.number' => '可用次数必须为数字！',
            ]);
            
            // 检查唯一性
            $map = [
                ['email', '=', $data['email']]
            ];
            if (MemberModel::where($map)->count() > 0) {
                $this->error('邮箱已存在！');
            }
            
            $map = [
                ['order_id', '=', $data['order_id']]
            ];
            if (MemberModel::where($map)->count() > 0) {
                $this->error('闲鱼订单号已存在！');
            }
            
            // 设置默认值
            $data['status'] = isset($data['status']) ? 1 : 0;
            $data['used_count'] = 0;
            
            // 保存数据
            if (MemberModel::create($data) !== false) {
                $this->success('添加成功！');
            } else {
                $this->error('添加失败！');
            }
        }
        
        $this->title = '添加会员';
        return $this->fetch('form');
    }

    /**
     * 编辑会员
     * @auth true
     */
    public function edit()
    {
        $id = input('id');
        if (empty($id)) $this->error('参数错误！');
        
        if ($this->request->isPost()) {
            $data = $this->_vali([
                'id.require' => 'ID不能为空！',
                'email.require' => '邮箱不能为空！',
                'email.email' => '邮箱格式错误！',
                'order_id.require' => '闲鱼订单号不能为空！',
                'expire_time.require' => '有效期不能为空！',
                'usage_limit.require' => '可用次数不能为空！',
                'usage_limit.number' => '可用次数必须为数字！',
            ]);
            
            // 检查唯一性
            $map = [
                ['email', '=', $data['email']],
                ['id', '<>', $id]
            ];
            if (MemberModel::where($map)->count() > 0) {
                $this->error('邮箱已存在！');
            }
            
            $map = [
                ['order_id', '=', $data['order_id']],
                ['id', '<>', $id]
            ];
            if (MemberModel::where($map)->count() > 0) {
                $this->error('闲鱼订单号已存在！');
            }
            
            // 设置默认值
            $data['status'] = isset($data['status']) ? 1 : 0;
            $data['used_count'] = isset($data['used_count']) ? intval($data['used_count']) : 0;
            
            // 保存数据
            if (MemberModel::update($data) !== false) {
                $this->success('编辑成功！');
            } else {
                $this->error('编辑失败！');
            }
        }
        
        $this->title = '编辑会员';
        $this->member = MemberModel::find($id);
        return $this->fetch('form');
    }

    /**
     * 修改状态
     * @auth true
     */
    public function state()
    {
        MemberModel::mSave($this->_vali([
            'status.in:0,1'  => '状态值范围异常！',
            'status.require' => '状态值不能为空！',
        ]));
    }

    /**
     * 删除会员
     * @auth true
     */
    public function remove()
    {
        MemberModel::mDelete();
    }

    /**
     * 表单数据处理
     * @param array $data
     */
    protected function _form_filter(array &$data)
    {
        if ($this->request->isPost()) {
            // 检查数据完整性
            empty($data['username']) && $this->error('用户名不能为空！');
            empty($data['order_id']) && $this->error('闲鱼订单号不能为空！');
            empty($data['expire_time']) && $this->error('有效期不能为空！');

            // 检查唯一性
            $map = [];
            if (empty($data['id'])) {
                $map[] = ['username', '=', $data['username']];
                $map[] = ['order_id', '=', $data['order_id']];
                if (MemberModel::where($map)->count() > 0) {
                    $this->error('用户名或闲鱼订单号已存在！');
                }
            } else {
                $map[] = ['id', '<>', $data['id']];
                $map[] = ['username|order_id', '=', $data['username']];
                if (MemberModel::where($map)->count() > 0) {
                    $this->error('用户名或闲鱼订单号已存在！');
                }
            }

            // 设置默认值
            $data['status'] = isset($data['status']) ? 1 : 0;
            $data['used_count'] = isset($data['used_count']) ? intval($data['used_count']) : 0;
            $data['balance'] = isset($data['balance']) ? floatval($data['balance']) : 0;
            $data['points'] = isset($data['points']) ? intval($data['points']) : 0;
            $data['level'] = isset($data['level']) ? intval($data['level']) : 1;
        }
    }
} 