<?php

namespace app\common\model\school;

use app\common\model\BaseModel;
use think\Model;


class Message extends BaseModel
{

    

    

    // 表名
    protected $name = 'school_message';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

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

    // 追加属性
    protected $append = [
        'platform_text',
        'oper_type_text',
        'to_type_text',
        'status_text',
        'mini_type_text',
        "type_text",
        'createtime_text',
    ];

          public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y.m.d|H:i", $value) : $value;
    }



    public function getTypeList()
    {
        return ['1' => __('Type 1'), '2' => __('Type 2')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }




    public function getPlatformList()
    {
        return ['admin' => __('Platform admin'), 'user' => __('Platform user'), 'shop' => __('Platform shop')];
    }

    public function getOperTypeList()
    {
        return ['admin' => __('Oper_type admin'), 'user' => __('Oper_type user'), 'system' => __('Oper_type system'), 'shop' => __('Oper_type shop')];
    }

    public function getToTypeList()
    {
        return ['admin' => __('To_type admin'), 'user' => __('To_type user'), 'system' => __('To_type system'), 'shop' => __('To_type shop')];
    }

    public function getStatusList()
    {
        return ['system' => __('Status system'), 'classes' => __('Status classes'), 'order' => __('Status order'),'activity' => __('Status activity')];
    }

    public function getMiniTypeList()
    {
        return ['order_notice' => __('Mini_type order_notice'), 'classes_auth' => __('Mini_type classes_auth'), 'classes_apply' => __('Mini_type classes_apply') , 'activity_apply' => __('Mini_type activity_apply'), 'shop_apply' => __('Mini_type shop_apply'), 'classes_order_notice' => __('Mini_type classes_order_notice'), 'user_auth' => __('Mini_type user_auth'), 'aftercare' => __('Mini_type aftercare'), 'other' => __('Mini_type other'),'activity_order' => __('Mini_type activity_order')];
    }


    public function getPlatformTextAttr($value, $data)
    {
        $value = $value ?: ($data['platform'] ?? '');
        $valueArr = explode(',', $value);
        $list = $this->getPlatformList();
        return implode(',', array_intersect_key($list, array_flip($valueArr)));
    }


    public function getOperTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['oper_type']) ? $data['oper_type'] : '');
        $list = $this->getOperTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getToTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['to_type']) ? $data['to_type'] : '');
        $list = $this->getToTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


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


    public function getMiniTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['mini_type']) ? $data['mini_type'] : '');
        $list = $this->getMiniTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setPlatformAttr($value)
    {
        return is_array($value) ? implode(',', $value) : $value;
    }


    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'oper_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function user()
    {
        return $this->belongsTo('app\admin\model\User', 'to_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


     public function messageevent()
    {
        return $this->belongsTo(MessageConfig::class, 'event', 'event', [], 'LEFT')->setEagerlyType(0);
    }



    public static $event_name = "";

    /**  发送站内信
     * @param $title 站内信标题
     * @param $desc  内容
     * @param $mini_type 消息子类型
     * @param $to_id 接收者id
     * @param $to_type 接收者类型
     * @param $status  消息大类型
     * @param $platform 发送平台
     * @param $params 额外参数
     * @param $oper_id  发送人id
     * @param $oper_type  发送人类型
     *
     */
    public static function send($title,$desc,$mini_type,$to_id,$to_type="user",$status="system",$platform="user",$params=[],$oper_id=0,$oper_type="system"){
        $data = [
            'title' => $title,
            'desc' => $desc,
            'params' => json_encode($params),
            'platform' => $platform,
            'oper_id' => $oper_id,
            'oper_type' => $oper_type,
            'to_id' => $to_id,
            'to_type' => $to_type,
            'status' => $status,
            'mini_type' => $mini_type,
            "event" =>self::$event_name ?? "",
        ];
        $message = new self();
        $message->save($data);
        return $message;
    }



    /**展示订单信息
     * @param $order_no
     * @param $price_info
     * @return array
     */
    public static function showInfo($id, $price_info = []){
        $data = [];
        $data['id'] =$id;
        $data['message_info'] = self::getDetail($id);
        return array_merge($data,$price_info);
    }




    /**得到订单详情
     * @param $order_no
     */
    public static function getDetail($id,$oper_id = []){
        $model = self::where('id',$id);
        if($oper_id)$model = $model->where("oper_id","in",$oper_id);
        $data = $model->find();

        if(!$data)  return $data;

        //如果非全局消息,更新成已读

        if($data->to_id != 0){
            $data["type"]= '2';
            $data->save();
        }

        //
       $data->messageevent;
//        //加载订单详情
//        $data->detail->teacher;
//        //订单用户
////        $data->user;
//        $data->user->visible(['id','nickname','mobile','avatar','realname']);
//

        return $data;
    }








    /**得到基础条件
     * @param $status
     * @param null $model
     * @param string $alisa
     */
    public static function getBaseWhere($whereData = [], $model = null, $alisa = '',$with = false)
    {

        if (!$model) {
            $model = new static;
            if ($alisa&&!$with) $model = $model->alias($alisa);
        }
        if ($alisa) $alisa = $alisa . '.';
        $tableFields = (new static)->getTableFields();
        foreach ($tableFields as $fields)
        {
            if(in_array($fields, ['platform','oper_type','to_type','status','mini_type','to_id']))continue;
//            if (isset($whereData[$fields]) && $whereData[$fields]) $model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);

            if (isset($whereData[$fields]) && $whereData[$fields]){
                if(is_array($whereData[$fields])){
                    $model = $model->where("{$alisa}{$fields}", $whereData[$fields][0], $whereData[$fields][1]);
                }else{
                    $model = $model->where("{$alisa}{$fields}", '=', $whereData[$fields]);
                }

            }


        }
        if (isset($whereData['status'])) $model = $model->where("{$alisa}status", 'in', $whereData['status']);
        if (isset($whereData['not_status'])) $model = $model->where("{$alisa}status", 'not in', $whereData['not_status']);
        if (isset($whereData['keywords'])&&$whereData['keywords']) $model = $model->where("{$alisa}id|{$alisa}title|{$alisa}desc", '=', $whereData['keywords']);
        if (isset($whereData['time'])&&$whereData['time']){
            $model = $model->time(["{$alisa}createtime",$whereData['time']]);
        }
        if (isset($whereData['user_id']) && $whereData['user_id']) $model = $model->where("{$alisa}to_id", '=', $whereData['user_id']);

        if (isset($whereData['platform']) && $whereData['platform']){
            $platforms =  implode("|",explode(',',$whereData['platform']));
            $model = $model->whereRaw(" {$alisa}platform REGEXP '({$platforms})'");
//            $model = $model->where("{$alisa}platform", 'in', $whereData['platform']);
        }


        if (isset($whereData['oper_type']) && $whereData['oper_type']) $model = $model->where("{$alisa}oper_type", 'in', $whereData['oper_type']);
        if (isset($whereData['to_type']) && $whereData['to_type']) $model = $model->where("{$alisa}to_type", 'in', $whereData['to_type']);
        if (isset($whereData['mini_type']) && $whereData['mini_type']) $model = $model->where("{$alisa}mini_type", 'in', $whereData['mini_type']);


        if (isset($whereData['to_id']) && $whereData['to_id']){
            $model = $model->where(function ($query) use($whereData,$alisa) {
                $query->where("{$alisa}to_id", $whereData['to_id'])
                    ->whereOr("{$alisa}to_id", '=', 0);
            });
        }


        return $model;
    }






    public static function baseCount($where = []){
        $where["type"] = '1';
        $where["platform"]= 'user';
        $unread_number =    self::getBaseWhere($where)->count();
        $unread_system_number =     self::getBaseWhere(array_merge(['status'=>'system'],$where))->count();
        $unread_classes_number =     self::getBaseWhere(array_merge(['status'=>'classes'],$where))->count();
        $unread_order_number =  self::getBaseWhere(array_merge(['status'=>'order'],$where))->count();
        $unread_activity_number =  self::getBaseWhere(array_merge(['status'=>'activity'],$where))->count();;


        $where["type"] = '2';
        $read_number =    self::getBaseWhere($where)->count();
        $read_system_number =     self::getBaseWhere(array_merge(['status'=>'system'],$where))->count();
        $read_classes_number =     self::getBaseWhere(array_merge(['status'=>'classes'],$where))->count();
        $read_order_number =  self::getBaseWhere(array_merge(['status'=>'order'],$where))->count();
        $read_activity_number =  self::getBaseWhere(array_merge(['status'=>'activity'],$where))->count();


        return compact("unread_activity_number",'unread_number','unread_system_number','unread_classes_number','unread_order_number',
        'read_number','read_system_number','read_classes_number','read_order_number',"read_activity_number");
    }



    /**订单数量统计
     * @param int $user_id
     * @return array
     */
    public static function messageCount($user_id = 0){

        if(!$user_id){
             $unread_number =   0;
        $unread_system_number =  0;
        $unread_classes_number =  0;
        $unread_order_number =  0;

        $unread_activity_number =  0;

        $read_number =   0;
        $read_system_number =  0;
        $read_classes_number =  0;
        $read_order_number =  0;
        $read_activity_number =  0;

        return compact('unread_number',
            'unread_system_number',
            'unread_classes_number',
            'unread_activity_number',
            'unread_order_number',
            'read_number',
            'read_system_number',
            'read_classes_number',
            'read_order_number',
            'read_activity_number'
        );
        }

        return self::baseCount(['user_id'=>$user_id]);
    }





    public static function messageList($page, $limit,$to_id,$keywords,$status,$mini_type,$type,$time=null){
        $with_field = [
            'user'=>['nickname','mobile','avatar','realname'],
            'messageevent'=>['event','logo_image'],
            'base'=>['*'],
//            'shop'=>['*'],
//            'detail'=>['*'],
        ];

        $alisa = (new self)->getWithAlisaName();
        $sort = "{$alisa}.weigh desc,{$alisa}.id desc";
//        $sort = "field({$alisa}.type,'1','2') asc,{$alisa}.weigh desc,{$alisa}.id desc";
        $serch_where = ["to_id"=>$to_id,'platform'=>"user",'status'=>$status,'keywords'=>$keywords,"mini_type"=>$mini_type,"type"=>$type,"time"=>$time];
//        if($type)$serch_where['type'] = $type;
        return (new self)->getBaseList($serch_where, $page, $limit,$sort,$with_field);
    }






    /**设置一键已读
     * @param $id
     * @param int $user_id
     * @param bool $check
     * @param bool $trans
     * @throws \Exception
     */
    public static function batchRead($id,$user_id,$status=null,$mini_type=null,$event=null,$oper_type='user',$oper_id=0,$trans=false){
        //匹配已读查询条件

        $model = self::where("to_id",$user_id);
        if($status)$model = $model->where("status","in","".$status);
        if($mini_type)$model = $model->where("mini_type","in","".$mini_type);
        if($event)$model = $model->where("event","in","".$event);
        if($id && $id!="*")$model = $model->where("id","in","".$id);
        //判断逻辑
        if($trans){
            self::beginTrans();
        }

        try{
            //事务逻辑
             $ids = $model->column("id");
             //$ids逗号拼接
             $ids = implode(",",$ids);
             //合并成数组
             $update_data = ['type'=>'2'];
             self::where("id","in",$ids)->update($update_data);

             //调用事件
//            $data = ['classes' => $classes_lib,"user_id"=>$user_id,"oper_type"=>$oper_type,"oper_id"=>$oper_id];
//            \think\Hook::listen('classes_view_after', $data);

            if($trans){
                self::commitTrans();
            }
        }catch (\Exception $e){
            if($trans){
                self::rollbackTrans();
            }
            throw new \Exception($e->getMessage());
        }
        return true;
    }




}
