<?php

namespace app\api\controller;

use app\common\model\Order;
use think\facade\Db;
use think\facade\Log;
use app\common\model\Goods;


class Trade extends Base
{
    //生成订单
    public function setOrder()
    {
        $uid = $this->request->user['id'];
        $web_time = $this->request->post('web_time', '', 'trim');
        // dd($web_time,date('Y-m-d H:i:s'));
        if ($web_time) {
            $web_time = strtotime($web_time);
            $diff_time = time() - $web_time;
        } else {
            $web_time = 0;
            $diff_time = 0;
        }
        // dd($web_time,$diff_time);
        //运营时间判断
        $open_date = $this->config['system_basic']['open_time'] ?? '';
        $close_date = $this->config['system_basic']['close_time'] ?? '';
        $start_time = strtotime($open_date);
        $close_time = strtotime($close_date);
        if ($start_time) {
            $start_time -= $diff_time;
            if ($start_time > $web_time)
                $this->result(false, '开盘时间为：', ['var' => $open_date . ' - ' . $close_date, 'start_date' => date('Y-m-d H:i:s', $start_time), 'web_date' => date('Y-m-d H:i:s', $web_time)]);
        }
        if ($close_time) {
            $close_time -= $diff_time;
            if ($close_time < $web_time)
                $this->result(false, '开盘时间为：', ['var' => $open_date . ' - ' . $close_date, 'close_date' => date('Y-m-d H:i:s', $close_time), 'web_date' => date('Y-m-d H:i:s', $web_time)]);
        }
        $order_info = [];
        $extra_data['back_comm_multiple'] = $this->config['system_basic']['back_comm_multiple'] ?? 0; //返佣倍数
        try {
            $mod = new Order();
            $count = $mod->where(['uid' => $uid, 'status' => 1])->count();
            if ($count)
                throw new \Exception('您还有未完成的订单');
            $order_info = $mod->createNewOrder($uid, $extra_data); //生成订单
            if ($order_info)
                $order_info['create_time'] = date('Y-m-d H:i:s', $order_info['create_time'] - $diff_time);
        } catch (\Exception $e) {
            if ($e->getCode()) {
                Log::error('生成订单失败-' . $e->getMessage() . ':' . $e->getLine());
                $this->result(false, '系统繁忙，请重试');
            } else {
                $msg = $e->getMessage();
                $arr = explode('-', $msg);
                if (count($arr) == 3) {
                    $msg = $arr[0];
                    $this->result(false, $msg, ['status' => $arr[1], 'num' => $arr[2]]);
                } else
                    $this->result(false, $msg);
            }
        }
        if ($order_info) {
            $order_info['goods_img'] = $this->request->domain() . $order_info['goods_img'];
            $this->result(true, '操作成功', $order_info);
        } else
            $this->result(false, '操作失败');
    }

    //提交订单-分佣
    public function commitOrder()
    {
        $order_id = $this->request->post('order_id', 0, 'intval');
        $uid = $this->request->user['id'];
        if (!$order_id)
            $this->result(false, '参数有误');
        $level_arr = [
            $this->config['system_basic']['comm_reward_0'] ?? '0.01',
            $this->config['system_basic']['comm_reward_1'] ?? '0.01',
            $this->config['system_basic']['comm_reward_2'] ?? '0.01',
            $this->config['system_basic']['comm_reward_3'] ?? '0.01',
            $this->config['system_basic']['comm_reward_4'] ?? '0.01',
        ];
        try {
            $mod = new Order();
            $mod->doOrder($order_id, $uid, $level_arr);
        } catch (\Exception $e) {
            if ($e->getCode()) {
                Log::error('订单分佣失败-' . $e->getMessage() . ':' . $e->getLine());
                $this->result(false, '系统繁忙，请重试');
            } else {
                $this->result(false, $e->getMessage());
            }
        }
        $this->result(true, '操作成功');
    }

    //订单列表
    public function getOrderList()
    {
        $uid = $this->request->user['id'];
        $web_time = $this->request->post('web_time', '', 'trim');
        if ($web_time)
            $diff_time = time() - strtotime($web_time);
        else
            $diff_time = 0;
        $page = $this->request->post('page', 1, 'intval');
        $status = $this->request->post('status', 0, 'intval');
        $domain = $this->request->domain();
        $where['o.uid'] = $uid;
        if ($status)
            $where['o.status'] = $status;
        $list = Db::name('Order')->alias('o')->leftJoin('mod_goods g', 'o.goods_id=g.id')->where($where)
            ->field('o.*,g.name as goods_name,g.img as goods_img')->order('o.id desc')->paginate(['list_rows' => 10, 'page' => $page])->toArray();
        foreach ($list['data'] as &$item) {
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time'] - $diff_time);
            if ($item['end_time'])
                $item['end_time'] = date('Y-m-d H:i:s', $item['end_time'] - $diff_time);
            if ($item['goods_img'])
                $item['goods_img'] = $domain . $item['goods_img'];
            // Calculate order_rate from price and commission
            //$item['order_rate'] = $item['price'] > 0 ? round(($item['commission'] / $item['price']), 4) : 0;
            $item['order_rate'] = $item['price'] > 0 ? round(abs($item['commission'] / $item['price']), 4) : 0;
        }
        $this->result(true, '操作成功', $list['data'], ['total' => $list['total'], 'last_page' => $list['last_page']]);
    }

    //订单详情
    public function getOrderInfo()
    {
        $web_time = $this->request->post('web_time', '', 'trim');
        if ($web_time)
            $diff_time = time() - strtotime($web_time);
        else
            $diff_time = 0;
        $domain = $this->request->domain();
        $order_id = $this->request->post('order_id', 0, 'intval');
        if (!$order_id)
            $this->result(false, '参数有误');
        $order_info = Db::name('Order')->alias('o')->leftJoin('mod_goods g', 'o.goods_id=g.id')->where(['o.id' => $order_id])->field('o.*,g.name as goods_name,g.img as goods_img')->find();
        if (!$order_info)
            $this->result(false, '数据不存在');
        $order_info['create_time'] = date('Y-m-d H:i:s', $order_info['create_time'] - $diff_time);
        if ($order_info['end_time'])
            $order_info['end_time'] = date('Y-m-d H:i:s', $order_info['end_time'] - $diff_time);
        if ($order_info['goods_img'])
            $order_info['goods_img'] = $domain . $order_info['goods_img'];
        $this->result(true, '操作成功', $order_info);
    }

    //热门商品
    public function getHotPro()
    {

        $page = $this->request->get('page', 1);

        $domain = $this->request->domain();
        $orderModel = new Order;
        $ids = $orderModel::withJoin('goods', 'LEFT')->field('count(goods_id) as num,goods_id')->group('goods_id')->order('num desc')->page($page, 20)->select();
        
        // Process goods images and prefix with domain (consistent with getOrderList)
        // Convert to array and process goods images
        $ids = $ids->toArray();
        foreach ($ids as &$item) {
            if (isset($item['goods']) && isset($item['goods']['img']) && $item['goods']['img']) {
                $item['goods']['img'] = $domain . $item['goods']['img'];
            }
        }

        $this->result(true, '操作成功', ['data' => $ids, 'domain' => $domain]);
    }
    //商品jiage
    public function getProPri()
    {

        $page = $this->request->get('page', 1);

        $domain = $this->request->domain();
        $Model = new Goods;
        $ids = $Model->order('price asc')->page($page, 20)->select();

        $this->result(true, '操作成功', ['data' => $ids, 'domain' => $domain]);
    }
}
