<?php
declare (strict_types=1);

namespace app\store\controller;

use app\common\enum\RecoveryStatusEnum;
use app\common\library\helper;
use app\common\model\RecoveryOrder;
use app\store\model\server\RecoveryCategory;
use app\store\model\server\ServerRecovery;
use cores\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Json;

class Recovery extends Controller
{
    /**
     * @notes:分类列表
     * @return Json
     * @author: wanghousheng
     */
    public function categoryList(): Json
    {
        $name = $this->request->post('name');
        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', `%$name%`];
        }
        $model = new RecoveryCategory();
        try {
            $list = $model->getList($where);
        } catch (DataNotFoundException|ModelNotFoundException|DbException $e) {
            return $this->renderError($e->getMessage() ?: '接口异常');
        }
        return $this->renderSuccess(compact('list'));
    }

    /**
     * @notes:添加分类
     * @return Json
     * @author: wanghousheng
     */
    public function addCategory(): Json
    {
        $data = $this->postForm();
        if (!$data) {
            return $this->renderError('缺少必要参数');
        }
        $model = new RecoveryCategory();
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * @notes:编辑分类
     * @param int $categoryId
     * @return Json
     * @author: wanghousheng
     */
    public function editCategory(int $categoryId): Json
    {
        $data = $this->postForm();
        if (!$data) {
            return $this->renderError('缺少必要参数');
        }
        $model = RecoveryCategory::detail($categoryId);
        if ($model->edit($data)) {
            return $this->renderSuccess('编辑成功');
        }
        return $this->renderError($model->getError() ?: '编辑失败');
    }

    public function deleteCategory(int $categoryId): Json
    {
        $model = RecoveryCategory::detail($categoryId);
        if ($model->remove()) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError('删除失败');
    }

    /**
     * @notes:回收列表
     * @return Json
     * @author: wanghousheng
     */
    public function recoveryList(): Json
    {
        // 获取列表记录
        $model = new ServerRecovery();
        $recovery_name = $this->request->post('recovery_name');
        $category_id = intval($this->request->post('category_id'));
        $status = intval($this->request->post('status'));
        $where = [];
        if ($recovery_name) {
            $where[] = ['server_recovery.server_name', 'like', "%$recovery_name%"];
        }
        if ($category_id) {
            $where[] = ['server_recovery.category_id', '=', $category_id];
        }
        if ($status) {
            $where[] = ['server_recovery.status', '=', $status];
        }
        try {
            $list = $model->getList($where);
        } catch (DbException $e) {
            return $this->renderError($e->getMessage());
        }
        return $this->renderSuccess(compact('list'));
    }

    public function recoveryDetail(int $recoveryId): Json
    {
        // 获取商品详情
        $model = new ServerRecovery;
        $info = $model->getDetail($recoveryId);
        return $this->renderSuccess(compact('info'));
    }

    /**
     * @notes:添加回收
     * @return Json
     * @author: wanghousheng
     */
    public function addRecovery(): Json
    {
        $data = $this->postForm();
        if (!$data) {
            return $this->renderError('缺少必要参数');
        }
        $model = new ServerRecovery();
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * @notes:编辑回收
     * @param int $recoveryId
     * @return Json
     * @author: wanghousheng
     */
    public function editRecovery(int $recoveryId): Json
    {
        $data = $this->postForm();
        if (!$data) {
            return $this->renderError('缺少必要参数');
        }
        $model = ServerRecovery::detail($recoveryId);
        if ($model->edit($data)) {
            return $this->renderSuccess('编辑成功');
        }
        return $this->renderError($model->getError() ?: '编辑失败');
    }

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

    /**
     * @notes:删除回收
     * @param array $recoveryId
     * @return Json
     * @author: wanghousheng
     */
    public function deleteRecovery(array $recoveryId): Json
    {
        $model = new ServerRecovery;
        if ($model->remove($recoveryId)) {
            return $this->renderSuccess('删除成功');
        }
        return $this->renderError('删除失败');
    }

    /**
     * 修改回收状态(上下架)
     * @param array $recoveryIds id集
     * @param bool $state 为true表示上架
     * @return Json
     */
    public function recoveryStatus(array $recoveryIds, bool $state): Json
    {
        $model = new ServerRecovery;
        if (!$model->setStatus($recoveryIds, $state)) {
            return $this->renderError($model->getError() ?: '操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 回收订单列表
     */
    public function orderList(Request $request): Json
    {

        $server_name = $this->request->post('recovery_name');
        $order_no = $this->request->post('order_no');
        $order_status = intval($this->request->post('order_status'));
        $user_mobile = $this->request->post('user_mobile');
        $where = [];
        if (!empty($server_name)) {
            $where[] = ['a.recovery_name', 'like', "%$server_name%"];
        }
        if (!empty($order_no)) {
            $where[] = ['a.order_no', '=', $order_no];
        }
        if ($order_status) {
            $where[] = ['a.order_status', '=', $order_status];
        }
        if ($user_mobile) {
            $where[] = ['b.mobile', '=', $user_mobile];
        }
        $model = new RecoveryOrder();
        $list = $model->where($where)
            ->alias('a')
            ->join('user b', 'b.user_id = a.user_id')
            ->field('a.*,b.mobile as user_mobile,b.nick_name as user_nick_name')
            ->order('create_time', 'desc')
            ->paginate(15);
        $data['list'] = $list->items();
        $data['total'] = $list->total();
        return $this->renderSuccess($data);
    }

    /**
     * @notes:订单详情
     * @return Json
     * @author: wanghousheng
     */
    public function orderDetail(): Json
    {
        $orderId = intval($this->request->post('orderId'));
        $data = RecoveryOrder::detail(['order_id' => $orderId], ['images.file', 'shop', 'user']);
        return $this->renderSuccess(['detail' => $data]);
    }

    /**
     * @notes:删除订单
     * @return Json
     * @author: wanghousheng
     */
    public function orderDel(): Json
    {
        $orderId = intval($this->request->post('order_id'));
        if (!$orderId) {
            return $this->renderError('非法请求');
        }
        if ((new RecoveryOrder())->remove($orderId)) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError('操作失败');
    }

    /**
     * @notes:订单验收
     * @return Json
     * @author: wanghousheng
     */
    public function completeOrder(): Json
    {
        $data = $this->postForm();
        if (empty($data['order_id'])) {
            return $this->renderError('缺少必要参数');
        }
        if (empty($data['real_price']) || helper::number2($data['real_price']) <= 0) {
            return $this->renderError('回收价不能为空');
        }
        $order_id = intval($data['order_id']);
        $real_price = helper::number2($data['real_price']);
        if (!RecoveryOrder::detail(['order_id' => $order_id, 'order_status' => RecoveryStatusEnum::ACCEPTED])) {
            return $this->renderError('订单信息不存在');
        }
        $model = new RecoveryOrder();
        if ($model->where(['order_id' => $order_id])->save(['order_status' => RecoveryStatusEnum::ALREADY, 'real_price' => $real_price])) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError('操作失败');
    }
}