<?php
/*
 * @Author: xiaohai zmhwork@qq.com
 * @Date: 2025-03-14 17:38:50
 * @LastEditors: xiaohai zmhwork@qq.com
 * @LastEditTime: 2025-03-17 18:43:05
 * @FilePath: \opkpm\app\shop\logic\order\OrderRenewLogic.php
 * @Description: 续费订单逻辑处理
 */

namespace app\shop\logic\order;

use app\common\model\shop\OrderRenew;
use app\common\model\shop\ShopGoodsRenew;

use app\common\basics\Logic;
use app\common\enum\OrderEnum;
use app\common\model\shop\Shop;
use app\common\model\shop\ShopHkLog;
use app\common\server\AliPayServer;
use app\common\server\YansongdaAliPayServer;
use app\shop\validate\order\OrderRenewValidate;
use think\facade\Db;
use think\facade\Log;
use Yansongda\Pay\Pay;

class OrderRenewLogic extends Logic
{
    public static function lists($get)
    {
        $page = $get['page'] ?? 1;
        $limit = $get['limit'] ?? 10;

        $where[] = ['del', '=', 0];
        $where[] = ['shop_id', '=', $get['shop_id']];

        $count = OrderRenew::where($where)->count();
        $lists = OrderRenew::where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()->toArray();
        foreach ($lists as $key => $value) {
            $lists[$key]['type_str'] = $value['renew_type_id'] == 0 ? '包月' : '按量付费';
            $lists[$key]['order_status_str'] = OrderEnum::getOrderStatus($value['order_status']);
            $lists[$key]['pay_status_str'] = OrderEnum::getPayStatus($value['pay_status']);
            $lists[$key]['pay_way_str'] = $value['pay_way'] == 1 ? '微信' : '支付宝';
            $lists[$key]['pay_time_str'] = $value['pay_time'] ? date('Y-m-d H:i:s', $value['pay_time']) : '';
        }

        return ['count' => $count, 'lists' => $lists];
    }

    public static function renewLists($get)
    {
        $page = $get['page'] ?? 1;
        $limit = $get['limit'] ?? 10;

        $where = [
            ['del', '=', 0],
            ['status', '=', 1]
        ];

        if (!empty($get['name']) && $get['name']) {
            $where[] = ['name', 'like', '%' . $get['name'] . '%'];
        }
        // var_dump($get, $where);        

        $count = ShopGoodsRenew::where($where)->count();
        $lists = ShopGoodsRenew::where($where)
            ->page($page, $limit)
            ->order('id', 'desc')
            ->select()->toArray();
        foreach ($lists as $key => $value) {
            $lists[$key]['type_str'] = $value['type_id'] == 0 ? '包月' : '按量付费';
            $lists[$key]['status_str'] = $value['status'] == 0 ? '禁用' : '启用';
        }

        return ['count' => $count, 'lists' => $lists];
    }

    public static function buy($id)
    {
        $where = [
            ['del', '=', 0],
            ['status', '=', 1],
            ['id', '=', $id]
        ];
        $info = ShopGoodsRenew::where($where)->find();
        if (!$info) {
            static::$error = '数据不存在';
            return false;
        }

        return $info->toArray();
    }

    
    public static function cancel($post)
    {
        try {
            validate(OrderRenewValidate::class)->scene('cancel')->check($post);
        } catch (\Exception $e) {
            static::$error = $e->getMessage();
            return false;
        }

        $where = [
            ['del', '=', 0],
            ['id', '=', $post['id']],
            ['shop_id', '=', $post['shop_id']],
        ];

        $info = OrderRenew::where($where)->find();
        if (!$info) {
            self::$error = '数据不存在';
            return false;
        }

        if ($info->order_status > 0) {
            self::$error = '订单状态不可取消';
            return false;
        }

        $info->order_status = 4;
        $info->save();

        return true;
    }

    public static function add($post)
    {
        try {
            validate(OrderRenewValidate::class)->scene('add')->check($post);
        } catch (\Exception $e) {
            static::$error = $e->getMessage();
            return false;
        }

        $model = new OrderRenew();
        $name = $model->getName();
        $post['order_sn'] = createSn($name, 'order_sn');
        $post['renew_name'] = $post['name'];
        $post['renew_image'] = $post['image'];
        $post['renew_desc'] = $post['desc'];
        $post['renew_type_id'] = $post['type_id'];
        $post['renew_price'] = $post['price'];
        $post['renew_op_count'] = $post['op_count'];

        $post['total_amount'] = $post['renew_price'] * $post['renew_num'];
        $post['total_num'] = $post['renew_num'];
        $post['order_amount'] = $post['total_amount'];

        $info = $model->create($post);

        return $info->toArray();
    }

    public static function payPage($get)
    {
        $where = [
            ['del', '=', 0],
            ['id', '=', $get['id']],
            ['shop_id', '=', $get['shop_id']],
        ];

        $info = OrderRenew::where($where)->find();
        if (!$info) {
            static::$error = '数据不存在';
            return false;
        }

        return $info->toArray();
    }

    private static function aliPay($info, $time_expire)
    {
        // 支付宝PC端支付
        $domain = request()->domain();

        $return_url = (string) url('shop/order.OrderRenew/lists', [], false, true);
        $notify_url = (string) url('shop/order.Pay/aliNotify', [], false, true);

        $ali_data = [
            'out_trade_no'      => $info['order_sn'],
            'total_amount'      => $info['order_amount'],
            'subject'           => '订单:' . $info['order_sn'],
            // 'return_url'        => $domain . '/shop/order.OrderRenew/lists',
            'return_url'        => $return_url,
            'time_expire'   => date('Y-m-d H:i:s', $time_expire),
        ];

        $aliPayConf = YansongdaAliPayServer::config();
        $aliPayConf['notify_url'] = $notify_url;

        $aliPay = Pay::alipay($aliPayConf);

        // $ali_data['notify_url'] = $domain . '/shop/order.Pay/aliNotify';
        $ali_data['notify_url'] = $notify_url;
        return $aliPay->web($ali_data)->getContent();
    }

    public static function payWay($post)
    {
        try {
            validate(OrderRenewValidate::class)->scene('pay_way')->check($post);
        } catch (\Exception $e) {
            static::$error = $e->getMessage();
            return false;
        }

        $where = [
            ['del', '=', 0],
            ['id', '=', $post['id']],
            ['shop_id', '=', $post['shop_id']],
        ];

        $info = OrderRenew::where($where)->find();
        if (!$info) {
            static::$error = '数据不存在';
            return false;
        }

        if ($info['order_status'] > 0) {
            static::$error = '订单不处于可支付状态下';
            return false;
        }

        $time_expire = time() + 3600 * 2;

        $info->pay_way = $post['pay_way'];
        $info->time_expire = $time_expire - 600;
        $info->save();

        if ($post['pay_way'] == 2) {
            return self::aliPay($info, $time_expire);
        }

        self::$error = '暂不支持该支付方式';
        return false;
    }

    private static function changeHkCount($info, $time)
    {
        // 添加用户套餐时间或者数量
        // 操作数量
        $op_count = $info['renew_op_count'] * $info['total_num'];
        $shop = Shop::find($info['shop_id']);
        // 包月
        if ($info['renew_type_id'] == 0) {
            $old_expire_time = $shop['expire_time'];
            if ($old_expire_time < $time) {
                $old_expire_time = $time;
            }

            $di = \DateInterval::createFromDateString(strval($op_count) . ' months');
            $dt = date_create_from_format('Y-m-d H:i:s', date('Y-m-d H:i:s', $old_expire_time))->add($di);
            $dt_str = $dt->format('Y-m-d 00:00:00');
            $shop->expire_time = strtotime($dt_str);
        } else {
            // 按量付费
            // 添加数量记录
            $old_hksy_count = $shop->hksy_count;
            $hk = new ShopHkLog();
            $hk->shop_id = $shop['id'];
            $hk->source_id = $info->id;
            $hk->change_count = $op_count;
            $hk->left_count = $op_count + $old_hksy_count;
            $hk->remark = '[' . $info->renew_name . '],订单号:' . $info->order_sn;
            $hk->save();

            $shop->hksy_count += $op_count;
        }

        $shop->save();

        return true;
    }

    private static function aliPaySucc($order_sn, $result)
    {
        $time = time();
        Db::startTrans();

        try {
            $where = [
                ['del', '=', 0],
                ['order_sn', '=', $order_sn],
            ];

            $info = OrderRenew::where($where)->find();
            if (empty($info)) {
                static::$error = '数据不存在';
                return false;
            }

            $info->order_status = 3;
            $info->pay_status = 1;
            $info->pay_time = $time;
            $info->notify_content = $result->toJson();
            $info->buyer_id = $result->buyer_open_id;
            $info->trade_no = $result->trade_no;
            $info->save();

            self::changeHkCount($info, $time);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('aliPaySucc 支付宝回调错误:' . $e->getMessage());
            static::$error = $e->getMessage();
            return false;
        }

        return true;
    }

    public static function aliNotify($post)
    {
        try {
            $aliPayConf = YansongdaAliPayServer::config();
            $aliPay = Pay::alipay($aliPayConf);
            $result = $aliPay->verify($post);
        } catch (\Exception $e) {
            static::$error = $e->getMessage();
            return false;
        }

        // 支付成功
        if ($result->trade_status === 'TRADE_SUCCESS') {
            self::aliPaySucc($result->out_trade_no, $result);
        }

        return true;
    }
}