<?php

namespace App\Http\Controllers\Admin;

use App\Exports\FeedbackExport;
use App\Exports\ReportLogExport;
use App\Http\Controllers\Controller;
use App\Http\Response\ResponseJson;
use App\Models\AppVersion;
use App\Models\Feedback;
use App\Models\PublicConfig;
use App\Models\ReportLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

class ConfigController extends Controller
{
    use ResponseJson;

    /**
     * 设置隐私协议
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function setPrivacy(Request $request)
    {
        try {
            $name = $request->get('name', PublicConfig::APP_PRIVACY);
            $content = $request->input('content') ?? [];

            $language = $request->get('language');
            $remark = $request->input('remark');
            $sub_name = 'cn_privacy';
            if (strlen($language) > 0) {
                $name_arr = PublicConfig::NAME_ARR[$name] ?? [];
                $sub_name = $name_arr[$language] ?? '';
            }

            $data['name'] = $name;
            $data['sub_name'] = $sub_name;
            $data['content'] = $content;
            $data['remark'] = $remark ?? 'app多语言隐私协议';
            $privacy = PublicConfig::where('name', $name)->where('sub_name', $sub_name)->first();
            if ($privacy) {
                $privacy->content = $data['content'];
                $res = $privacy->save();
            } else {
                $res = PublicConfig::create($data);
            }
            return $this->success('ok', $res);
        } catch (\Exception $e) {
            Log::error('setPrivacy:' . $e->getMessage());
            return $this->failure('保存失败');
        }
    }

    public function setPublicConfig(Request $request)
    {
        try {
            $data = $request->only(['name', 'sub_name', 'content', 'remark']);
            $data['content'] = json_encode($data['content']);
            $policy = PublicConfig::where('name', $data['name'])->first();
            if ($policy) {
                PublicConfig::where('id', $policy->id)->update($data);
            } else {
                PublicConfig::create($data);
            }
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('setPublicConfig:' . $e->getMessage());
            return $this->failure('保存失败');
        }
    }
    /**
     * 获取隐私协议
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
     */
    public function getPrivacy(Request $request)
    {
        try {
            $name = $request->get('name', PublicConfig::APP_PRIVACY);
            $privacy = PublicConfig::where('name', $name)->get();
            foreach ($privacy as $key => $value) {
                $content = json_decode($value->content, true);
                if ($content != null) {
                    $value->content = $content;
                }
            }
            return $this->success('ok', $privacy);
        } catch (\Exception $e) {
            Log::error('getPrivacy:' . $e->getMessage());
            return $this->failure('获取失败');
        }
    }

    /**
     * 添加配置
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|void
     */
    public function setAppVersion(Request $request)
    {
        try {
            $version = $request->input('version');
            $code = $request->input('code');
            $url = $request->input('url');
            if (empty($url))
                return $this->failure('请上传apk');
            $desc = $request->input('desc');
            $update_flag = $request->input('update_flag');
            $platform = $request->input('platform');
            $is_prod = $request->input('is_prod');

            $map = [];
            $map['version'] = $version;
            $map['code'] = $code;
            $map['url'] = $url;
            $map['desc'] = $desc;
            $map['update_flag'] = $update_flag;
            $map['platform'] = $platform;
            $map['is_prod'] = $is_prod;
            AppVersion::create($map);
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('setAppVersion:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function updateAppVersion(Request $request)
    {
        try {
            $id = $request->get('id');
            $version_info = AppVersion::where('id', $id)->first();
            if (empty($version_info)) {
                return $this->failure('信息不存在');
            }
            $version = $request->input('version');
            $code = $request->input('code');
            $url = $request->input('url');
            if (empty($url))
                return $this->failure('请上传apk');
            $desc = $request->input('desc');
            $update_flag = $request->input('update_flag');
            $platform = $request->input('platform');
            $is_prod = $request->input('is_prod');
            $force_update = $request->input('force_update');

            $version_info->version = $version;
            $version_info->code = $code;
            $version_info->url = $url;
            $version_info->desc = $desc;
            $version_info->update_flag = $update_flag;
            $version_info->platform = $platform;
            $version_info->is_prod = $is_prod;
            $version_info->force_update = $force_update;
            $version_info->save();
            return $this->success('ok');
        } catch (\Exception $e) {
            Log::error('updateAppVersion:' . $e->getMessage());
            return $this->failure($e->getMessage());
        }
    }

    public function deleteAppVersion(Request $request)
    {
        $id = $request->get('id');
        AppVersion::where('id', $id)->delete();
        return $this->success('删除成功');
    }

    public function getAppVersionList(Request $request)
    {
        $keyword = $request->get('keyword');
        $platform = $request->get('platform');
        $is_prod = $request->get('is_prod');
        $data = AppVersion::query()->when($keyword, function ($query) use ($keyword) {
            $query->where(function ($query) use ($keyword) {
                $query->where('version', 'like', "%{$keyword}%");
            });
        })->when(strlen($platform) > 0, function ($query) use ($platform) {
            $query->where("platform", $platform);
        })
            ->when(strlen($is_prod) > 0, function ($query) use ($is_prod) {
                $query->where("is_prod", $is_prod);
            })
            ->orderByDesc('id')->paginate();
        foreach ($data as $item) {
            $item->feedback = '';
            if (empty($item->feedback_ids)) {
                continue;
            }
            $ids = explode(',', $item->feedback_ids);
            // 获取 feedback 对象，并且在 desc 前面拼接 id
            $feedbacks = Feedback::whereIn('id', $ids)->get(['id', 'desc']);

            $feedbackWithIds = $feedbacks->map(function ($feedback) {
                return $feedback->id . '.' . $feedback->desc;
            });
            // 将拼接后的值赋给 item 的 feedback 属性
            $item->feedback = $feedbackWithIds;
        }
        return $this->success('ok', $data);
    }

    public function getFeedback(Request $request)
    {
        $keyword = $request->get('keyword');
        $is_export = $request->get('is_export');
        $status = $request->get('status');
        $source = $request->get('source');
        $type = $request->get('type');
        $is_bug = $request->get('is_bug');
        $no_page = $request->get('no_page');
        $query = Feedback::query()->with('user');

        $query->when(strlen($status) > 0, function ($sql) use ($status) {
            $sql->where('status', $status);
        });
        $query->when(strlen($is_bug) > 0, function ($sql) use ($is_bug) {
            $sql->where('is_bug', $is_bug);
        });
        $query->when(!empty($type), function ($sql) use ($type) {
            $sql->where('type', $type);
        });
        $query->when(strlen($source) > 0, function ($sql) use ($source) {
            $sql->where('source', $source);
        });
        $query->when($keyword, function ($sql) use ($keyword) {
            $sql->where('desc', 'like', '%' . $keyword . '%')->orWhere('id', 'like', "%" . $keyword . "%");
        });

        $query->orderByDesc('id');

        if ($is_export) {
            $list = $query->get();
            return Excel::download(new FeedbackExport($list), 'feedback.xlsx');
        }
        if ($no_page) {
            $list = $query->get();
        } else {
            $list = $query->paginate();
        }

        foreach ($list as $item) {
            $item->images = json_decode($item->images);
        }
        return $this->success('ok', $list);
    }

    public function getReport(Request $request)
    {
        $keyword = $request->get('keyword');
        $is_export = $request->get('is_export');

        $query = ReportLog::query();

        $query->when($keyword, function ($sql) use ($keyword) {
            $sql->where('remark', 'like', '%' . $keyword . '%');
        });

        $query->orderByDesc('id');
        if ($is_export) {
            $list = $query->get();
        } else {
            $list = $query->paginate();
        }

        foreach ($list as $item) {
            $item->by_user_name = User::where('id', $item->by_user_id)->value('name');
            $item->user_name = User::where('id', $item->user_id)->value('name');
            $item->img = json_decode($item->img);
        }

        if ($is_export) {
            return Excel::download(new ReportLogExport($list), 'report.xlsx');
        }
        return $this->success('ok', $list);
    }
}
