<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AlertException;
use App\Http\Controllers\Core\Auth;
use App\Models\Appearance\AppearanceModel;
use App\Models\CheckLog;
use App\Models\PartnerModel;
use App\Http\Controllers\Controller;
use App\Models\User\FeedcheckLogModel;
use App\Services\Appearance\RankService;
use App\Services\User\PartnerService;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

/**
 * Class PartnerController
 * @package App\Http\Controllers\Admin
 */
class PartnerController extends Controller
{
    /**
     * 通过qq或微信搜索某条卡片
     * @param  Request  $request
     * @return array
     */
    public function search(Request $request)
    {
        $this->validate($request, [
            'content' => 'required',
        ]);

        $content = $request->input('content');
        if (is_int(strpos($content, 'uid'))) {
            $uid = substr($content, 4);
            $where = ['uid' => $uid];
        } elseif (is_int(strpos($content, 'qq'))) {
            $qq = substr($content, 3);
            $where = ['qq' => $qq];
        } elseif (is_int(strpos($content, 'weixin'))) {
            $weixin = substr($content, 7);
            $where = ['weixin' => $weixin];
        } elseif (is_int(strpos($content, 'cid'))) {
            $partner_id = substr($content, 4);
            $where = ['id' => $partner_id];
        } else {
            return response([
                'code' => 422,
                'message' => '搜索格式：uid=xxx,qq=xx,weixin=xxx,cid=xxx'
            ]);
        }
        $partners = PartnerModel::where($where)->limit(10)->get();
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $partners
        );
    }

    /**
     * 添加审核日志
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     */
    public function addCheckLog(int $partner_id, Request $request)
    {
        $data = array(
            'partner_id' => $partner_id,
            'log' => json_encode($request->toArray())
        );
        $clog = new CheckLog();
        $clog->fill($data)->save();
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 审核卡片
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     * @throws \Exception
     */
    public function checkPartner(int $partner_id, Request $request)
    {
        $this->validate($request, [
            'field' => 'required',
            'check' => 'required'
        ]);
        $field = $request->input('field');
        $check = $request->input('check', -1);
        $ps = new PartnerService();
        $ps->check($partner_id, $field, $check);

        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 切换是否推送到信息流
     * @param  int  $partner_id
     * @return array
     */
    public function pushFeed(int $partner_id)
    {
        $partner = PartnerModel::findOrFail($partner_id);
        $partner->is_push_feed = abs($partner->is_push_feed - 1);
        $partner->save();

        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 上/下榜卡片
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function xhxcrank(int $partner_id, Request $request)
    {
        $this->validate($request, [
            'xhxc_rank_state' => 'required|in:-1,1,2'
        ]);
        $partner = PartnerModel::findOrFail($partner_id);
        $xhxc_rank_state = $request->post('xhxc_rank_state');
        $appearance = AppearanceModel::where('partner_id', $partner_id)->first();
        if (!collect($appearance)->isEmpty()) {
            if (2 == $xhxc_rank_state) {
                // 上榜
                if (!(new RankService())->passive($partner->uid)) {
                    throw new AlertException("不符合上榜条件", 101);
                }
            } else {
                $appearance->state = $xhxc_rank_state;
                $appearance->save();
            }
        } elseif (2 == $xhxc_rank_state) {
            // 上榜
            if (!(new RankService())->passive($partner->uid)) {
                throw new AlertException("不符合上榜条件", 101);
            }
        }
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 获取审核列表
     * @param  Request  $request
     * @return array
     */
    public function checkList(Request $request)
    {
        // 页数
        $page = $request->get('page', 1);

        // 是否是72h活动的
        $is_fpdx = $request->post('fpdx', null);
        if (!is_null($is_fpdx)) {
            $where[] = ['is_fpdx', $is_fpdx];
        }

        // 性别
        $sex = $request->post('sex', null);
        if (!is_null($sex)) {
            $where[] = ['sex', $sex];
        }

        // 是否精选
        $is_recommend = $request->post('is_recommend', null);
        if (!is_null($is_recommend)) {
            $where[] = ['is_select', $is_recommend];
        }

        // 是否需要审核
        $is_commit_check = $request->post('is_commit_check', null);
        if (!is_null($is_commit_check)) {
            $where[] = ['is_commit_check', $is_commit_check];
        }

        // 是否上架
        $is_sell = $request->post('is_sell', null);
        if (!is_null($is_sell)) {
            $where[] = ['is_sell', $is_sell];
        }

        // 是否推荐到信息流
        $is_push_feed = $request->post('is_push_feed', null);
        if (!is_null($is_push_feed)) {
            $where[] = ['is_push_feed', $is_push_feed];
        }

        // 是否有照片
        $is_photo = $request->post('photo', 0);
        // 是否关注公众号
        $is_subscribe = $request->post('is_subscribe', 0);

        // 在校花校草榜的状态
        $xhxc_rank_state = $request->post('xhxc_rank_state', null);
        if (!is_null($xhxc_rank_state)) {
            // 获取上榜的卡片集合
            $xhxcrank = AppearanceModel::where(
                'state',
                $xhxc_rank_state
            )->get(['partner_id'])->pluck('partner_id')->toArray();
        } else {
            $xhxcrank = array();
        }

        $where[] = ['is_hide', 0];
        $orderby = 'update_at';
        if (1 == $is_sell) {
            $orderby = "upload_at";
        }

        if ($is_subscribe) {
            $where[] = ['openid.subscribe', 1];
            $where[] = ['openid.public_id', 'gh_b598cb7474d8'];
            if (in_array($sex, [1, 2])) {
                $where[] = ['partner.sex', $sex];
            }
            $partners = DB::table('kdgx_partner_charge_partner as partner')
                ->join('kddx_user_openid as openid', 'partner.uid', 'openid.uid')
                ->where($where)->when($is_photo, function (/** @var Builder $query */ $query) use ($is_photo) {
                    if (1 == $is_photo) {
                        return $query->where(function (/** @var Builder $query */ $query) {
                            $query->where('check_photo', 1)->orWhere('voice_check', 1)->orWhere('photo_1_check', 1)
                                ->orWhere('photo_2_check', 1)->orWhere('photo_3_check', 1)->orWhere('photo_4_check', 1);
                        });
                    }
                })->when(!is_null($xhxc_rank_state), function (/** @var Builder $query */ $query) use ($xhxcrank) {
                    return $query->whereIn('p.id', $xhxcrank);
                })->orderBy(
                "partner.{$orderby}",
                'desc'
            )->skip(($page - 1) * 100)->take(100)->select('partner.*')->get();
            $count = DB::table('kdgx_partner_charge_partner as partner')
                ->join('kddx_user_openid as openid', 'partner.uid', 'openid.uid')
                ->where($where)->when($is_photo, function (/** @var Builder $query */ $query) use ($is_photo) {
                    if (1 == $is_photo) {
                        return $query->where(function (/** @var Builder $query */ $query) {
                            $query->where('check_photo', 1)->orWhere('voice_check', 1)->orWhere('photo_1_check', 1)
                                ->orWhere('photo_2_check', 1)->orWhere('photo_3_check', 1)->orWhere('photo_4_check', 1);
                        });
                    }
                })->count();
        } else {
            if (in_array($sex, [1, 2])) {
                $where[] = ['sex', $sex];
            }

            /** @var PartnerModel $partners */
            $partners = PartnerModel::where($where)->when(
                $is_photo,
                function (/** @var Builder $query */ $query) use ($is_photo) {
                    if (1 == $is_photo) {
                        return $query->where(function (/** @var Builder $query */ $query) {
                            $query->where('check_photo', 1)->orWhere('voice_check', 1)->orWhere('photo_1_check', 1)
                                ->orWhere('photo_2_check', 1)->orWhere('photo_3_check', 1)->orWhere('photo_4_check', 1);
                        });
                    }
                }
            )->when(!is_null($xhxc_rank_state), function (/** @var Builder $query */ $query) use ($xhxcrank) {
                    return $query->whereIn('id', $xhxcrank);
            })->orderBy($orderby, 'desc')->skip(($page - 1) * 100)->take(100)->get();
            $count = PartnerModel::where($where)->when(
                $is_photo,
                function (/** @var Builder $query */ $query) use ($is_photo) {
                    if (1 == $is_photo) {
                        return $query->where(function (/** @var Builder $query */ $query) {
                            $query->where('check_photo', 1)->orWhere('voice_check', 1)->orWhere('photo_1_check', 1)
                                ->orWhere('photo_2_check', 1)->orWhere('photo_3_check', 1)->orWhere('photo_4_check', 1);
                        });
                    }
                }
            )->count();
        }

        $xhxcranks = AppearanceModel::whereIn('partner_id', $partners->pluck('id')->toArray())->get()->toArray();
        $xhxcranks = array_combine(array_column($xhxcranks, "partner_id"), $xhxcranks);
        foreach ($partners as &$partner) {
            /** @var PartnerModel $partner */
            if (isset($xhxcranks[$partner->id])) {
                $partner->xhxc_rank_state = $xhxcranks[$partner->id]['state'];
            } else {
                $partner->xhxc_rank_state = 1;
            }
            if (!empty($partner->photo_src)) {
                $partner->photo_src = "https://oss.pocketuniversity.cn{$partner->photo_src}";
            }
            if (!empty($partner->photo_1)) {
                $partner->photo_1 = "https://oss.pocketuniversity.cn{$partner->photo_1}";
            }
            if (!empty($partner->photo_2)) {
                $partner->photo_2 = "https://oss.pocketuniversity.cn{$partner->photo_2}";
            }
            if (!empty($partner->photo_3)) {
                $partner->photo_3 = "https://oss.pocketuniversity.cn{$partner->photo_3}";
            }
            if (!empty($partner->photo_4)) {
                $partner->photo_4 = "https://oss.pocketuniversity.cn{$partner->photo_4}";
            }
            $partner->is_recommend = $partner->is_select;
            $partner->sell_count = 1;
        }

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'page' => $page,
                'limit' => 100,
                'total' => $count,
                'list' => $partners
            ],
        );
    }

    /**
     * 「list」活动审核卡片
     * @param  Request  $request
     * @return array
     */
    public function feedcheckList(Request $request)
    {
        $where = array(
            ['feedcheck_cnt', '<', 5],
            ['is_sell', 1],
            ['is_recommend', 0],
            ['feed_push_type', 3],
            ['login_at', '>', time() - 90 * 86400]
        );

        // 性别
        $sex = $request->post('sex', null);
        if (!is_null($sex)) {
            $where[] = ['sex', $sex];
        }


        // 时间排序
        $request->post('sort', 'desc');

        $uid = Auth::auth();
        $seeIds = Redis::zrange("feedcheck:{$uid}", 0, -1);
        Redis::expire("feedcheck:{$uid}", 7200);
        if (empty($seeIds)) {
            $seeIds = array();
        }

        array_walk($seeIds, function (&$value) {
            $value = intval($value);
        });

        $partnerIds = FeedcheckLogModel::where([
            ['uid', $uid],
            ['expire_at', 0]
        ])->get(['partner_id'])->pluck('partner_id')->toArray();
        $partnerIds = array_merge($partnerIds, $seeIds);

        /** @var PartnerModel[] $partners */
        $partners = PartnerModel::where($where)->whereNotIn('id', $partnerIds)->take(10)->orderBy(
            'feedcheck_cnt',
            'asc'
        )->get();

        foreach ($partners as &$partner) {
            Redis::zadd("feedcheck:{$uid}", [$partner->id => time()]);
            if (!empty($partner->photo_src)) {
                $partner->photo_src = "https://oss.pocketuniversity.cn{$partner->photo_src}";
            }
            if (!empty($partner->photo_1)) {
                $partner->photo_1 = "https://oss.pocketuniversity.cn{$partner->photo_1}";
            }
            if (!empty($partner->photo_2)) {
                $partner->photo_2 = "https://oss.pocketuniversity.cn{$partner->photo_2}";
            }
            if (!empty($partner->photo_3)) {
                $partner->photo_3 = "https://oss.pocketuniversity.cn{$partner->photo_3}";
            }
            if (!empty($partner->photo_4)) {
                $partner->photo_4 = "https://oss.pocketuniversity.cn{$partner->photo_4}";
            }
            if (1 != $partner->check_photo) {
                unset($partner->photo_src);
            }
            if (1 != $partner->photo_1_check) {
                unset($partner->photo_1);
            }
            if (1 != $partner->photo_2_check) {
                unset($partner->photo_2);
            }
            if (1 != $partner->photo_3_check) {
                unset($partner->photo_3);
            }
            if (1 != $partner->photo_4_check) {
                unset($partner->photo_4);
            }
            if (1 != $partner->voice_check) {
                unset($partner->voice);
            }
            unset($partner->check_photo);
            unset($partner->photo_1_check);
            unset($partner->photo_2_check);
            unset($partner->photo_3_check);
            unset($partner->photo_4_check);
            unset($partner->voice_check);
        }

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $partners
        );
    }

    /**
     * 通过|不通过某卡片
     * @param  int  $partner_id
     * @param  Request  $request
     * @return array
     * @throws AlertException
     */
    public function passPartner(int $partner_id, Request $request)
    {
        $ispass = $request->post('is_pass', 0);
        $uid = Auth::auth();
        $partner = PartnerModel::findOrFail($partner_id);

        if (FeedcheckLogModel::where([['uid', $uid], ['partner_id', $partner_id], ['expire_at', 0]])->exists()) {
            return response([
                'code' => 200,
                'message' => 'success'
            ]);
        }

        try {
            if (5 <= FeedcheckLogModel::where([['partner_id', $partner_id], ['expire_at', 0]])->count()) {
                return response([
                    'code' => 200,
                    'message' => 'success'
                ]);
            }
            FeedcheckLogModel::create([
                'uid' => $uid,
                'partner_id' => $partner_id,
                'is_pass' => $ispass,
                'created_at' => time(),
                'expire_at' => 0
            ]);
            $partner->increment('feedcheck_cnt', 1);
            if (0 == $ispass) {
                $cnt = FeedcheckLogModel::where([
                    ['partner_id', $partner_id],
                    ['is_pass', 0],
                    ['expire_at', 0]
                ])->count();
                if (3 <= $cnt || 1 == $partner->feedcheck_cnt) {
                    $partner->is_push_feed = 0;

                    // 取消推荐通知
                    try {
                        $notice = new \App\Services\Partner\NoticeService();
                        $notice->recommendCancel($partner->uid);
                    } catch (\Exception $e) {
                        app('sentry')->captureException($e);
                    }
                }
                $partner->save();
            } else {
                $cnt = FeedcheckLogModel::where([
                    ['partner_id', $partner_id],
                    ['is_pass', 1],
                    ['expire_at', 0]
                ])->count();
                3 <= $cnt && $partner->is_push_feed = 1;
                $cnt >= 5 && $partner->is_recommend = 1;
                $partner->save();
            }
        } catch (QueryException $e) {
            throw new AlertException("划得来太快了哦");
        }
        return response([
            'code' => 200,
            'message' => 'success'
        ]);
    }

    /**
     * 审核排行榜
     * @param  Request  $request
     * @return array
     */
    public function passRank(Request $request)
    {
        $rank_type = $request->get('ranktype', 'day');
        switch ($rank_type) {
            case "yesterday":
                $begin_at = mktime(0, 0, 0) - 86400;
                $end_at = mktime(0, 0, 0);
                break;
            case "day":
                $date = $request->get('date', date('Y-m-d'));
                $begin_at = strtotime($date);
                $end_at = $begin_at + 86400 - 1;
                break;
            case "week":
            default:
                $date = $request->get(
                    "date",
                    date('Y-m-d', (time() - ((date('w') == 0 ? 7 : date('w')) - 1) * 24 * 3600))
                );
                $begin_at = strtotime($date);
                $end_at = $begin_at + 7 * 86400 - 1;
                break;
        }

        $ranks = FeedcheckLogModel::select(DB::raw("uid, count(*) as count"))
            ->whereBetween('created_at', [$begin_at, $end_at])
            ->groupBy('uid')
            ->get();

        foreach ($ranks as $rank) {
            $passCnt = FeedcheckLogModel::whereBetween('created_at', [$begin_at, $end_at])->where([
                ['uid', $rank->uid],
                ['is_pass', 1]
            ])->count();
            $rank->pass_count = $passCnt;
            $rank->pass = sprintf('%.2f', ($passCnt / $rank->count * 100));
            $rank->user = \DB::table('ta_users')->select('uid', 'name', 'headimgurl')->where(
                'uid',
                $rank->uid
            )->first();
        }

        $ranks = $ranks->sortByDesc(function ($rank) {
            return $rank->count;
        })->values()->all();

        return response([
            "code" => 200,
            "message" => "success",
            "data" => $ranks
        ]);
    }

    public function unpushList(Request $request)
    {
        $page = $request->get('page', 1);

        $count = PartnerModel::where(array(['is_push_feed', 0], ['is_sell', 1], ['feed_push_type', 3]))->count();

        $datas = PartnerModel::where(array(['is_push_feed', 0], ['is_sell', 1], ['feed_push_type', 3]))
            ->skip(($page - 1) * 100)->take(100)->get([
                'id',
                'photo_src',
                'check_photo',
                'photo_1',
                'photo_1_check',
                'photo_2',
                'photo_2_check',
                'photo_3',
                'photo_3_check',
                'photo_4',
                'photo_4_check',
            ]);
        $datas->map(function (&$data) {
            /** @var PartnerModel $data */
            if (1 != $data->check_photo) {
                unset($data->photo_src);
            }
            if (1 != $data->photo_1_check) {
                unset($data->photo_1);
            }
            if (1 != $data->photo_2_check) {
                unset($data->photo_2);
            }
            if (1 != $data->photo_3_check) {
                unset($data->photo_3);
            }
            if (1 != $data->photo_4_check) {
                unset($data->photo_4);
            }
            unset($data->check_photo);
            unset($data->photo_1_check);
            unset($data->photo_2_check);
            unset($data->photo_3_check);
            unset($data->photo_4_check);
            if (
                !isset($data->photo_src)
                && !isset($data->photo_1)
                && !isset($data->photo_2)
                && !isset($data->photo_3)
                && !isset($data->photo_4)
            ) {
                PartnerModel::where('id', $data->id)->update(['feed_push_type' => 5]);
                unset($data);
            }
        });
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'page' => $page,
                'limit' => 100,
                'total' => $count,
                'list' => $datas
            ],
        );
    }

    public function push(int $partner_id)
    {
        PartnerModel::where('id', $partner_id)->update(['is_push_feed' => 1]);
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 某人卡片列表
     * @param  Request  $request
     * @return array
     */
    public function userList(Request $request)
    {
        $uid = $request->get('uid');
        $partners = PartnerModel::where('uid', $uid)->get();
        foreach ($partners as &$partner) {
            if (!empty($partner->photo_src)) {
                $partner->photo_src = "https://oss.pocketuniversity.cn{$partner->photo_src}";
            }
            if (!empty($partner->photo_1)) {
                $partner->photo_1 = "https://oss.pocketuniversity.cn{$partner->photo_1}";
            }
            if (!empty($partner->photo_2)) {
                $partner->photo_2 = "https://oss.pocketuniversity.cn{$partner->photo_2}";
            }
            if (!empty($partner->photo_3)) {
                $partner->photo_3 = "https://oss.pocketuniversity.cn{$partner->photo_3}";
            }
            if (!empty($partner->photo_4)) {
                $partner->photo_4 = "https://oss.pocketuniversity.cn{$partner->photo_4}";
            }
        }
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $partners,
        );
    }

    /**
     * 推荐/取消 卡片
     * @param  int  $partner_id
     * @return array
     */
    public function commitPartner(int $partner_id)
    {
        /** @var PartnerModel $partner */
        $partner = PartnerModel::findOrFail($partner_id);
        $partner->is_select = abs($partner->is_select - 1);
        $partner->wait_select = 2;
        $partner->save();
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    /**
     * 推荐/取消 语音
     * @param  int  $partner_id
     * @return array
     */
    public function commitVoice(int $partner_id)
    {
        $partner = PartnerModel::findOrFail($partner_id);
        $partner->is_voice_recommend = abs($partner->is_voice_recommend - 1);
        $partner->save();
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    public function selects(Request $request)
    {
        $selects = $request->post();
        foreach ($selects as $select) {
            PartnerModel::where([
                ['id', $select['partner_id']],
                ['wait_select', 1]
            ])->update([
                'select_at' => time(),
                'is_select' => $select['select'],
                'wait_select' => 2
            ]);
        }
        return array(
            'code' => 200,
            'message' => 'success'
        );
    }

    public function waitSelects(Request $request)
    {
        $limit = 20;
        $page = $request->get('page', 1);
        if (1 == $page) {
            $total = PartnerModel::where([
                ['is_sell', 1],
                ['wait_select', 1]
            ])->where(function (/** @var \Illuminate\Database\Eloquent\Builder $query */ $query) {
                return $query->where('check_photo', 1)->orWhere('photo_1_check', 1)
                    ->orWhere('photo_2_check', 1)->orWhere('photo_3_check', 1)
                    ->orWhere('photo_4_check', 1);
            })->count();
        } else {
            $total = 10000;
        }
        $datas = PartnerModel::where([
            ['is_sell', 1],
            ['wait_select', 1]
        ])->where(function (/** @var \Illuminate\Database\Eloquent\Builder $query */ $query) {
            return $query->where('check_photo', 1)
                ->orWhere('photo_1_check', 1)
                ->orWhere('photo_2_check', 1)
                ->orWhere('photo_3_check', 1)
                ->orWhere('photo_4_check', 1);
        })->skip(($page - 1) * $limit)
            ->take($limit)
            ->get();
        foreach ($datas as &$data) {
            /** @var PartnerModel $data */
            if ($data->check_photo == 1) {
                $data->photo_src = "http://oss.pocketuniversity.cn{$data->photo_src}";
            } else {
                unset($data->photo_src);
            }
            if ($data->photo_1_check == 1) {
                $data->photo_1 = "http://oss.pocketuniversity.cn{$data->photo_1}";
            } else {
                unset($data->photo_1);
            }
            if ($data->photo_2_check == 1) {
                $data->photo_2 = "http://oss.pocketuniversity.cn{$data->photo_2}";
            } else {
                unset($data->photo_2);
            }
            if ($data->photo_3_check == 1) {
                $data->photo_3 = "http://oss.pocketuniversity.cn{$data->photo_3}";
            } else {
                unset($data->photo_3);
            }
            if ($data->photo_4_check == 1) {
                $data->photo_4 = "http://oss.pocketuniversity.cn{$data->photo_4}";
            } else {
                unset($data->photo_4);
            }
        }

        return array(
            'code' => 200,
            'message' => 'success',
            'data' => [
                'page' => [
                    'page' => (int)$page,
                    'limit' => $limit,
                    'total' => $total
                ],
                'partners' => $datas
            ]
        );
    }


    public function getBeautyList(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        $sex = $request->get('sex', 1);
        $photos = \DB::table('partner_beautys')
            ->where('new_photo', '!=', '')
            ->where('sex', $sex)
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get();
        return response([
            'code' => 200,
            'message' => 'OK',
            'data' => $photos
        ]);
    }
}
