<?php

namespace app\api\model;


use think\Db;
use think\Model;


class FamilyTree extends Model
{


    // 表名
    protected $name = 'family_tree';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'sex_text',
        'status_text'
    ];


    public function getSexList()
    {
        return ['0' => __('Sex 0'), '1' => __('Sex 1'), '2' => __('Sex 2')];
    }


    public function getSexTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sex']) ? $data['sex'] : '');
        $list = $this->getSexList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusList()
    {
        return ['0' => __('Status 0'), '1' => __('Status 1')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function users()
    {
        return self::hasOne("\app\admin\model\User", 'id', "create_user_id");
    }

    public function parent()
    {
        return self::hasOne("FamilyTree", 'id', "parent_id");
    }


    public function family()
    {
        return self::hasOne("Family", 'id', "family_id");
    }

    /**
     * 贡献排行榜
     * */
    public static function getDevoteByList($rows=20,$pages=[])
    {
//        family_people
//        family_tree
//        family_tree_mate

        $array = Db::name('family_people')
            ->alias('p')
            ->field('p.id,t.family_id,p.user_id ,t.name, u.username ,u.nickname,COUNT(l.id) AS log_count, u.avatar')
            ->join('family_tree t','p.id = t.people_id AND p.user_id != ""')
            ->join('user u',' p.user_id = u.id')
            ->join('worship_log l',' p.user_id = u.id  AND l.type = 2','left')
            ->join('fastim_user fu','p.user_id  = fu.user_id ')
            ->group('p.user_id')
            ->order('log_count DESC')
            ->paginate(
                empty($rows)?null:$rows,    //每页显示几条记录
                empty($pages[0])?false:$pages[0],
                empty($pages[1])?['query'=>input('get.')]:$pages[1]
            );

//        $array = Db::name('fastim_user')
//            ->alias('u')
//            ->field('u.nickname ,u.avatar,u.nickname, COUNT(l.id) AS log_count')
//            ->join('worship_log l','u.user_id = l.user_id AND l.type = 2','left')
//            ->group('u.user_id')
//            ->order('log_count DESC')
//            ->paginate(
//                empty($rows)?null:$rows,    //每页显示几条记录
//                empty($pages[0])?false:$pages[0],
//                empty($pages[1])?['query'=>input('get.')]:$pages[1]
//            );
        return $array;
    }

}
