<?php

namespace app\admin\controller;

use app\model\QaCitys;
use app\model\QaQuestions;
use app\model\Qas;
use support\Log;
use support\Request;
use think\facade\Db;

class QaController extends base
{
    public function getQaList(Request $request)
    {
        $city_id = $request->get('city_id');
        $keyword = $request->get('keyword');
        $limit = $request->get('limit', 10);

        $listQuery = Qas::query();

        if (!empty($city_id)) {
            $listQuery->where(['status' => 1, 'city_id' => $city_id]);
        }

        if (!empty($keyword)) {
            $qaIds = QaQuestions::whereRaw("title LIKE ? OR content LIKE ?", ['%'.$keyword.'%', '%'.$keyword.'%'])
                ->column('qa_id');
            $listQuery->when(!empty($qaIds), function ($query) use ($qaIds) {
                $query->whereIn('id', $qaIds);
            });
        }

        $list = $listQuery->order('id', 'desc')
            ->with(['qaQuestions' => function ($query) use ($keyword) {
                $query->whereRaw("title LIKE ? OR content LIKE ?", ['%'.$keyword.'%', '%'.$keyword.'%']);
                $query->order('sort', 'desc');
            }])
            ->paginate($limit);

        $list = json_decode(json_encode($list), true);
        if (isset($list['data']) && is_array($list['data'])) {
            foreach ($list['data'] as &$item) {
                if (isset($item['img_zip']) && !empty($item['img_zip'])) {
                    $item['img_zip'] = json_decode($item['img_zip'], true);
                }
                if (isset($item['trip_zip']) && !empty($item['trip_zip'])) {
                    $item['trip_zip'] = json_decode($item['trip_zip'], true);
                }
            }
        }

        return $this->success($list);
    }

    /**
     * cms list
     * @param Request $request
     * @return \support\Response
     * @throws \think\db\exception\DbException
     */
    public function getQa(Request $request)
    {
        $title = $request->get('title');
        $status = $request->get('status');

        $list = Qas::with(['qaCitys','qaQuestions'=>function ($query) {
            $query->order('sort desc');
        }])->order('create_time desc');

        if (!empty($title)){
            $list = $list->where('title','like','%'.$title.'%');
        }
        if (!is_null($status)){
            $list = $list->where('status',$status);
        }
        $list = $list->paginate($request->get('limit',10))->toArray();

        foreach ($list['data'] as &$item) {
            if (isset($item['img_zip']) && !empty($item['img_zip'])) {
                $item['img_zip'] = json_decode($item['img_zip'], true);
            }
            if (isset($item['trip_zip']) && !empty($item['trip_zip'])) {
                $item['trip_zip'] = json_decode($item['trip_zip'], true);
            }
        }

        return $this->success($list);
    }

    public function getQaDetail(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) return $this->error(2001, 'id data cannot be empty!');

        $data = Qas::with(['qaCitys','qaQuestions'=>function ($query) {
            $query->order('sort asc');
        }])->where('status',1)->find();

        return $this->success($data);
    }

    public function addQa(Request $request)
    {
        $post = $request->post();
        if (empty($post['city_id'])) return $this->error(2001, 'city_id data cannot be empty!');
        if (empty($post['title'])) return $this->error(2001, 'title data cannot be empty!');

        if ($post['trip_zip'] && is_array($post['trip_zip'])) {
            $post['trip_zip'] = json_encode($post['trip_zip']);
        }
        if ($post['img_zip'] && is_array($post['img_zip'])) {
            $post['img_zip'] = json_encode($post['img_zip']);
        }

        $qaQuestion = $post['qaQuestions'] ?? null;
        unset($post['qaQuestions']);
        if (isset($post['update_time'])) {
            unset($post['update_time']);
        }
        if (isset($post['id'])) {
            unset($post['id']);
        }
        $post['create_time'] = time();

        try {
            Db::transaction(function () use ($post,$qaQuestion){
                $data = Qas::create($post);
                if (!empty($qaQuestion)){
                    foreach ($qaQuestion as $k => $v){
                        $qaQuestion = new QaQuestions();
                        $qaQuestion->qa_id = $data->id;
                        $qaQuestion->title = $v['title'];
                        $qaQuestion->content = urldecode($v['content']);
                        $qaQuestion->sort = $v['sort'];
                        $qaQuestion->save();
                    }
                    $data->qaQuestions = $qaQuestion;
                }
            });
        } catch (\Exception $e) {
            return $this->error(2002, $e->getMessage());
        }
        return $this->success(null);
    }

    public function editQa(Request $request)
    {
        $post = $request->post();
        if (empty($post['id'])) return $this->error(2001, 'id data cannot be empty!');
        $qaQuestion = $post['qaQuestions'] ?? null;
        unset($post['create_time']);
        unset($post['update_time']);
        unset($post['qaQuestions']);

        if (isset($post['trip_zip']) && $post['trip_zip']) {
            $post['trip_zip'] = json_encode($post['trip_zip']);
        }
        if (isset($post['img_zip']) && $post['img_zip']) {
            $post['img_zip'] = json_encode($post['img_zip']);
        }

        try {
            Db::transaction(function () use ($post,$qaQuestion){
                $data = Qas::update($post);
                if (!empty($qaQuestion)){
                    QaQuestions::where('qa_id',$post['id'])->delete();
                    foreach ($qaQuestion as $k => $v){
                        $qaQuestion = new QaQuestions();
                        $qaQuestion->qa_id = $data->id;
                        $qaQuestion->title = $v['title'];
                        $qaQuestion->content = urldecode($v['content']);
                        $qaQuestion->sort = $v['sort'];
                        $qaQuestion->save();
                    }
                    $data->qa_question = $qaQuestion;
                }
            });
        } catch (\Exception $e) {
            return $this->error(2002, $e->getMessage());
        }
        return $this->success(null);
    }

    public function delQa(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) return $this->error(2001, 'id data cannot be empty!');
        try {
            Db::transaction(function () use ($id){
                Qas::destroy($id);
                QaQuestions::where('qa_id',$id)->delete();
            });
        } catch (\Exception $e) {
            return $this->error(2002, $e->getMessage());
        }
        return $this->success(null);
    }

    public function getQaCityList()
    {
        $list = QaCitys::order('sort desc')->select();
        return $this->success($list);
    }
}