<?php

namespace app\controller\manager;

use app\model\Feedback as FeedbackModel;
use app\model\FeedbackType;
use app\model\Log;
use Exception;
use think\response\Json;
use think\response\View;

/**
 * 意见反馈
 *
 * Class Feedback
 * @package app\controller\manager
 */
class Feedback extends Base
{
    /**
     * 删除
     *
     * @return Json
     */
    public function del(): Json
    {
        if ($this->request->isPost()) {
            $ids = input('post.ids/a', []);
            if (empty($ids)) {
                $ids[] = input('post.id/d');
            }
            FeedbackModel::deleteByIds($ids);
            Log::write(get_class().'Del', 'del', '涉及到的ID为:'.implode(',', $ids));
            return $this->json();
        }
        return $this->json(4001, '非法请求!');
    }

    /**
     * 列表
     *
     * @return View|Json
     * @throws Exception
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $page         = input('page/d', 1);
            $limit        = input('size/d', 20);
            $searchParams = input('searchParams');
            $search       = [];
            if ($searchParams) {
                foreach ($searchParams as $key => $param) {
                    if ($param) {
                        $search[] = [$key, 'like', '%'.$param.'%'];
                    }
                }
            }

            $items = FeedbackModel::findList($search, [], $page, $limit, function ($q) {
                return $q->with(['type', 'account'])->order('created_at', 'desc');
            });

            $items['list'] = $items['list']->each(function ($item) {
                $item->feedback_type = $item->type->title ?? '';
                $item->nickname      = $item->account->nickname ?? '';
                $item->mobile      = $item->account->mobile ?? '';
            });

            return $this->json(0, '操作成功', $items);
        }

        $this->data['typeList'] = FeedbackType::select();

        return $this->view();
    }
}