<?php


namespace app\models\system;


use app\models\merchant\Merchant;
use app\models\store\StoreOrder;
use app\models\user\User;
use app\models\user\BindUser;
use crmeb\utils\Queue;
use crmeb\basic\BaseModel;
use crmeb\traits\ModelTrait;
use crmeb\jobs\ReportJob;
use crmeb\services\WechatService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Route;

class MerchantDailyReport extends BaseModel
{
    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

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

    //业绩查询结果通知
    const REPORT = '2IcjJ4Rfge8dXDUTEl2YHRKW4Bfs2Jad6qYT5AhkyY8';

    use ModelTrait;

    /**
     * 记录昨天的记录
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function recordYesterdayReport()
    {
        if (self::where('report_date', date('Y-m-d', strtotime('-1day')))->find()) {
            return;
        }
        $merchant_list = Merchant::column('id');
        foreach ($merchant_list as $v) {
            $add = [
                'mer_id' => $v,
                'report_date' => date('Y-m-d', strtotime('-1day')),
                'add_time' => time(),
                'today_reg' => User::where('mer_id', $v)->whereDay('add_time', 'yesterday')->count(),
                'today_visit' => User::where('mer_id', $v)->whereDay('last_time', 'yesterday')->count(),
                'today_order' => StoreOrder::where('mer_id', $v)->whereDay('add_time', 'yesterday')->count(),
                'today_order_money' => StoreOrder::where('paid', 1)
                    ->where('mer_id', $v)
                    ->where('is_del', 0)
                    ->where('refund_status', 0)
                    ->whereDay('pay_time', 'yesterday')
                    ->sum('pay_price'),
            ];
            self::create($add);
        }
    }

    /**
     * 发送商户报表模板消息
     */
    public static function sendMerchantMessage()
    {
        $merchant_list = Merchant::column('id');
        foreach($merchant_list as $v){
            $report = MerchantDailyReport::where('mer_id', $v)->where('report_date', date('Y-m-d', strtotime('-1day')))->find();
            if($report['state']){
                break;
            }
            $bindUser = BindUser::where(['mer_id' => $v, 'status' => 1, 'is_del' => 0])->column('openid');
            foreach($bindUser as $value){
                //发送模板消息
                Queue::instance()->do('sendMerchantMessage')->job(ReportJob::class)->data($report, $value, $v)->push();
            }
            MerchantDailyReport::where('id', $report['id'])->update(['state' => 1]);
        }
    }
}