<?php

namespace app\api\controller;

use app\common\service\ConfigService;

class UserLabel extends BaseShopController
{
    public function listGroup()
    {
        $data = \app\common\model\UserLabelGroup::order('sort DESC')->select();
        return show(1, '用户标签组列表', $data);
    }

    public function listItem($gid)
    {
        $data = \app\common\model\UserLabelItem::order('sort DESC')->where('group_id', $gid)->select();
        return show(1, '用户标签列表', $data);
    }

    public function addRecord()
    {
        $params = $this->request->post();

        $recordCount = \app\common\model\UserLabelRecord::where('user_id', $this->userId)->count();
        $maxCount = ConfigService::get('user', 'max_label_num', 7);

        if ($recordCount >= $maxCount) {
            return show(0, '最多添加' . $maxCount . '个标签');
        }

        $record = \app\common\model\UserLabelRecord::where('user_id', $this->userId)->where('label_item_id', $params['label_id'])->find();

        if ($record) {
            return show(0, '已经添加过');
        }

        \app\common\model\UserLabelRecord::create([
            'user_id' => $this->userId,
            'label_item_id' => $params['label_id']
        ]);

        return show(1, '成功');
    }

    public function delRecord()
    {
        $params = $this->request->post();

        \app\common\model\UserLabelRecord::where('user_id', $this->userId)->where('label_item_id', $params['label_id'])->delete();

        return show(1, '成功');
    }

    public function listRecord()
    {
        $params = $this->request->param();

        $userId = $this->userId;

        if (isset($params['user_id'])) {
            $userId = $params['user_id'];
        }

        $data = \app\common\model\UserLabelRecord::with(['labelItem'])->where('user_id', $userId)->select();

        return show(1, '用户标签列表', $data);
    }

    public function getConfig()
    {
        return show(1, '设置', [
            'max_label_num' => ConfigService::get('user', 'max_label_num', 7),
        ]);
    }
}