<?php


namespace app\models\system;

use app\models\user\UserLevel;
use crmeb\traits\ModelTrait;
use crmeb\basic\BaseModel;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * TODO 设置会员等级Model
 * Class SystemUserLevel
 * @package app\models\system
 */
class SystemUserLevel extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'system_user_level';

    use ModelTrait;

    public static function merSet($mer_id, $alias = '')
    {
        return $mer_id ? (self::where($alias ? ($alias . '.mer_id') : 'mer_id', $mer_id)->where($alias ? ($alias . '.is_del') : 'is_del', 0)) : self::where($alias ? $alias . '.is_del' : 'is_del', 0);
    }

    public static function getAddTimeAttr($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    public static function getDiscountAttr($value)
    {
        return (int)$value;
    }

    /**
     * 获取查询条件
     * @param array $where
     * @param string $alert
     * @param null $model
     * @return $this|SystemUserLevel|null
     */
    public static function setWhere($where = [], $alert = '', $model = null)
    {
        $model = $model === null ? new self() : $model;
        if (isset($where['mer_id']) && $where['mer_id']) {
            $model = $model->merSet($where['mer_id'], $alert);
        }
        if ($alert) $model = $model->alias($alert);
        $alert = $alert ? $alert . '.' : '';
        $model = $model->where("{$alert}is_del", 0);
        if (isset($where['is_show']) && $where['is_show'] !== '') $model = $model->where("{$alert}is_show", $where['is_show']);
        if (isset($where['title']) && $where['title']) $model = $model->where("{$alert}name", 'LIKE', "%$where[title]%");
        return $model;
    }

    /**
     * 获取某个等级的折扣
     * @param int $id
     * @return mixed
     */
    public static function getLevelDiscount($id = 0, $mer_id = false)
    {
        $where = [];
        if ($mer_id) $where['mer_id'] = $mer_id;
        $model = self::setWhere($where);
        if ($id) $model = $model->where('id', $id);
        else $model = $model->order('grade asc');
        return $model->value('discount');
    }

    /**
     * 获取用户等级和当前等级
     * @param int $uid 用户uid
     * @param bool $isArray 是否查找任务列表
     * @return array|bool|mixed|string|\think\Model|null
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public static function getLevelInfo($uid, $isArray = false, $mer_id = false)
    {
        $level = ['id' => 0];
        $task = [];
        $id = UserLevel::getUserLevel($uid);
        if ($id !== false) $level = UserLevel::getUserLevelInfo($id);
        $list = self::getLevelListAndGrade($level['id'], $isArray, $mer_id);
        if (isset($list[0]) && $isArray) $task = SystemUserTask::getTashList($list[0]['id'], $uid, $level);
        if ($isArray) return [$list, $task];
        else return $level['id'] && $id !== false ? $level : false;
    }

    /*
     * 获取会员等级级别
     * @param int $leval_id 等级id
     * @return Array
     * */
    public static function getLevelGrade($leval_id)
    {
        return self::setWhere()->where('id', $leval_id)->value('grade');
    }

    /**
     * 获取会员等级列表
     * @param int $leval_id 用户等级
     * @param bool $isArray 是否查找任务列表
     * @param bool $mer_id
     * @return array|Collection
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getLevelListAndGrade($leval_id, $isArray, $mer_id = false)
    {
        $grade = 0;
        $where = [];
        if ($mer_id) {
            $where['mer_id'] = $mer_id;
        }
        if (!$leval_id && !$isArray) $leval_id = self::setWhere($where)->where('grade', self::setWhere($where)->min('grade'))->order('add_time DESC')->value('id');
        $list = self::setWhere($where)->field('name,discount,image,icon,explain,id,grade')->order('grade asc')->select();
        $list = count($list) ? $list->toArray() : [];
        foreach ($list as &$item) {
            if ($item['id'] == $leval_id)
                $grade = $item['grade'];
            if ($isArray)
                $item['task_list'] = SystemUserTask::getTashList($item['id'], 0, null, 1400, $mer_id);
        }
        foreach ($list as &$item) {
            if ($grade < $item['grade'])
                $item['is_clear'] = true;
            else
                $item['is_clear'] = false;
        }
        return $list;
    }

    /**
     * @param $leval_id
     * @param null $list
     * @param bool $mer_id
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getClear($leval_id, $list = null, $mer_id = false)
    {
        $list = $list === null ? self::getLevelListAndGrade($leval_id, false, $mer_id) : $list;
        foreach ($list as $item) {
            if ($item['id'] == $leval_id) return $item['is_clear'];
        }
        return false;
    }

    /**
     * 获取当前vipid 的下一个会员id
     * @param int $leval_id 当前用户的会员id
     * @param bool $mer_id
     * @return int
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getNextLevelId($leval_id, $mer_id = false)
    {
        $list = self::getLevelListAndGrade($leval_id, false, $mer_id);
        $grade = 0;
        $leveal = [];
        foreach ($list as $item) {
            if ($item['id'] == $leval_id) $grade = $item['grade'];
        }
        foreach ($list as $item) {
            if ($grade < $item['grade']) array_push($leveal, $item['id']);
        }
        return isset($leveal[0]) ? $leveal[0] : 0;
    }

    /**
     * 获取会员等级列表
     * @param $uid
     * @param bool $mer_id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getLevelList($uid, $mer_id = false)
    {
        list($list, $task) = self::getLevelInfo($uid, true, $mer_id);
        return ['list' => $list, 'task' => $task];
    }

    /**
     * 查找系统设置的会员等级列表
     * @param $where
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getSytemList($where)
    {
        $model = self::setWhere($where)->order('grade asc');
        if ($where['limit'] != '') $model = $model->page((int)$where['page'], (int)$where['limit']);
        $list = $model->select();
        $list = count($list) ? $list->toArray() : [];
        $count = self::setWhere($where)->count();
        return compact('count', 'list');
    }
}