<?php

namespace app\admin\controller\order;

use app\admin\validate\coupon\CouponValidate;
use app\admin\validate\device\DeviceValidate;
use app\admin\validate\order\OrderValidate;
use app\controller\Curd;
use app\model\Coupon;
use app\model\Device;
use app\model\Order;
use app\model\OrderReturn;
use app\model\OrderSheet;
use app\model\SysSerial;
use support\exception\BusinessException;
use support\Request;
use support\Response;
use Tinywan\Jwt\JwtToken;
use Webman\Event\Event;

class ReturnController extends Curd
{
    public function __construct()
    {
        $this->model = new OrderReturn();
        $this->validate = true;
        $this->validateClass = new OrderValidate();
    }

    /**
     * @Desc 列表
     * @Author Gorden
     * @Date 2024/3/28 15:01
     *
     * @param Request $request
     * @return Response
     * @throws \support\exception\BusinessException
     */
    public function select(Request $request): Response
    {
        [$where, $format, $limit, $field, $order] = $this->selectInput($request);
        $where['order_category'] = 'RETURN';
        $order = $request->get('order', 'desc');
        $field = $field ?? 'order_addtimes';
        $query = $this->doSelect($where, $field, $order);
        return $this->doFormat($query, $format, $limit);
    }

    /**
     * @Desc 订单商品详情
     * @Author Gorden
     * @Date 2024/3/29 8:50
     *
     * @param Request $request
     * @return Response
     */
    public function sheet(Request $request)
    {
        $orderId = $request->get('order_id');
        $orderSheet = OrderSheet::with([
            'member' => function ($query) {
                $query->select('member_id', 'member_mobile');
            },
            'goods' => function ($query) {
                $query->select('goods_id', 'goods_name', 'goods_cover', 'goods_market_price', 'goods_sales_price');
            },
        ])->where('join_sheet_order_id', $orderId)
            ->get()
            ->toArray();
        foreach ($orderSheet as &$item) {
            $item['goods']['goods_cover'] = getenv('STORAGE_DOMAIN') . $item['goods']['goods_cover'];
        }

        $order = Order::where('order_id', $orderId)->first();
        $data = [
            'order' => $order,
            'sheet' => $orderSheet
        ];

        return json_success('', $data);
    }

    protected function updateInput(Request $request): array
    {
        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($request->post());
        $model = $this->model->find($id);
        if (!$model) {
            throw new BusinessException('记录不存在', 2);
        }
        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * @Desc 退货退款状态变更通知
     * @Author Gorden
     * @Date 2024/7/16 14:22
     *
     * @param Request $request
     * @return Response
     */
    public function updateStatus(Request $request)
    {
        try {
            [$id, $data] = $this->updateInput($request);

//            if($data['order_return_status'] == 'DOING'){
                $data['order_return_accept_datetime'] = date('Y-m-d H:i:s');
                $data['join_order_return_user_id'] = JwtToken::getCurrentId();
//            }

            $this->doUpdate($id, $data);

            // 退货、退款状态变更通知
            $data['orders_return_id'] = $id;
            Event::dispatch('client_message.return_status',$data);

            return json_success('success');
        } catch (BusinessException $e) {
            return json_fail($e->getMessage());
        } catch (\Exception $e) {
            dump($e->getMessage());
            return json_fail('数据更新失败');
        }

    }
}