<?php
namespace app\open\controller;
use app\common\model\User as UserModel;
use app\common\model\UserInfo as UserInfoModel;
use app\common\model\JobsDeliveryResume as JobsDeliveryResumeModel;
use app\common\model\InviteAninterview as InviteAninterviewModel;
use app\common\model\Orders as OrdersModel;
use app\common\model\Statistics as StatisticsModel;
use app\common\model\CrmStatistics as CrmStatisticsModel;
use app\bsadmin\model\Admin as AdminModel;
use app\common\model\CrmCustomer as CrmCustomerModel;
class Statistics extends Base
{
	public function bsadmin_charts_statistics()
	{
		$StatisticsModel=StatisticsModel::whereDay('create_time','yesterday')->find();
		if(!$StatisticsModel)
			$StatisticsModel=new StatisticsModel;
		$StatisticsModel->new_user=UserModel::whereDay('create_time','yesterday')->count();
		$StatisticsModel->personal_new_user=UserInfoModel::where(['role_type'=>0])->whereDay('create_time','yesterday')->count();
		$StatisticsModel->company_new_user=UserInfoModel::where(['role_type'=>1])->whereDay('create_time','yesterday')->count();
		$StatisticsModel->delivery_resume=JobsDeliveryResumeModel::whereDay('create_time','yesterday')->count();
		$StatisticsModel->invite_aninterview=InviteAninterviewModel::whereDay('create_time','yesterday')->count();
		$StatisticsModel->orders_sum=OrdersModel::where(['status'=>2])->whereDay('create_time','yesterday')->count();
		$StatisticsModel->order_price=OrdersModel::where(['status'=>2])->whereDay('create_time','yesterday')->sum('oprice');
		$StatisticsModel->create_time=strtotime(date('Y-m-d ',strtotime("-1 days",time())).'4:30:00');
		$StatisticsModel->save();
		return 'success';
	}
	public function bsadmin_crm_charts_statistics()
	{
		$CrmStatisticsModel=CrmStatisticsModel::whereDay('create_time','yesterday')->count();
		if($CrmStatisticsModel)
			return 'fail';
        $AdminModel=AdminModel::whereIn('role_id',config('xy_crm.admin_role_id'))->field('id,nickname')->select();
        if (!$AdminModel->isEmpty()) {
			$CrmStatisticsModel=new CrmStatisticsModel;
			$CrmStatisticsData=[];
			foreach ($AdminModel as $admin) {
				$CrmStatisticsData[]=[
					'adviser_id'	=>	$admin->id,
					'new_customer'	=>	CrmCustomerModel::where(['adviser_id'=>$admin->id])->whereDay('adviser_time','yesterday')->count(),
					'follow_up_customer'=>	CrmCustomerModel::where(['adviser_id'=>$admin->id])->whereDay('last_follow_up_time','yesterday')->count(),
					'create_time'=>strtotime(date('Y-m-d ',strtotime("-1 days",time())).'4:30:00')
				];
			}
			$CrmStatisticsModel->saveAll($CrmStatisticsData);
        }else{
			return 'admin is empty';
        }
	}
}