<?php

namespace app\api\controller;

class MerchantFollow extends BaseShopController
{
    public array $notNeedLogin = ['list'];

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

        if (isset($params['del'])) {
            return $this->del($id);
        }

        $merchant = \app\common\model\Merchant::find($id);

        if (!$merchant) {
            return show(0, '添加失败');
        }

        $data = [
            ['user_id', '=', $this->userId],
            ['merchant_id', '=', $merchant->id]
        ];

        $follow = \app\common\model\MerchantFollow::where($data)->find();

        if ($follow) {
            return show(0, '请勿重复关注');
        }

        \app\common\model\MerchantFollow::create([
            'user_id' => $this->userId,
            'merchant_id' => $merchant->id,
        ]);

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

    public function del($id)
    {
        $merchant = \app\common\model\Merchant::find($id);

        if (!$merchant) {
            return show(0, '取关失败');
        }

        \app\common\model\MerchantFollow::where([
            ['user_id', '=', $this->userId],
            ['merchant_id', '=', $merchant->id]
        ])->delete();

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

    public function list($id)
    {
        $list = \app\common\model\MerchantFollow::with(['user'])
            ->where('merchant_id', $id)
            ->order('id', 'desc')
            ->paginate(20)
            ->toArray();

        return show(1, '列表', $list);
    }
}