<?php

namespace App\Services\Appearance;

use App\Exceptions\AlertException;
use App\Models\Appearance\AppearanceModel;
use App\Models\Appearance\PartnerRankModel;
use App\Models\Fpdx\MediaModel;
use App\Models\PartnerModel;
use App\Models\SchoolModel;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;

class RankService
{


    /**
     * 学校第一名
     * @param $type
     * @param $date
     * @param $schools
     * @return array
     */
    public function getSchoolsFirstPartner($type, $date, array $schools)
    {
        $build = DB::table("fpdx_appearance_partner_ranks as r")
            ->join("fpdx_appearances as a", 'r.partner_id', '=', 'a.partner_id')
            ->where(['r.date' => $date, 'r.type' => $type, 'r.sex' => 1])
            ->where("a.state", 2)
            ->whereIn('r.school', $schools)
            ->orderBy("r.count", "desc")
            ->select(['r.partner_id', 'r.school', 'r.count']);
        $menSchools = DB::table(DB::raw("({$build->toSql()}) as tab"))->setBindings($build->getBindings())->groupBy('school')->get()->toArray();
        $menSchools = array_combine(array_column($menSchools, 'partner_id'), $menSchools);

        $menPartners = PartnerModel::whereIn('id', array_keys($menSchools))->get(['id', 'photo_src'])->toArray();
        $menPartners = array_combine(array_column($menPartners, 'id'), $menPartners);
        array_walk($menSchools, function (&$value) use ($menPartners) {
            $value = json_decode(json_encode($value), true);
            $value['partner'] = $menPartners[$value['partner_id']];
        });
        $men = array_combine(array_column($menSchools, 'school'), $menSchools);

        $build = DB::table("fpdx_appearance_partner_ranks as r")
            ->join("fpdx_appearances as a", 'r.partner_id', '=', 'a.partner_id')
            ->where(['r.date' => $date, 'r.type' => $type, 'r.sex' => 2])
            ->where("a.state", 2)
            ->whereIn('r.school', $schools)
            ->orderBy("r.count", "desc")
            ->select(['r.partner_id', 'r.school', 'r.count']);
        $womenSchools = DB::table(DB::raw("({$build->toSql()}) as tab"))->setBindings($build->getBindings())->groupBy('school')->get()->toArray();
        $womenSchools = array_combine(array_column($womenSchools, 'partner_id'), $womenSchools);
        $womenPartners = PartnerModel::whereIn('id', array_keys($womenSchools))->get(['id', 'photo_src'])->toArray();
        $womenPartners = array_combine(array_column($womenPartners, 'id'), $womenPartners);
        array_walk($womenSchools, function (&$value) use ($womenPartners) {
            $value = json_decode(json_encode($value), true);
            $value['partner'] = $womenPartners[$value['partner_id']];
        });
        $women = array_combine(array_column($womenSchools, 'school'), $womenSchools);
        $schoolsRank = array();
        array_map(function ($value) use (&$schoolsRank, $men, $women) {
            $tmp = array(
                'men' => isset($men[$value]) ? $men[$value] : "",
                'women' => isset($women[$value]) ? $women[$value] : "",
            );
            $schoolsRank[$value] = $tmp;
        }, $schools);

        return $schoolsRank;
    }


    /**
     * 学校第一名
     * @param $type
     * @param $date
     * @param $school
     * @return array
     */
    public function getPartners($type, $date, $school)
    {
        $men_partner_id = \DB::table("fpdx_appearance_partner_ranks as r")
            ->join("fpdx_appearances as a", 'r.partner_id', '=', 'a.partner_id')
            ->where([
                'r.date' => $date,
                'r.type' => $type,
                'r.school' => $school,
                'r.sex' => 1,
            ])->where("a.state", 2)
            ->orderBy("r.count", "desc")
            ->value('r.partner_id');
        $men = PartnerModel::where('id', $men_partner_id)->value('photo_src');

        $women_partner_id = \DB::table("fpdx_appearance_partner_ranks as r")
            ->join("fpdx_appearances as a", 'r.partner_id', '=', 'a.partner_id')
            ->where([
                'r.date' => $date,
                'r.type' => $type,
                'r.school' => $school,
                'r.sex' => 2,
            ])->where("a.state", 2)
            ->orderBy("r.count", "desc")
            ->value('r.partner_id');
        $women = PartnerModel::where('id', $women_partner_id)->value('photo_src');
        $partners = [
            'men' => $men ? "https://oss.pocketuniversity.cn" . $men : '',
            'women' => $women ? "https://oss.pocketuniversity.cn" . $women : '',
        ];

        return $partners;
    }


    /**
     * 获取学校
     */
    public function getSchoolFirstMedia($school)
    {
        $media_id = \DB::table('pocket.kdgx_activity_enrolls')->where('state', 1)->where(
            'school',
            $school
        )->orderBy('pick', 'desc')->value('media_id');

        return MediaModel::select('public_name', 'head_img')->where('media_id', $media_id)->first();
    }


    /**
     * 设置上榜
     * @param $uid
     * @param  bool  $bool  是否主动上榜，被动时下榜(状态1)不置为上榜(状态2)
     * @return bool
     * @throws AlertException
     */
    public function passive($uid, $bool = false)
    {
        $appearance = AppearanceModel::where('uid', $uid)->first();
        $partner = PartnerModel::where('uid', $uid)->first();
        if (!$partner) {
            return false;
        }
        $school = SchoolModel::where('school', $partner->school)->first();
        // 满足上榜条件
        if (
            $partner
            && $school
            && $partner->sex
            && $partner->is_sell == 1
        ) {
            try {
                if (!$appearance) {
                    AppearanceModel::create([
                        'uid' => $uid,
                        'partner_id' => $partner->id,
                        'sex' => $partner->sex,
                        'province' => $school->province,
                        'city' => $school->city,
                        'school' => $school->school,
                        'state' => 2,
                    ]);
                } else {
                    // 同步学校
                    if ($appearance->school != $school->school) {
                        $appearance->province = $school->province;
                        $appearance->city = $school->city;
                        $appearance->school = $school->school;
                    }

                    // 同步性别
                    if ($appearance->sex != $partner->sex) {
                        $appearance->sex = $partner->sex;
                    }

                    // 修改状态为上榜
                    if ($appearance->state != 1 || $bool) {
                        $appearance->state = 2;
                    }
                    $appearance->save();
                }
            } catch (QueryException $e) {
                throw new AlertException("操作太快了");
            }

            // 初始月榜
            $type = 'monthly';
            $date = date("Y-m-01");
            if (
                !PartnerRankModel::where('partner_id', $partner->id)
                ->where('date', $date)
                ->where('type', $type)
                ->first()
            ) {
                PartnerRankModel::create([
                    'type' => $type,
                    'sex' => $partner->sex,
                    'partner_id' => $partner->id,
                    'count' => $partner->praises ?: 1,
                    'date' => $date,
                    'school' => $partner->school,
                ]);
            }

            // 初始周榜
            $type = 'weekly';
            $date = date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600));
            if (
                !PartnerRankModel::where('partner_id', $partner->id)
                ->where('date', $date)
                ->where('type', $type)
                ->first()
            ) {
                PartnerRankModel::create([
                    'type' => $type,
                    'sex' => $partner->sex,
                    'partner_id' => $partner->id,
                    'count' => $partner->praises ?: 1,
                    'date' => $date,
                    'school' => $partner->school,
                ]);
            }

            return true;
        } else {
            // 上架
            if ($appearance) {
                $appearance->state = -1;
                $appearance->save();
            }

            return false;
        }
    }
}
