<?php

namespace app\controller\manager;

use app\model\AccountRecord;
use app\model\Overview as OverviewModel;
use app\model\AccountRole;
use app\model\Appointment;
use app\model\Account;
use Exception;
use think\response\Json;
use think\response\View;

class Overview extends Base
{
    /**
     * 客户分析
     *
     * @return Json|View
     * @throws Exception
     */
    public function customer()
    {
        if ($this->request->isPost()) {
            $page    = input('page/d', 1);
            $limit   = input('size/d', 10);
            $params = input('searchParams');
            $keyword = $params['keyword'] ?? '';

            $items = OverviewModel::findList([], [], $page, $limit, function ($q) use ($keyword) {
                return $q->alias('o')->leftJoin('account a', 'a.id = o.account_id')
                    ->field('o.*,a.nickname,a.real_name,a.mobile')
                    ->when(!empty($keyword), function ($q) use ($keyword) {
                        $q->where('a.nickname|a.real_name|a.mobile', 'like', '%'.$keyword.'%');
                    })
                    ->where('a.phone_active', Account::COMMON_ON)
                    ->order('customer', 'desc')
                    ->order('shares', 'desc')
                    ->order('views', 'desc')
                    ->order('asks', 'desc');
            });

            $items['list'] = $items['list']->each(function ($item) {
                $item->position = '客户';
            });

            return $this->json(0, '操作成功', $items);
        }

        $today          = date('Y-m-d 00:00:00');
        $count['new']   = Account::where('created_at', '>', $today)->count();
        $count['total'] = Account::where('phone_active', Account::COMMON_ON)->count();

        $this->data['count'] = $count;
        return $this->view();
    }

}