<?php

namespace app\traits\account;

use app\model\BusinessFlow;
use think\Collection;

trait BusinessFlowTrait
{
    /**
     * 获取关注的商家列表
     * @param $accountCode
     * @param $page
     * @param $size
     * @param $keyword
     * @return
     */
    public function getBusinessFlowList($accountCode, $page, $size,$keyword=null)
    {
        $data = [
            'total' => 0,
            'current' => $page,
            'size' => $size,
            'list' => new Collection(),
        ];
        $model = BusinessFlow::alias("a")
            ->join("business b", "a.business_code = b.code")
            ->where("a.user_code", $accountCode)
            ->when(!empty($keyword), function ($q) use ($keyword) {
                $q->where("b.business_name", "like", "%{$keyword}%");
            })
            ->field([
                "b.id",
                "b.code as businessCode",
                "b.business_name as businessName",
                "b.background",
                "a.create_time as createTime",
                "a.user_code as userCode",
            ]);
        $data["total"] = $model->count();
        $data["list"] = $model
            ->page($page, $size)
            ->order("a.id desc")
            ->select();
        return $data;
    }

    /**
     * 获取关注的商家的code
     * @param $accountCode
     * @return array
     */
    public function getBusinessFlowCodeArray($accountCode)
    {
        return BusinessFlow::where("user_code",$accountCode)
            ->column("business_code");
    }

    /**
     * 获取关注的商家的code
     * @param $accountCode
     * @param $businessCode
     * @return BusinessFlow|array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function hasBusinessFlow($accountCode,$businessCode)
    {
        return BusinessFlow::where("user_code",$accountCode)
            ->where("business_code",$businessCode)
            ->find();
    }

    /**
     * 关注一个商家
     * @param $accountCode
     * @param $businessCode
     * @param $businessName
     * @return BusinessFlow|\think\Model
     */
    public function createBusinessFlow($accountCode,$businessCode,$businessName)
    {
        return BusinessFlow::create([
            "user_code"=>$accountCode,
            "business_code"=>$businessCode,
            "business_name"=>$businessName,
            "create_time"=>date("Y-m-d H:i:s")
        ]);
    }

}
