<?php
declare (strict_types = 1);

namespace app\model\system;

use app\Request;
use Firebase\JWT\JWT;
use library\basic\BaseModel;
use library\services\UtilService;
use library\traits\JwtAuthModelTrait;
use library\traits\ModelTrait;
use think\db\exception\DbException;
use think\facade\Env;
use think\Model;

/**
 * @mixin \think\Model
 */
class Site extends BaseModel
{
    use ModelTrait;
    use JwtAuthModelTrait;

    /**
     * 具体信息
     * @param $page
     * @param array $where
     * @param int $pageCount
     * @param string $filed
     * @param string $desc
     * @return array|void
     */
    public function getList($page,$where = [],$pageCount = 20,$filed = '*',$desc = '') {

        $data =  $this
            ->field("*,(select name from table_site where sassid = s.tj_sassid) as tj_name")
            ->alias("s")
            ->when(1 ==1 ,function ($query) use ($where){
                if($where['artType'] == 'open'){
                    $query->where('status',1);
                }
                if($where['artType'] == 'stop'){
                    $query->where('status',0);
                }

                if(!empty($where['name'])) {
                    $query->whereLike('name',"%{$where['name']}%");
                }

                if(!empty($where['i_sassid'])) {
                    $query->where('sassid','<>',$where['i_sassid']);
                }

            })
            ->order($desc)
            ->paginate(['list_rows'=>$pageCount,'page'=>$page])
            ->toArray();
       // echo $this->getLastSql();
        foreach ($data['data'] as $k=>$v) {
            $data['data'][$k]['time'] = date('Y-m-d',$v['time']);
        }
        return [$data['total'],$data['data']];
    }


    /**
     * 具体信息
     * @param $page
     * @param array $where
     * @param int $pageCount
     * @param string $filed
     * @param string $desc
     * @return array|void
     */
    public function getList2($page,$where = [],$pageCount = 20,$filed = '*',$desc = '') {
        $regWhere = '';
        $oWhere = "";
        if(!empty($where['start_time'])) {
            $sTime = strtotime($where['start_time']);
            $eTime = strtotime($where['end_time']) + 86400;
            $regWhere = " AND regtime >= {$sTime} AND regtime < {$eTime}";
            $oWhere = " AND time >= {$sTime} AND time < {$eTime}";
        }


        $data =  $this
            ->field("s.*,
                (SELECT count(*) from table_member where sassid = s.sassid {$regWhere}) as user_count,
                (SELECT count(*) from table_order where status > 0 and sassid = s.sassid {$oWhere}) as order_count,
                (SELECT count(*) from table_order_info where status > 0 and sassid = s.sassid {$oWhere}) as sub_order_count,
                (SELECT sum(all_price) from table_order where status > 0 and sassid = s.sassid {$oWhere}) as order_money,
                (SELECT sum(v) from table_recharge where status = 1 and sassid = s.sassid {$oWhere}) as recharge_money,
                (SELECT sum(v) from table_site_detail where type = 1 and sassid = s.sassid {$oWhere}) as commission_money
                
                
             ")
            ->alias("s")
            ->order($desc)
            ->paginate(['list_rows'=>$pageCount,'page'=>$page])
            ->toArray();
        foreach ($data['data'] as $k=>$v) {
            $data['data'][$k]['time'] = date('Y-m-d',$v['time']);
        }
        return [$data['total'],$data['data']];
    }


    /**
     * 保存数据
     * @param $post
     */
    public function saveSite($post) {
        if(empty($post['sassid'])) {
            try {
                self::beginTrans();
                //判断前缀是否重复
                $count = $this->where('sub_domain', $post['sub_domain'])->count();
                if ($count > 0) {
                    self::setErrorInfo('二级域名重复');
                    return false;
                }
                $ltSassid = $this->getLastInsID();
                $params   = ['time' => time(), 'id' => $ltSassid];
                [$token, $parm] = JWT::encode($params, Env::get('app.app_key', 'default'));
                //生成密钥
                $key                = md5(time() . $token . $ltSassid);
                $post['secret_key'] = $key;
                $post['time']       = time();
                unset($post['id']);
                $sassid = $this->insertGetId($post);
                (new AdminRole)->insert([
                    'sassid'    => $sassid,
                    'name'      => '超级管理员',
                    'module'    => '',
                    'is_system' => 1
                ]);
                self::commitTrans();
                return true;
            }catch (DbException $e) {
                self::rollbackTrans();
                return false;
            }
        } else {
            $sassid = $post['sassid'];
            unset($post['sassid']);
            $this->where('sassid',$sassid)->save($post);
            return true;
        }
    }


}
