<?php

namespace app\common\model\school\classes;


use app\common\model\BaseModel;
use app\common\model\dyqc\ManystoreShop;
use app\common\model\school\classes\order\Order;
use app\common\model\school\classes\order\OrderLog;
use app\manystore\model\Manystore;
use think\Model;


class Evaluate extends BaseModel
{

    

    

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

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

    // 追加属性
    protected $append = [
        'evaluate_time_text',
        'status_text',
        'top_text'
    ];
    

    protected static function init()
    {
        self::afterInsert(function ($row) {
            if (!$row['weigh']) {
                $pk = $row->getPk();
                $row->getQuery()->where($pk, $row[$pk])->update(['weigh' => $row[$pk]]);
            }
        });
    }

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

    public function getTopList()
    {
        return ['0' => __('Top 0'), '1' => __('Top 1')];
    }


    public function getEvaluateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['evaluate_time']) ? $data['evaluate_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $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 getTopTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['top']) ? $data['top'] : '');
        $list = $this->getTopList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setEvaluateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


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


    public function lib()
    {
        return $this->belongsTo(ClassesLib::class, 'classes_lib_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function classesorder()
    {
        return $this->belongsTo(\app\common\model\school\classes\order\Order::class, 'classes_order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function manystore()
    {
        return $this->belongsTo(Manystore::class, 'manystore_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function shop()
    {
        return $this->belongsTo(ManystoreShop::class, 'shop_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function teacher()
    {
        return $this->belongsTo(Teacher::class, 'teacher_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function getImageAttr($value, $data)
    {
        if (!empty($value)) return cdnurl($value, true);
    }


    /**得到基础条件
     * @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, ['status']))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']) && $whereData['status']) $model = $model->where("{$alisa}status", 'in', $whereData['status']);
        if (isset($whereData['not_status']) && $whereData['not_status']) $model = $model->where("{$alisa}status", 'not in', $whereData['not_status']);


        if (isset($whereData['keywords'])&&$whereData['keywords']) $model = $model->where("{$alisa}message_text|{$alisa}nickname", 'like', "%". $whereData['keywords']."%");
        if (isset($whereData['time'])&&$whereData['time']){
            $model = $model->time(["{$alisa}evaluate_time",$whereData['time']]);
        }


        return $model;
    }




    public static function evaluateList($page, $limit,$params=[]){
        $with_field = [
            'user'=>['nickname','mobile','avatar','realname'],
            'base'=>['*'],
            'shop'=>['name','logo'],
            'lib'=>['title','headimage'],
            'classesorder'=>['order_no'],
            'teacher'=>['name',"head_image"],
        ];

        $alisa = (new self)->getWithAlisaName();
        $sort = "{$alisa}.top desc,{$alisa}.weigh desc,{$alisa}.id desc";
        $serch_where = ["status"=>'1'];
        $serch_where = array_merge($serch_where,$params);
        return (new self)->getBaseList($serch_where, $page, $limit,$sort,$with_field);
    }



    /** 课程详情
     * @param $id
     * @throws \think\exception\DbException
     */
    public static function detail($id,$user_id=0,$oper_type='user',$trans=false){
        $self = self::get($id,['user','shop',"lib",'teacher','classesorder']);
        if(!$self) throw new \Exception("未找到相关数据");

        if($user_id){
            if($self["user_id"] != $user_id) throw new \Exception("非法访问");
        }

        $self->getRelation('user')->visible(['nickname','realname','mobile','avatar']);
        $self->getRelation('shop')->visible(['name','logo']);
        $self->getRelation('lib')->visible(['title','headimage']);
        $self->getRelation('classesorder')->visible(['order_no']);
        $self->getRelation('teacher')->visible(['name',"head_image"]);
        //参与人数 = 虚拟人数 + 平台人数
        return $self;
    }



    /** 课程反馈
     * @param $order_no
     * @param int $user_id
     * @param bool $check
     * @param bool $trans
     * @return bool
     * @throws \Exception
     */
    public static  function evaluate($order_no,$message_text="系统自动评价,默认给与好评",$classes_star=5,$teacher_star=5,$shop_star=5,$user_id=0,$check=false,$oper_type='user',$oper_id=0,$trans=false){

        //得到可取消订单
        $order = \app\common\model\school\classes\order\Order::getHaveEvaluateOrder($order_no);
        if($check){
            //用户操作权限检测
            \app\common\model\school\classes\hourorder\Order::checkOptionAuth($order['id'],$user_id ?: $oper_id,$oper_type,true);
        }

        $detail = $order->detail;
        $user = $order->user;
        if(!$detail)throw new \Exception("课程详情不存在");
        if(!$user)throw new \Exception("下单用户不存在");
        //已提交不让提交
        $self = self::where(['classes_order_id'=>$order['id'], "user_id"=>$order['user_id']])->find();
        if($self) throw new \Exception("课程已评价,想修改请去修改");
        //评价星级只能是数字0.5,1,1.5,2,2.5,3,3.5,4,4.5,5
        $classes_star = round($classes_star,1);
        $teacher_star = round($teacher_star,1);
        $shop_star = round($shop_star,1);
        if(!in_array($classes_star,[0.5,1,1.5,2,2.5,3,3.5,4,4.5,5])) throw new \Exception("课程评价星级只能是数字,异常");
        if(!in_array($teacher_star,[0.5,1,1.5,2,2.5,3,3.5,4,4.5,5])) throw new \Exception("老师评价星级只能是数字,异常");
        if(!in_array($shop_star,[0.5,1,1.5,2,2.5,3,3.5,4,4.5,5])) throw new \Exception("上课环境星级只能是数字,异常");

        $data = [
            'user_id'=>$order['user_id'],
            'classes_lib_id'=>$order['classes_lib_id'],
            'classes_order_id'=>$order['id'],
            'manystore_id'=>$order['manystore_id'],
            'shop_id'=>$order['shop_id'],
            'teacher_id' =>$detail['teacher_id'],
            'image'=>$user["avatar"],
            'nickname'=>$user["nickname"],
            'evaluate_time'=>time(),
            'status'=>'1',
            'weigh'=>0,
            'message_text'=>$message_text,
            'classes_star'=>$classes_star,
            'teacher_star'=>$teacher_star,
            'shop_star'=>$shop_star,
        ];


        //判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
            //事务逻辑
            $classes_evaluate = self::create($data);
            $classes_evaluate_id = $classes_evaluate->id;


            //更新订单评价状态
            $order = Order::updateEvaluate($order,$classes_evaluate_id);
            //插入订单取消日志
            if(!$user_id ||$order["user_id"] !=$user_id ){
                OrderLog::log($order['id'],"[系统操作]课程订单评价成功",$oper_type ?: 'user', $oper_id ?: $order['user_id']);
            }else{
                OrderLog::log($order['id'],"课程订单评价成功",$oper_type ?: 'user', $oper_id ?: $order['user_id']);
            }

            //调用订单取消事件
            $data = ['order' => $order,"classes_evaluate"=>$classes_evaluate,"user_id"=>$user_id,"oper_type"=>$oper_type,"oper_id"=>$oper_id];
            \think\Hook::listen('classes_order_evaluate_after', $data);
            //执行课时数更新
            $res1 = order::statisticsAndUpdateClassesNumber($order['id']);


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




    /** 课程反馈修改
     * @param $order_no
     * @param int $user_id
     * @param bool $check
     * @param bool $trans
     * @return bool
     * @throws \Exception
     */
    public static  function evaluateUpdate($order_no,$message_text="系统自动评价,默认给与好评",$classes_star=5,$teacher_star=5,$shop_star=5,$user_id=0,$check=false,$oper_type='user',$oper_id=0,$trans=false){

        //得到可取消订单
        $order = \app\common\model\school\classes\order\Order::getHaveEvaluateOrder($order_no);
        if($check){
            //用户操作权限检测
            \app\common\model\school\classes\hourorder\Order::checkOptionAuth($order['id'],$user_id ?: $oper_id,$oper_type,true);
        }
        $detail = $order->detail;
        $user = $order->user;
        if(!$detail)throw new \Exception("课程详情不存在");
        if(!$user)throw new \Exception("下单用户不存在");
        //已提交不让提交
        $self = self::where(['classes_order_id'=>$order['id'], "user_id"=>$order['user_id']])->find();
        if(!$self) throw new \Exception("课程未评价,请先去评价");

        //超出评价修改次数
        $classes_evaluate_number = config("site.classes_evaluate_number");
        if($self['update_number'] >= $classes_evaluate_number){
            throw new \Exception("已超过评价修改次数,无法继续修改");
        }

        $classes_star = round($classes_star,1);
        $teacher_star = round($teacher_star,1);
        $shop_star = round($shop_star,1);
        if(!in_array($classes_star,[0.5,1,1.5,2,2.5,3,3.5,4,4.5,5])) throw new \Exception("课程评价星级只能是数字,异常");
        if(!in_array($teacher_star,[0.5,1,1.5,2,2.5,3,3.5,4,4.5,5])) throw new \Exception("老师评价星级只能是数字,异常");
        if(!in_array($shop_star,[0.5,1,1.5,2,2.5,3,3.5,4,4.5,5])) throw new \Exception("上课环境星级只能是数字,异常");


        $data = [
            'user_id'=>$order['user_id'],
            'classes_lib_id'=>$order['classes_lib_id'],
            'classes_order_id'=>$order['id'],
            'manystore_id'=>$order['manystore_id'],
            'shop_id'=>$order['shop_id'],
            'teacher_id' =>$detail['teacher_id'],
            'image'=>$user["avatar"],
            'nickname'=>$user["nickname"],
            'message_text'=>$message_text,
            'classes_star'=>$classes_star,
            'teacher_star'=>$teacher_star,
            'shop_star'=>$shop_star,
        ];



        //判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
            //修改次数+1
            $data['update_number'] = $self['update_number'] + 1;
            //事务逻辑
            $self->save($data);

            $classes_evaluate = $self;
            $classes_evaluate_id = $self->id;


            //更新订单评价状态
            $order = Order::updateEvaluate($order,$classes_evaluate_id);
            //插入订单取消日志
            if(!$user_id ||$order["user_id"] !=$user_id ){
                OrderLog::log($order['id'],"[系统操作]课程订单评价修改成功",$oper_type ?: 'user', $oper_id ?: $order['user_id']);
            }else{
                OrderLog::log($order['id'],"课程订单评价修改成功",$oper_type ?: 'user', $oper_id ?: $order['user_id']);
            }

            //调用订单取消事件
            $data = ['order' => $order,"classes_evaluate"=>$classes_evaluate,"user_id"=>$user_id,"oper_type"=>$oper_type,"oper_id"=>$oper_id];
            \think\Hook::listen('classes_order_evaluate_update_after', $data);
            //执行课时数更新
            $res1 = order::statisticsAndUpdateClassesNumber($order['id']);


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






    /** 课程评价统计
     * @param $order_no
     * @param int $user_id
     * @param bool $check
     * @param bool $trans
     * @return bool
     * @throws \Exception
     */
    public static  function evaluateStatistics($id,$trans=false){

        $self = self::where(['id'=>$id])->find();
        if(!$self) return false;


        //判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
            //统计老师评分
            $teacher =  $self->teacher; //teacher_star
            if($teacher){

                //求所有评价平均值,最终值必须四舍五入在0.5,1,1.5,2,2.5,3,3.5,4,4.5,5
              $count = self::where("teacher_id",$teacher['id'])->count();
              if($count){
                  $teacher_star = self::where("teacher_id",$teacher['id'])->avg("teacher_star");
                  $teacher_star = round($teacher_star,1);
                  //最终值必须在0.5,1,1.5,2,2.5,3,3.5,4,4.5,5 这几个数字中
                  $teacher_star_arr = [0.5,1,1.5,2,2.5,3,3.5,4,4.5,5];
                  //循环$teacher_star_arr 找到最接近的
                  foreach ($teacher_star_arr as $k=>$v){
                      if(abs($v-$teacher_star) < 0.5){
                          $teacher_star = $v;
                          break;
                      }
                  }
              }else{
                  $teacher_star = 5;
              }
                $teacher->save(['teacher_star'=>$teacher_star,'star_number'=>$count]);
            }

            $shop =  $self->shop; //shop_star
            if($shop){
                $count = self::where("shop_id",$shop['id'])->count();
                if($count){
                    $shop_star = self::where("shop_id",$shop['id'])->avg("shop_star");
                    $shop_star = round($shop_star,1);
                    //最终值必须在0.5,1,1.5,2,2.5,3,3.5,4,4.5,5 这几个数字中
                    $shop_star_arr = [0.5,1,1.5,2,2.5,3,3.5,4,4.5,5];
                   //循环$teacher_star_arr 找到最接近的
                    foreach ($shop_star_arr as $k=>$v){
                        if(abs($v-$shop_star) < 0.5){
                            $shop_star = $v;
                            break;
                        }
                    }
                }else{
                    $shop_star = 5;
                }
                $shop->save(['shop_star'=>$shop_star,'star_number'=>$count]);
            }
            $lib =  $self->lib; //classes_star
            if($lib){
                $count = self::where("classes_lib_id",$lib['id'])->count();
                if($count){
                    $classes_star = self::where("classes_lib_id",$lib['id'])->avg("classes_star");
                    $classes_star = round($classes_star,1);
                    //最终值必须在0.5,1,1.5,2,2.5,3,3.5,4,4.5,5 这几个数字中
                    $classes_star_arr = [0.5,1,1.5,2,2.5,3,3.5,4,4.5,5];
                    //循环$teacher_star_arr 找到最接近的
                    foreach ($classes_star_arr as $k=>$v){
                        if(abs($v-$classes_star) < 0.5){
                            $classes_star = $v;
                            break;
                        }
                    }

                }else{
                    $classes_star = 5;
                }
                $lib->save(['classes_star'=>$classes_star,'star_number'=>$count]);
            }



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






}