<?php

namespace App\Services\Pair;

use App\Models\Fpdx\PairModel;
use App\Models\User\UserModel;
use Illuminate\Support\Facades\Redis;

class CheckService
{

    public $id;
    public $user;

    public function baocun($stage_id)
    {
        // 开始钉钉通知
//                \Curl::to("http://api.deep.fenpeiduixiang.com/api/ding/pairsave/begin/{$stage_id}")->get();

        Redis::Del('pair:data');
        $pairs = PairModel::where('stage_id', $stage_id)->whereNotNull('assoc_id')->get();
        foreach ($pairs as $pair) {
            try {
                $this->id = $pair->id;
                $user = $this->getUser($this->getPair()->uid);
                $other = $this->getUser($this->getOtherPair()->uid);

                Redis::Zadd('pair:data', $pair->id, json_encode([
                    'user' => $user,
                    'other' => $other,
                    'pair' => $pair,
                ]));
            } catch (\Exception $exception) {
            }
        }

        // 结束钉钉通知
        if (app()->environment() == 'production') {
            \Curl::to("http://api.deep.fenpeiduixiang.com/api/ding/pairsave/end/{$stage_id}")->get();
        }
    }


    //

    public function getUser($uid)
    {
        $user = UserModel::selectRaw(" `uid`,
           `uid`,
           `sex`,
           `sxo`,
           `age`,
           `height`,
            YEAR(`age`) as `year`,
            YEAR(`age`) - `pair_max_age` as `max_year`,
            YEAR(`age`)+ `pair_min_age` as `min_year`,
            `pair_min_age`,
            `pair_max_age`,
            `fpdx_like`,
            `pair_province`,
            `pair_all`,
            `home`,
            `address`,
            `school`
            ")->find($uid);
        @list($user->province, $user->city) = explode('-', $user->address);
        $user->fpdx_like = explode(',', $user->fpdx_like);

        return $user;
    }

    public function getPair()
    {
        return PairModel::find($this->id);
    }

    public function getOtherPair()
    {
        $pair = $this->getPair();

        return PairModel::where('assoc_id', $pair->id)->first();
    }

    /**
     * @param $stage_id
     * @return array
     * 1 => '年龄必须比我大',
     * 2 => '年龄必须比我小',
     * 3 => '身高必须比我高',
     * 4 => '身高必须比我矮',
     * 5 => '必须是同校',
     * 6 => '必须同城',
     * 7 => '必须是不同校',
     * 8 => '接受同省调剂',
     * 9 => '必须是同乡'
     */
    public function check($stage_id)
    {
        // 开始钉钉通知
        if (app()->environment() == 'production') {
            \Curl::to("http://api.deep.fenpeiduixiang.com/api/ding/paircheck/begin/{$stage_id}")->get();
        }

        $errors = array();
        $pairs = Redis::ZRANGE('pair:data', 0, -1, 'WITHSCORES');
        foreach ($pairs as $key => $id) {
            $data = json_decode($key);
            $user = $data->user;
            $other = $data->other;
            $pair = $data->pair;
            $message = $this->where($user, $other, $pair);
            if ($message) {
                array_push($errors, $pair->id . $message);
            }
        }
        // 结束钉钉通知
        if (app()->environment() == 'production') {
            \Curl::to("http://api.deep.fenpeiduixiang.com/api/ding/paircheck/end/{$stage_id}")->withData([
                'errors' => $errors,
            ])->post();
        }

        return $errors;
    }

    public function where($user, $other, $pair)
    {
        $message = '';
        if (!$this->isSex($user, $other)) {
            $message .= "对方性取向不满足\t";
        }
        if (!$this->isSxo($user, $other)) {
            $message .= "我的性取向不满足\t";
        }
        if (!$this->isAgeDiff($user, $other)) {
            $message .= "年龄不在区间内\t";
        }
        if ($this->isRepeat($user, $other, $pair)) {
            $message .= "以前匹配过\t";
        }

        ## 不允许全国调剂
        if (!$user->pair_all) {
            ## 允许全国调剂
            if ($user->pair_province) {
                foreach ($user->fpdx_like as $type) {
                    switch ($type) {
                        case '5':
                            if ($user->school != $other->school) {
                                if (!$this->isProvince($user, $other)) {
                                    $message .= "没有跟我同校，";
                                    $message .= "也没有跟我同省\t";
                                }
                            }
                            break;
                        case '6':
                            if (!$this->isCity($user, $other)) {
                                if (!$this->isProvince($user, $other)) {
                                    $message .= "没有跟我同市，";
                                    $message .= "也没有跟我同省\t";
                                }
                            }
                            break;
                        case '7':
                            if ($user->school == $other->school) {
                                if (!$this->isProvince($user, $other)) {
                                    $message .= "必须跟我不同校，";
                                    $message .= "也没有跟我同省\t";
                                }
                            }
                            break;
                        case '8':
                            if (!$this->isProvince($user, $other)) {
                                $message .= "没有跟我同省\t";
                            }
                            break;
                    }
                }
            } else {
                foreach ($user->fpdx_like as $type) {
                    switch ($type) {
                        case '5':
                            if ($user->school != $other->school) {
                                $message .= "没有跟我同校，";
                            }
                            break;
                        case '6':
                            if (!$this->isCity($user, $other)) {
                                $message .= "没有跟我同市，";
                            }
                            break;
                        case '7':
                            if ($user->school == $other->school) {
                                $message .= "必须跟我不同校，";
                            }
                            break;
                        case '8':
                            if (!$this->isProvince($user, $other)) {
                                $message .= "没有跟我同省\t";
                            }
                            break;
                        case '9':
                            if (!$this->isHome($user, $other)) {
                                $message .= "没有跟我同乡";
                            }
                            break;
                    }
                }
            }
        }

        return $message;
    }

    public function isSex($user, $other)
    {
        return ($user->sex == $other->sxo) ? true : false;
    }

    public function isSxo($user, $other)
    {
        if ($user->sxo == $other->sex) {
            return true;
        } else {
            return false;
        }
    }

    public function isAgeDiff($user, $other)
    {
        $max = date('Y', strtotime($user->age)) + $user->pair_min_age;
        $min = date('Y', strtotime($user->age)) - $user->pair_max_age;
        $age = date('Y', strtotime($other->age));
        if ($min <= $age && $age <= $max) {
            return true;
        } else {
            return false;
        }
    }

    public function isRepeat($user, $other, $pair)
    {
        $array = PairModel::whereRaw("id IN (
            SELECT `assoc_id`
        FROM `koudai`.`kdgx_partner_charge_pair`
       WHERE `uid`= ?
         and `assoc_id` IS NOT NULL
         and `stage_id`< ?)", [$user->uid, $pair->stage_id])->pluck('uid')->toArray();
        if (in_array($other->uid, $array)) {
            return true;
        } else {
            return false;
        }
    }


    //年龄比我大

    public function isProvince($user, $other)
    {
        if ($user->province == $other->province) {
            return true;
        } else {
            return false;
        }
    }

    //年龄比我小

    public function isCity($user, $other)
    {
        if ($user->city == $other->city) {
            return true;
        } else {
            return false;
        }
    }

    //身高比我高

    public function isHome($user, $other)
    {
        if ($user->home == $other->home) {
            return true;
        } else {
            return false;
        }
    }

    //身高比我矮

    public function luodan($pair)
    {
        $user = $this->getUser($pair->uid);
        $unlikes = Redis::SMEMBERS('fpdx_pairs_' . $user->uid);
        \DB::connection()->enableQueryLog(); // 开启查询日志

        $others = UserModel::selectRaw("`uid`,
            `sex`,
            `sxo`,
            `age`,
            `height`,
            YEAR(`age`) as `year`,
            YEAR(`age`) - `pair_max_age` as `max_year`,
            YEAR(`age`)+ `pair_min_age` as `min_year`,
            `pair_min_age`, `pair_max_age`,
            `fpdx_like`,
            `pair_province`,
            `pair_all`,
            `address`,
            `home`,
            `school`")
            ->where('sex', $user->sxo)
            ->where('sxo', $user->sex)
            ->when($user->sex == 1 && $user->sxo == 2, function ($query) use ($user) {
                return $query->where('height', '<', $user->height - 5);
            })
            ->when($user->sex == 2 && $user->sxo == 1, function ($query) use ($user) {
                return $query->where('height', '>', $user->height + 5);
            })
            ->whereRaw(" YEAR(`age`) BETWEEN ? AND ?", [$user->max_year, $user->min_year])
            ->whereRaw("? BETWEEN YEAR(`age`) - `pair_max_age` AND YEAR(`age`)+ `pair_min_age`", [$user->year])
            ->when(in_array('1', $user->fpdx_like), function ($query) use ($user) {
                return $query->whereRaw("YEAR(`age`) <= ?", $user->year);
            })
            // 年龄必须比我小; 年龄差距最大4岁
            ->when(in_array('2', $user->fpdx_like), function ($query) use ($user) {
                return $query->whereRaw("YEAR(`age`) >= ?", $user->year);
            })
            ->when(in_array('3', $user->fpdx_like), function ($query) use ($user) {
                return $query->where('height', '>=', $user->height);
            })
            ->when(in_array('4', $user->fpdx_like), function ($query) use ($user) {
                return $query->where('height', '<=', $user->height);
            })
            ->when(in_array('5', $user->fpdx_like), function ($query) use ($user) {
                return $query->where('school', $user->school);
            })
            ->when(in_array('6', $user->fpdx_like), function ($query) use ($user) {
                return $query->where('address', $user->address);
            })
            ->when(in_array('7', $user->fpdx_like), function ($query) use ($user) {
                return $query->where('school', '<>', $user->school);
            })
            ->when(in_array('8', $user->fpdx_like), function ($query) use ($user) {
                return $query->where('address', 'like', $user->province . "-%");
            })
            ->when(in_array('9', $user->fpdx_like), function ($query) use ($user) {
                return $query->where('home', $user->home);
            })
            ->whereIn(
                'uid',
                PairModel::where('stage_id', $pair->stage_id)
                    ->whereNull('assoc_id')
                    ->where('state', '>', 100)
                    ->where('uid', '<>', $user->uid)
                    ->whereNotIn('uid', $unlikes)
                    ->pluck('uid')
            )
            ->get();
        dump($others->implode('uid', ','));
        foreach ($others as $other) {
            $other = $this->getUser($other->uid);
            if (in_array(5, $other->fpdx_like)) {
                if ($user->school != $other->school) {
                    dump("{$other->uid}[学校]必须一致");
                    continue;
                }
            }
            if (in_array(6, $other->fpdx_like)) {
                if ($user->city != $other->city) {
                    dump("{$other->uid}[城市]必须一致");
                    continue;
                }
            }
            if (in_array(7, $other->fpdx_like)) {
                if ($user->school == $other->school) {
                    dump("{$other->uid}[学校]必须不一致");
                    continue;
                }
            }
            if (in_array(9, $other->fpdx_like)) {
                if ($user->home != $other->home) {
                    dump("{$other->uid}[家乡]必须一致");
                    continue;
                }
            }
            if ($other->pair_province || in_array(8, $other->fpdx_like)) {
                if ($user->province != $other->province) {
                    dump("{$other->uid}[省]必须一致");
                    continue;
                }
            }
            dump("{$other->uid}条件全部满足");
        }
    }


    //跟我同校

    public function isAgeBigger($user, $other)
    {
        if ((int)($user->age) >= (int)($other->age)) {
            return true;
        } else {
            return false;
        }
    }

    public function isAgeSmaller($user, $other)
    {
        if ((int)($user->age) <= (int)($other->age)) {
            return true;
        } else {
            return false;
        }
    }


    //跟我同省

    public function isHeightHigher($user, $other)
    {
        if ($user->height <= $other->height) {
            return true;
        } else {
            return false;
        }
    }

    //跟我同城

    public function isHeightShorter($user, $other)
    {
        if ($user->height >= $other->height) {
            return true;
        } else {
            return false;
        }
    }

    public function isSchool($user, $other)
    {
        if ($user->schoool == $other->schoool) {
            return 1;
        } else {
            return 0;
        }
    }
}
