<?php

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

use app\common\model\BaseModel;
use app\common\model\school\activity\Activity;
use think\Model;
use traits\model\SoftDelete;

class OrderCode extends BaseModel
{

    use SoftDelete;

    

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

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

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


    public function getCodeimageAttr($value, $data)
    {
        if (!empty($value)) return cdnurl($value, request()->domain());
    }

    public function getCodeoneimageAttr($value, $data)
    {
        if (!empty($value)) return cdnurl($value, request()->domain());
    }


    public function getMiniurlAttr($value, $data)
    {
        $code =  (isset($data['code']) ? $data['code'] : '');
        $activity_order_id =  (isset($data['activity_order_id']) ? $data['activity_order_id'] : '');



        if (!$activity_order_id || !$code){
            return $value;
        }else{
            return $value . "?id={$activity_order_id}&code={$code}";
        }
    }



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


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


    public function getVerificationtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['verificationtime']) ? $data['verificationtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

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


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


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



    /**更新订单核销状态
     * @param $order
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function updateVerification($code,$oper_id = 0,$oper_type='user',$check=true){
        if(is_string($code))$code = self::getHaveVerificationOrderCode($code,$check);
        $code->status = "6";//refund_status
        $code->verification_user_id = $oper_id;
        $code->verification_type = $oper_type;
        $code->verificationtime = time();
        $code->save();
        return $code;
    }





    /**得到可核销订单
     * @param $order_no
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getHaveVerificationOrderCode($code,$check=true){
//        $where = [self::STATUS_NOPAY,self::STATUS_PAYED];
        $ordercode = self::where('code',$code)->where("status","in",['3'])->find();
        if(!$ordercode)throw new \Exception("当前码已存在或核销过！");
        $order = $ordercode->order;
        if(!$order)throw new \Exception("订单异常！");
        if(!$check) return $ordercode;

        if(!in_array($order["status"],['2','3']))throw new \Exception("当前订单不可核销！");
        //过了可核销时间段
        (new Activity)->update_classes($order["activity_id"]);
        $activity = $order->activity;
        if(!$activity)throw new \Exception("活动异常！");
        if(!in_array($activity["status"],["2","3","4"]))throw new \Exception("当前活动还不能核销！可能未到时间！");

        return $ordercode;
    }

    /** 强制核销订单
     * @param $code
     * @param $oper_type
     * @param $oper_id
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function forceVerification($code,$oper_type='user',$oper_id=0,$check=true)
    {

        $ordercode = self::updateVerification($code,$oper_id,$oper_type,$check);
        $order = $ordercode->order;
        if($check){

            //插入订单取消日志
            if($oper_type!='user' || $order["user_id"] !=$oper_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']);
            }

        }else{
            OrderLog::log($order['id'],"活动结束订单强制完成核销（超时结算或特殊情况）",$oper_type ?: 'user', $oper_id ?: $order['user_id']);
        }


        //调用订单取消事件
        $data = ['order' => Order::where("id",$order['id'])->find(),"user_id"=>$order["user_id"],"oper_type"=>$oper_type,"oper_id"=>$oper_id];
        \think\Hook::listen('activity_order_verification_after', $data);

        //过了可核销时间段
        (new Activity)->update_classes($order["activity_id"]);
        return $ordercode;

    }


    /**订单核销
     * @param $code
     * @param int $user_id
     * @param bool $check
     * @param bool $trans
     * @return bool
     * @throws \Exception
     */
    public  function verification($code,$user_id=0,$check=false,$oper_type='user',$oper_id=0,$trans=false){
        //得到可取消订单
        $ordercode = self::getHaveVerificationOrderCode($code,$check);
        $order = $ordercode->order;
        if(!$order) throw new \Exception("订单异常！");
        $detail = $order->detail;
        if(!$detail) throw new \Exception("订单异常！");
        if($check){
            //用户操作权限检测
            Order::checkOptionAuth($order['id'],$user_id ?: $oper_id,$oper_type,false,true);
//            if($detail["user_id"] != $user_id){
//                throw new \Exception("当前用户不是核销员！");
//            }
        }

        //判断逻辑
        if($trans){
            self::beginTrans();
        }
        $res = true;
        try{
            //事务逻辑
            //更新订单状态

            $ordercode = $this->forceVerification($code,$oper_type,$oper_id,$check);

            //检测订单完成状态
           Order::statisticsAndUpdateOrderFinish($order['id']);

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






}
