<?php

namespace App\Models\Fpdx;

use App\Models\Model;
use Illuminate\Support\Facades\Redis;

/**
 * App\Models\Fpdx\MediaModel
 *
 * @property int $id 主键
 * @property string $media_id 公众号
 * @property string $public_name 公众号名称
 * @property string $head_img 头像
 * @property string $school 学校
 * @property int $sync_at 同步时间
 * @property float $gold_flower 累计小fa
 * @property float $get_flower 已获得小fa
 * @property string|null $keywords 关键字集
 * @property int $verify_type_info 认证状态
 * @property float $fpdx_money 分配对象收益
 * @property string|null $attach 附近值
 * @property int $type media_id类型
 * 0=公众号渠道
 * 1=口袋渠道
 * 2=kol渠道
 * 3=广告结单渠道
 * @property string $username 账号
 * @property int $fans 粉丝
 * @property int $kol_type kol渠道类型
 * @property \Illuminate\Support\Carbon $created_at 创建时间
 * @property \Illuminate\Support\Carbon $updated_at 修改时间
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereAttach($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereFans($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereFpdxMoney($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereGetFlower($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereGoldFlower($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereHeadImg($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereKeywords($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereKolType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereMediaId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel wherePublicName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereSchool($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereSyncAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereType($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereUsername($value)
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Fpdx\MediaModel whereVerifyTypeInfo($value)
 * @mixin \Eloquent
 */
class MediaModel extends Model
{
    protected $table = 'kdgx_partner_charge_media';

    protected $fillable = [
        'media_id',
        'public_name',
        'gold_flower',
        'red_flower',
        'partner_id',
        'from_media',
        'pay_media',
        'attach'
    ];

    public $dateFormat = 'U';

    /**
     * 获取公众号信息
     * @param  string  $media_id
     * @param  string  $app
     * @return object
     * {
     *      media_id: 公众号id
     *      public_name: 公众号名称
     *      school: 公众号学校
     *      keyword: [
     *          "关键词1",
     *          "关键词2"
     *      ]
     *      verify_type_info: 是否认证 [0认证 | -1未认证]
     * }
     * @throws \ApiException
     */
    public static function mediaInfo(string $media_id, string $app = 'fpdx')
    {
        $data = self::where('media_id', $media_id)->first();
        if (collect($data)->isEmpty()) {
            throw new \ApiException("不存在的公众号", 404);
        }
        $media_key = new MediaKeyModel();
        $keywords = $media_key->where([
            ['media_id', $media_id],
            ['app', $app]
        ])->get();
        $keys = array();
        $keywords->each(function ($item, $key) use (&$keys) {
            array_map(function ($value) use (&$keys) {
                array_push($keys, $value);
            }, json_decode($item->keywords, true));
        });
        $data->keywords = $keys ?: [];
        return $data;
    }

    /**
     * 是否开启某个app
     * @param  string 公众号id
     * @param  string app 应用
     * @param  string plat 平台
     * @return boolean
     */
    public function isOpen(string $media_id, string $app, string $plat = '')
    {
        if ($app == 'msy') {
            $data = self::where('media_id', $media_id)->first();
            if (empty($data->keywords)) {
                return false;
            } else {
                return true;
            }
        }
        $media_key = new MediaKeyModel();
        $first = $media_key->where([
            ['media_id', $media_id],
            ['app', $app]
        ])->when($plat, function ($query) use ($plat) {
            return $query->where('plat', $plat);
        })->first();
        if (collect($first)->isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 公众号收益总计
     * @param  string media_id 公众号id
     * @return array [
     *      'count' => 交易笔数,
     *      'msy_money' => 累计收益,
     *      'today_count' => 今日笔数
     * ]
     */
    public function incomeData(string $media_id)
    {
        $msy_money = self::where('media_id', $media_id)->first(['gold_flower']);
        $count = MediaLogModel::where(function ($query) use ($media_id) {
            $query->where('pay_media', $media_id)->orWhere('from_media', $media_id);
        })->count();
        $today_count = MediaLogModel::where(function ($query) use ($media_id) {
            $query->where('pay_media', $media_id)->orWhere('from_media', $media_id);
        })->whereBetween('create_at', [mktime(0, 0, 0), mktime(0, 0, 0) + 86400])->count();
        return [
            'count' => $count,
            'msy_money' => isset($msy_money->gold_flower) ? $msy_money->gold_flower : 0,
            'today_count' => $today_count
        ];
    }

    /**
     * 获取开启的公众号列表
     * @param  string app 应用
     * @return array
     * [
     *   [
     *      'media_id' => 公众号id，
     *      ‘public_name' => 公众号名称,
     *      'school' => 学校
     *   ]
     * ]
     */
    public function openMedias(string $app)
    {
        $hides = Redis::lrange("{pair_hides}", 0, -1);
        $medias = MediaKeyModel::where('app', $app)->whereNotIn(
            'media_id',
            $hides
        )->groupBy('media_id')->get(['media_id'])->pluck('media_id');
        $data = $this->where('type', 0)->whereIn('media_id', $medias)->get(['media_id', 'public_name', 'school']);
        return $data;
    }
}
