<?php

namespace app\model;

use support\Log;
use think\facade\Db;
use support\Redis;

class Orders extends base
{

    //orderStatus  1,   未付款  2 已取消  3 ,  待使用   4,   已使用  5,   已退款
    const OrderStatus = [1 => '未付款', 2 => '已取消', 3 => '待使用', 4 => '已使用', 5 => '已退款'];
    const KuaishouStatus = [1 => '已取消', 2 => '待支付', 3 => '订单确认中', 4 => '待使用', 5 => '已完成', 6 => '已过期', 7 => '待分享'];

    const DouyinReservationStatus = [1 => '未预约', 2 => '待接单', 3 => '已预约', 4 => '已取消', 5 => '已完成', 6 => '取消/退款申请'];
    const DouyinStatus = [1 => '未核销', 2 => '已核销', 3 => '申请退款中', 4 => '已退款', 5 => '部分核销'];

    // 订单状态(100 - 待付款,150-用户取消,200-待使用,205-预约中(抖音),210-已预约(抖音),310-已履约(抖音),300-已完成,400-已关闭)
    const TongchengStatus = [100 => '待付款', 150 => '用户取消', 200 => '待使用', 205 => '预约中(抖音)', 210 => '已预约(抖音)', 310 => '已履约(抖音)', 300 => '已完成', 400 => '已关闭'];

    const AllOssStatus = [1 => '待使用', 2 => '已核销', 3 => '已退款'];
    // 全部 未核销 已核销 已退款 未付款 已取消 待支付 申请退款中 部分核销
    // 0   1     2     3     4     5     6     7        8

    const AllOssStatusSql = [
        1 => '((os in (1,7) and order_status=3) or (os=2 and order_status=4) or (os in ("3", "5") and order_status=1))', //待使用
        2 => '((os in (1,7) and order_status=4) or (os=2 and order_status=5) or (os in ("3", "5") and order_status=2))', //已核销
        3 => '((os in (1,7) and order_status=5) or (os in ("3", "5") and order_status=4))' //已退款(快手暂无已退款状态)
    ];

    const StatusName = ['待跟进', '跟进中', '已核销', '核销失败', '放弃跟单'];
    const OSS = [1 => '美团(甄选)', '7' => '美团(新国旅)', 2 => '快手', 3 => '抖音(甄选)', '5' => '抖音(新国旅)', '6' => '同程', 4 => '全平台'];

    const timeType = ['create_time' => '添加记录时间', 'update_time' => '修改记录时间', 'last_follow' => '最后跟进时间', 'next_follow' => '下次跟进时间', 'travel_date' => '出行时间', 'create_at' => '下单时间'];


    // 客户端常量
    const H5_OSS = [1 => '美团官方视频号直播', '7' => '美团官方视频号直播', 2 => '快手', 3 => '抖音', '5' => '抖音', '6' => '同程'];
    const H5_STATUS_DESC = [
        // 美团
        1 => [1 => '未付款', 2 => '已取消', 3 => '未预约', 4 => '已预约', 5 => '已退款'],
        7 => [1 => '未付款', 2 => '已取消', 3 => '未预约', 4 => '已预约', 5 => '已退款'],
        // 抖音
        3 => [1 => '未核销', 2 => '已核销', 3 => '申请退款中', 4 => '已退款', 5 => '部分核销'],
        5 => [1 => '未核销', 2 => '已核销', 3 => '申请退款中', 4 => '已退款', 5 => '部分核销'],
    ];

    protected $json = ['personnel'];

    public function getOrderStatusNameAttr($val)
    {
        if ($this->os == 1 || $this->os == 7)
            return self::OrderStatus[$this->order_status] ?? '未知';
        elseif ($this->os == 3)
            return self::DouyinStatus[$this->order_status] ?? '未知';
        elseif ($this->os == 5)
            return self::DouyinStatus[$this->order_status] ?? '未知';
        elseif ($this->os == 6)
            return self::TongchengStatus[$this->order_status] ?? '未知';
        else
            return self::KuaishouStatus[$this->order_status] ?? '未知';
    }

    public function getStatusNameAttr($val)
    {
        return self::StatusName[$this->status] ?? '未知';
    }

    public function getOsNameAttr($val)
    {
        return self::OSS[$this->os] ?? '未知';
    }

    public function getH5OsNameAttr($val)
    {
        return self::H5_OSS[$this->os] ?? '未知';
    }
    public function getH5OsStatusNameAttr($val)
    {
        return self::H5_STATUS_DESC[$this->os][$this->order_status] ?? '未知';
    }

    public function getCanBookAttr($val)
    {
        $canBook = false;
        if (in_array($this->os, [1, 7]) && $this->order_status == 3) {
            $canBook = true;
        }
        return $canBook;
    }

    public function getAdminNameAttr()
    {
        if ($this->admin_id > 0) {
            return $this->admin->getData('name');
        } else {
            $aid = Redis::get('Travel:Order:' . $this->id);
            if ($aid) {
                $a = Admins::where('id', $aid)->find();
                return $a->getData('name') . '(电话中...)';
            }
        }
        return '';
    }

    public static function attimes($type, $times)
    {
        $query = self::where([]);
        if (in_array($type, array_keys(self::timeType))) {
            if (is_string($times)) {
                $times = explode(',', $times);
            } else {
                if (empty($times[0])) $times[0] = '';
                if (empty($times[1])) $times[1] = '';
            }
        }

        switch ($type) {
            case 'create_time':  //添加记录时间
                $query->whereBetween('create_time', [strtotime($times[0]), strtotime($times[1])]);
                Log::warning("==Orders====:", ['a' => strtotime($times[0]), 'b' => strtotime($times[1])]);
                break;

            case 'update_time':  //修改记录时间
                $query->whereBetween('update_time', [strtotime($times[0]), strtotime($times[1])]);
                break;

            case 'last_follow':  //最后跟进时间
                $query->whereBetween('last_follow', [strtotime($times[0]) * 1000, strtotime($times[1]) * 1000 + 999]);
                break;

            case 'next_follow':  //下次跟进时间
                $query->whereBetween('next_follow', [strtotime($times[0]) * 1000, strtotime($times[1]) * 1000 + 999]);
                break;

            case 'travel_date':  //出行时间
                $query->whereBetween('travel_date', [date('Y-m-d H:i:s', strtotime($times[0])), date('Y-m-d H:i:s', strtotime($times[1]))]);
                break;

            case 'create_at':  //下单时间
                $query->whereBetween('create_at', [strtotime($times[0]) * 1000, strtotime($times[1]) * 1000 + 999]);
                break;

            default:
                # code...
                break;
        }
        return $query;
    }

    public function admin() {
        $data = $this->belongsTo(Admins::class, 'admin_id')->visible(['name', 'username', 'avatar', 'wechat', 'wechat_pic', 'job', 'service_promise']);
        return $data;
    }

    public function anchor()
    {
        return $this->belongsTo(Admins::class, 'zhubo')->visible(['name', 'username', 'avatar']);
    }

    public function backs()
    {
        return $this->hasOne(Backs::class, 'order_id')->where('status', 0)->visible(['status', 'admin_id']);
    }

    public function follow()
    {
        return $this->hasMany(Follows::class, 'order_id')->order('id', 'desc');
    }

    public function finance()
    {
        return $this->hasMany(Finances::class, 'order_id')->order('id', 'desc');
    }

    public function product()
    {
        return $this->belongsTo(Products::class, 'product_id', 'third_product_id');
    }

    public static function fish($id, $admin_id)
    {
        return Db::transaction(function () use ($id, $admin_id) {
            $order = Orders::where('id', $id)->where('admin_id', 0)->lock(true)->find();
            if (empty($order)) return false;
            $order->admin_id = $admin_id;
            $order->give_time = time();
            $order->save();
            Logs::todo($id, $admin_id, 6);
            return true;
        });
    }

    public function mobileInfo()
    {
        return $this->hasOne(ThirdMobileLogs::class, 'mobile', 'mobile');
    }
}