<?php

namespace Modules\User\Models;

use App\Models\Model;
use App\Traits\HasCovers;
use App\Traits\OrderByOrderAsc;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Arr;
use Modules\User\Models\Traits\HasIdentityScopes;

class Identity extends Model
{

    use Cachable;
    use HasCovers,
        HasIdentityScopes,
        OrderByOrderAsc,
        SoftDeletes;

    public $dates = [
        'end_at'
    ];

    const Conditions = [
        'cost'  => '原价',
        'price' => '开通金额',
    ];

    const Rules = [
        'give_crystal'   => '开通赠水滴',
        'recommend_rate' => '推荐比例',
    ];

    const CHANNEL_ONLINE  = 1;
    const CHANNEL_OFFLINE = 2;

    const CHANNELS = [
        self::CHANNEL_ONLINE  => '线上',
        self::CHANNEL_OFFLINE => '线下'
    ];

    const JOB_VISITOR  = 0;
    const JOB_FREE_VIP = 1;
    const JOB_YK       = 2;
    const JOB_JK       = 3;
    const JOB_NK       = 4;
    const JOBS         = [
        self::JOB_VISITOR  => '游客',
        self::JOB_FREE_VIP => '免费会员',
        self::JOB_YK       => '月卡',
        self::JOB_JK       => '季卡',
        self::JOB_NK       => '年卡',
    ];

    protected $table = 'user_identities';

    protected $casts = [
        'conditions' => 'json',
        'rules'      => 'json',
        'rights'     => 'json',
        'ruleshows'  => 'json',
    ];

    public function setConditionsAttribute($value)
    {
        $this->attributes['conditions'] = json_encode(array_values($value));
    }

    public function setRulesAttribute($value)
    {
        $rules = collect($this->rules);

        foreach ($value as &$item) {
            $info = $rules->where('name', $item['name'])->first();
            if (! isset($item['icon']) && $info && isset($info['icon'])) {
                $item['icon'] = $info['icon'];
            }
        }
        $this->attributes['rules'] = json_encode(array_values($value));
    }

    public function setRuleshowsAttribute($value)
    {
        $rules = collect($this->ruleshows);

        foreach ($value as &$item) {
            $info = $rules->where('name', $item['name'])->first();
            if (! isset($item['icon']) && $info && isset($info['icon'])) {
                $item['icon'] = $info['icon'];
            }
        }
        $this->attributes['ruleshows'] = json_encode(array_values($value));
    }

    public function setRightsAttribute($value)
    {
        $rights = collect($this->rights);

        foreach ($value as &$item) {
            $info = $rights->where('name', $item['name'])->first();
            if (! isset($item['cover']) && $info && isset($info['cover'])) {
                $item['cover'] = $info['cover'];
            }
        }

        $this->attributes['rights'] = json_encode(array_values($value));
    }

    /**
     * Notes: 获取所有规则
     *
     * @Author: 玄尘
     * @Date: 2022/8/21 13:03
     */
    public function getRules()
    {
        $rules = $this->ruleshows;
        if ($rules) {
            foreach ($rules as $key => $rule) {
                if (isset($rule['icon'])) {
                    $rules[$key]['cover'] = $this->parseImageUrl($rule['icon']);
                }
                $rules[$key]['text'] = Arr::get(config('identity.show_rules'), $rule['name']);
            }
        }

        return $rules;
    }

    /**
     * Notes: 获取未开通身份时反馈的数据
     *
     * @Author: 玄尘
     * @Date: 2022/8/26 14:16
     * @return array|mixed
     */
    public function getNotRules()
    {
        $rules = $this->rules;
        if (in_array($this->job, [Identity::JOB_YK, Identity::JOB_JK, Identity::JOB_NK])) {
            return [
                'give_crystal' => [
                    'cover' => $this->getRuleIcon('give_crystal', ''),
                    'value' => $this->getRule('give_crystal', 0),
                    'text'  => '赠送水滴'
                ],
                'stock'        => [
                    'value' => $this->stock,
                    'text'  => "赠送{$this->stock}箱水"
                ],
                'year'         => [
                    'value' => $this->years,
                    'text'  => $this->years."个月有效期"
                ],
            ];
        }

        return $rules;
    }


    /**
     * Notes   : 组内用户
     *
     * @Date   : 2021/5/6 12:06 下午
     * @Author : < Jason.C >
     * @return BelongsToMany
     */
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'user_identity')
            ->withTimestamps();
    }

    /**
     * Notes   : 不同的客服匹配不同的身份
     *
     * @Date   : 2021/6/07 10:50
     * @Author : Mr.wang
     * @return BelongsToMany
     */
    public function identities(): BelongsToMany
    {
        return $this->belongsToMany(Service::class, 'user_service_identity')
            ->withTimestamps();
    }

    /**
     * 返回身份中的某一个规则
     *
     * @param  string  $key
     * @param  mixed  $default
     * @return mixed|string
     */
    public function getRule(string $key = '', $default = '')
    {
        $values = collect($this->rules);
        $value  = $values->where('name', $key)->first();
        if ($value) {
            return $value['value'];
        } else {
            return $default;
        }
    }

    /**
     * Notes: 获取规则图标
     *
     * @Author: 玄尘
     * @Date: 2022/8/26 14:24
     * @param  string  $key
     * @param $default
     * @return mixed|string
     */
    public function getRuleIcon(string $key = '', $default = '')
    {
        $values = collect($this->rules);
        $value  = $values->where('name', $key)->first();
        if ($value && isset($value['icon'])) {
            return $this->parseImageUrl($value['icon']);
        } else {
            return $default;
        }
    }

    /**
     * 返回条件中的某一个字段
     *
     * @param  string  $key
     * @param  mixed  $default
     * @return mixed|string
     */
    public function getCondition(string $key = '', $default = '')
    {
        $values = collect($this->conditions);
        $value  = $values->where('name', $key)->first();
        if ($value) {
            return $value['value'];
        } else {
            return $default;
        }
    }

}
