<?php

namespace app\server;

use app\common\Error;
use app\model\Admins as AdminsModel;
use app\model\FilterMobiles;
use app\model\Finances as FinancesModel;
use app\model\Orders as OrdersModel;
use support\Log;
use support\Redis;

class Orders {
    public static function isDaishiyong(OrdersModel $order): bool
    {
        // 根据 OrdersModel::AllOssStatusSql[1] 进行判断
        // ((os=1 and order_status=3) or (os=2 and order_status=4) or (os=3 and order_status=1))
        return ($order->os == 1 && $order->order_status == 3)
            || ($order->os == 2 && $order->order_status == 4)
            || ($order->os == 3 && in_array($order->order_status, [1, 5]));
    }

    /**
     * @params []OrdersModel $order
     * @return array
     */
    public static function reminderOrders(OrdersModel ...$orders)
    {
        $admin_ids = [];
        $sns = [];

        foreach ($orders as $order) {
            $admin_ids[] = $order->admin_id;
            $sns[] = $order->sn;
        }

        $admins = AdminsModel::whereIn('id', $admin_ids)->select()->column('mobile', 'id');

        if (empty($admins)) {
            return array_fill_keys($sns, Error::undefined('admin check error'));
        }

        $ttl    = 86400;
        $result = [];

        $admins = array_column($admins, null, 'id');
        foreach($orders as $order) {
            $admin_mobile = $admins[$order->admin_id] ?? '';

            if (empty($order->mobile) || empty($admin_mobile)) {
                $result[$order->sn] = Error::undefined('client mobile or admin mobile invalid');
                continue;
            }
            if (FilterMobiles::isFilterMobile($order->mobile)) {
                $result[$order->sn] = Error::undefined('刷单账单');
                continue;
            }
            $admin_mobile = $admin_mobile['mobile'] ?? '';

            if (Blacks::CExists($order->mobile)) {
                $result[$order->sn] = Error::ERR_SMS_BLACKS;
                Log::info(__METHOD__ . " blacks", [$order->mobile, $order->sn]);
                continue;
            }

            $key = sprintf("CRM:%s:%s_%s", 'reminderOrders', $order->sn, $order->mobile);
            $ok  = Redis::set($key, time(), 'EX', $ttl, 'NX');

            if (!$ok) {
                $result[$order->sn] = Error::undefined('reminder cooldown');
                continue;
            }

            $res = SMS::juhe_sms_send($order->mobile, SMS::JUHE_TMP_REMINDER_ORDER, ['title' => $order->product_name, 'mobile' => $admin_mobile]);
            $err_code = $res['error_code'] ?? 0;

            if ($err_code != 0) {
                Log::error(__METHOD__ . " send error", [$res, $order->mobile, $order->sn]);
                $result[$order->sn] = Error::ERR_SMS_SEND_FAIL;
                continue;
            }

            $result[$order->sn] = [];
        }

        return count($orders) > 1 ? $result : reset($result);
    }

    public static function syncFromThird(OrdersModel $order)
    {
        $got = null;

        switch ($order->os) {
            case 1:
            case 7:
                $mt = new Meituan($order->os);
                $it = $mt->get(1, null, null, $order->sn);

                if ($it) {
                    $got = $it[0];
                }

                break;
            case 3:
            case 5:
                $dy = new Douyin($order->os);
                $it = $dy->get(1, null, null, $order->sn);
                if ($it) {
                    $got = $it[0];

                    // 查询未预约状态
                    if ($order->appointment_status == 0) {
                        $appointment_status = $dy->_orderMakeAppointmentStatus($order->sn);
                        if ($appointment_status !== null) {
                            $got['appointment_status'] = 1;
                        }
                    }
                }

                break;
        }

        if (is_null($got)) {
            Log::info(__METHOD__ . ": get from os is null", [$order]);
            return;
        }

        $back = $order->save($got);

        if ($back) {
            self::finance(0, $order->id, $order->asset_price);
        }

        return 0;
    }

    public static function finance($type = 1, $order_id = 0, $price = 0)
    {
        //总的关于这个订单的金额
        $total = FinancesModel::where('order_id', $order_id)->sum('total');
        //如果总金额大于提交上来的核销金额,那就是退费的
        //如果提交上来的金额小于总金额,那就是核销的

        if ($total > $price) {
            $type = 2;
            $fee = -($total - $price);
        } elseif ($total < $price) {
            $type = 1;
            $fee = $price - $total;
        } else {
            return;
        }

        FinancesModel::create([
            'order_id' => $order_id,
            'type' => $type,
            'total' => $fee,
            'status' => 1
        ]);

        return;
    }

    /**
     * 同步第三方返回
     * @param OrdersModel $order
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function syncFromThirdV2(OrdersModel $order)
    {
        $got = null;
        switch ($order->os) {
            case 1:
            case 7:
                $mt = new Meituan($order->os);
                $it = $mt->get(1, null, null, $order->sn);

                if ($it) {
                    $got = $it[0];
                }

                break;
            case 3:
            case 5:
                $dy = new Douyin($order->os);
                $it = $dy->get(1, null, null, $order->sn);
                if ($it) {
                    $got = $it[0];
                }

                break;
        }

        if (is_null($got)) {
            Log::info(__METHOD__ . ": get from os is null", [$order]);
            return $order;
        }

        $back = $order->save($got);

        if ($back) {
            self::finance(0, $order->id, $order->asset_price);
        }

        return $order;
    }
}