<?php

namespace app\common\model\school\classes\order;

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


class ServiceOrderLog extends BaseModel
{

    

    

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

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

    // 追加属性
    protected $append = [
        'status_text',
        'service_stauts_text',
        'sales_type_text'
    ];
    

    
    public function getStatusList()
    {
        return ['1' => __('Status 1'), '4' => __('Status 4'), '7' => __('Status 7'), '-3' => __('Status -3')];
    }

    public function getServiceStautsList()
    {
        return ['1' => __('Service_stauts 1'), '4' => __('Service_stauts 4'), '7' => __('Service_stauts 7'),'10' => __('Service_stauts 10'), '-3' => __('Service_stauts -3')];
    }

    public function getSalesTypeList()
    {
        return ['-3' => __('Sales_type -3'), '1' => __('Sales_type 1'), '4' => __('Sales_type 4'), '7' => __('Sales_type 7'), '10' => __('Sales_type 10')];
    }


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


    public function getServiceStautsTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['service_stauts']) ? $data['service_stauts'] : '');
        $list = $this->getServiceStautsList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getSalesTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sales_type']) ? $data['sales_type'] : '');
        $list = $this->getSalesTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


            public function getRejectImagesAttr($value, $data)
    {
        $imagesArray = [];
        if (!empty($value)) {
            $imagesArray = explode(',', $value);
            foreach ($imagesArray as &$v) {
                $v = cdnurl($v, true);
            }
            return $imagesArray;
        }
        return $imagesArray;
    }




    public function serviceorder()
    {
        return $this->belongsTo(ServiceOrder::class, 'classes_service_order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function classesorder()
    {
        return $this->belongsTo(Order::class, 'classes_order_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


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


    public function detail()
    {
        return $this->belongsTo(OrderDetail::class, 'classes_order_detail_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


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



        /**记录订单日志
     * @param $params
     * @param bool $trans
     * @throws \Exception
     */
    public static function log($order,$mark='更新订单状态',$oper_type='user',$oper_id = 0,$trans=false){
//        var_dump($order);
        if(is_numeric($order)||is_string($order))$order = ServiceOrder::where('order_no|id',$order)->find();


        if(!$order)throw new \Exception("找不到订单");
        //操作人信息（可扩展）
        $data = [
            'oper_type'=>$oper_type ?: 'user',
            'oper_id'=>$oper_id ?: $order['user_id'],
            'log_text'=>$mark,
        ];
        //判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
            //事务逻辑
            $log_data = $order->toArray();
            $log_data["classes_service_order_id"] = $order['id'];
            unset($log_data['id']);
            unset($log_data['createtime']);
            if($mark)$log_data['log_text'] = $mark;


            $log_data = array_merge($log_data,$data);

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


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

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


        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}order_no|{$alisa}id|{$alisa}reason", '=', $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}user_id", '=', $whereData['user_id']);


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

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

        //classes_order_detail_id

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


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

        return $model;
    }






    public static function allList($user_id,$page, $limit,$keywords,$status,$service_stauts,$sales_type,$classes_service_order_id=[]){
        $with_field = [
            'user'=>['nickname','mobile','avatar','realname'],
            'base'=>['*'],
            'classesorder'=>['*'],
            'detail'=>['*'],
        ];

        $alisa = (new self)->getWithAlisaName();
        $sort = "{$alisa}.id desc";
        $serch_where = ['status'=>$status,'user_id'=>$user_id,
            'keywords'=>$keywords,"classes_service_order_id"=>$classes_service_order_id,
            "service_stauts"=>$service_stauts,"sales_type"=>$sales_type
        ];
//        if($type)$serch_where['type'] = $type;
        return (new self)->getBaseList($serch_where, $page, $limit,$sort,$with_field);
    }



     public static function workList($page, $limit,$keywords,$status,$service_stauts,$sales_type,$classes_service_order_id=[],$classes_lib_ids=[]){
        $with_field = [
            'user'=>['nickname','mobile','avatar','realname'],
            'base'=>['*'],
            'classesorder'=>['*'],
            'detail'=>['*'],
        ];

       $alisa = (new self)->getWithAlisaName();
       $sort = "{$alisa}.id desc";
        $serch_where = ['status'=>$status,'keywords'=>$keywords,"classes_service_order_id"=>$classes_service_order_id,"classes_lib_ids"=>$classes_lib_ids
        ,"service_stauts"=>$service_stauts,"sales_type"=>$sales_type
        ];
//        if($type)$serch_where['type'] = $type;
        return (new self)->getBaseList($serch_where, $page, $limit,$sort,$with_field);
    }



}
