<?php
/**
 * 服务控制器
 */

namespace app\api\controller;

use app\api\model\Server\ServerCategory;
use app\api\model\Server\ServerOrder;
use app\api\service\Server\ServerPayment;
use app\common\enum\ServerEnum;
use app\common\service\server\Order as ServerServiceOrder;
use cores\exception\BaseException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class Server extends Controller
{
    /**
     * @notes:分类列表
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function categoryList(): Json
    {
        $model = new ServerCategory();
        $list = $model->list();
        if (!empty($list)) {
            foreach ($list as $key => $value) {
                unset($list[$key]['image']);
            }
        }
        return $this->renderSuccess(compact('list'));
    }

    /**
     * @notes:服务列表页
     * @throws DbException
     * @author: wanghousheng
     */
    public function list(): Json
    {
        $server_name = $this->request->post('server_name');
        $category_id = intval($this->request->post('category_id'));
        $order_field = $this->request->post('order_field');
        $order_sort = $this->request->post('order_sort', 'desc');
        $where = [];
        if ($server_name) {
            $where[] = ['server.server_name', 'like', "%$server_name%"];
        }
        if ($category_id) {
            $where[] = ['server.category_id', '=', $category_id];
        }
        $where[] = ['server.status', '=', 1];
        $model = new \app\api\model\Server();
        $list = $model->getList($where, $order_field, $order_sort);
        $data['list'] = $list->items();
        $data['total'] = $list->total();
        if (!$list->isEmpty()) {
            foreach ($data['list'] as $key => $value) {
                unset($data['list'][$key]['image']);
                unset($data['list'][$key]['category']);
            }
        }
        return $this->renderSuccess($data);
    }

    /**
     * @notes:订单状态
     * @return Json
     * @author: wanghousheng
     */
    public function orderStatus(): Json
    {
        $list = array_values(ServerEnum::data());
        return $this->renderSuccess(compact('list'));
    }

    /**
     * @notes:用户订单列表
     * @throws DbException
     * @throws BaseException
     * @author: wanghousheng
     */
    public function orderList(): Json
    {
        $order_no = $this->request->post('order_no');
        $order_status = intval($this->request->post('order_status'));
        $where = [];
        if (!empty($order_no)) {
            $where['order_no'] = $order_no;
        }
        if ($order_status) {
            $where['order_status'] = $order_status;
        }
        $model = new ServerOrder($where);
        $list = $model->orderList($where);
        $data['list'] = $list->items();
        $data['total'] = $list->total();
        if (!$list->isEmpty()) {
            foreach ($data['list'] as $key => $value) {
                $data['list'][$key]['is_cancel'] = ServerServiceOrder::checkCancel($value);
                $data['list'][$key]['is_dispatch'] = ServerServiceOrder::checkDispatch($value);
                $data['list'][$key]['is_pay'] = ServerServiceOrder::checkPay($value);
                unset($data['list'][$key]['image']);
                if (!empty($data['list'][$key]['dealer'])) {
                    unset($data['list'][$key]['dealer']);
                }
                if (!empty($data['list'][$key]['user'])) {
                    unset($data['list'][$key]['user']);
                }
            }
        }
        return $this->renderSuccess($data);
    }

    /**
     * @notes:确认订单
     * @return Json
     * @throws BaseException
     * @throws DbException
     * @author: wanghousheng
     */
    public function checkOrder(): Json
    {
        $serverId = intval($this->request->post('server_id'));
        $couponId = intval($this->request->post('coupon_id'));
        if (!$serverId) {
            return $this->renderError('非法请求');
        }
        $orderService = new ServerServiceOrder();
        $data = $orderService->onCheck($serverId, $couponId);
        return $this->renderSuccess($data);
    }

    /**
     * @notes:生成订单
     * @return Json
     * @throws BaseException
     * @throws DbException
     * @author: wanghousheng
     */
    public function createOrder(): Json
    {
        $serverId = intval($this->request->post('server_id'));
        $couponId = intval($this->request->post('coupon_id'));
        $server_time = $this->request->post('server_time');
        $username = $this->request->post('username');
        if (!$username) {
            return $this->renderError('联系人不能为空');
        }
        $mobile = $this->request->post('mobile');
        if (!$mobile || !preg_match("/1[3457896]\d{9}$/", $mobile)) {
            return $this->renderError('手机号不正确');
        }
        if (!$server_time) {
            return $this->renderError('服务时间不能为空');
        }
        $server_address = $this->request->post('server_address');
        if (!$server_address) {
            return $this->renderError('服务地址不能为空');
        }
        $remake = (string)$this->request->post('remake');
        if (!$serverId) {
            return $this->renderError('非法请求');
        }
        $orderService = new ServerServiceOrder();
        $data = [
            'server_id' => $serverId,
            'server_time' => $server_time,
            'server_address' => $server_address,
            'buyer_remark' => $remake,
        ];
        $result = $orderService->createOrder($data, $couponId);
        if ($result) {
            return $this->renderSuccess($result);
        }
        return $this->renderError('创建订单失败');
    }

    /**
     * @notes:取消订单
     * @return Json
     * @throws BaseException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function cancelOrder(): Json
    {
        $orderId = intval($this->request->post('order_id'));
        if (!$orderId) {
            return $this->renderError('非法请求');
        }
        if (ServerServiceOrder::userCancelOrder($orderId)) {
            return $this->renderSuccess('取消成功');
        }
        return $this->renderError('操作失败');
    }

    /**
     * @notes:派单人员列表
     * @return Json
     * @throws BaseException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function getEngineer(): Json
    {
        $list = ServerServiceOrder::getEngineer();
        return $this->renderSuccess(compact('list'));
    }

    /**
     * @notes:派单
     * @return Json
     * @throws BaseException
     * @author: wanghousheng
     */
    public function dispatchOrders(): Json
    {
        $orderId = intval($this->request->post('order_id'));
        if (!$orderId) {
            return $this->renderError('非法请求');
        }
        $dealerId = intval($this->request->post('dealer_id'));
        if (!$dealerId) {
            return $this->renderError('分配人员不能为空');
        }
        if (ServerServiceOrder::userDispatchOrders($orderId, $dealerId)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError('操作失败');
    }

    /**
     * @notes:获取支付订单的信息
     * @return Json
     * @throws BaseException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function orderInfo(): Json
    {
        $orderId = intval($this->request->post('order_id'));
        if (!$orderId) {
            return $this->renderError('非法请求');
        }
        $client = $this->request->post('client');
        if (!$client) {
            return $this->renderError('客户端不能为空');
        }
        $paymentService = new ServerPayment();
        $data = $paymentService->setOrderId($orderId)->setClient($client)->orderInfo();
        return $this->renderSuccess($data);
    }

    /**
     * @notes:确认订单支付事件
     * @throws BaseException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function orderPay(): Json
    {
        $orderId = intval($this->request->post('order_id'));
        if (!$orderId) {
            return $this->renderError('非法请求');
        }
        $method = $this->request->post('method');
        if (!$method) {
            return $this->renderError('支付方式不能为空');
        }
        $client = $this->request->post('client');
        if (!$client) {
            return $this->renderError('客户端不能为空');
        }
        $paymentService = new ServerPayment();
        $data = $paymentService->setOrderId($orderId)
            ->setMethod($method)
            ->setClient($client)
            ->orderPay();
        return $this->renderSuccess($data, $paymentService->getMessage() ?: '下单成功');
    }

    /**
     * @notes:交易查询
     * @return Json
     * @throws BaseException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author: wanghousheng
     */
    public function tradeQuery(): Json
    {
        $method = $this->request->post('method');
        if (!$method) {
            return $this->renderError('支付方式不能为空');
        }
        $order_no = $this->request->post('order_no');
        if (!$order_no) {
            return $this->renderError('订单号不能为空');
        }
        $client = $this->request->post('client');
        if (!$client) {
            return $this->renderError('客户端不能为空');
        }
        $paymentService = new ServerPayment;
        $result = $paymentService->setMethod($method)->setClient($client)->tradeQuery($order_no);
        $message = $result ? '恭喜您,订单已付款成功' : ($paymentService->getError() ?: '很抱歉,订单未支付,请重新发起');
        return $this->renderSuccess(['isPay' => $result], $message);
    }
}