<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\AlertException;
use App\Exceptions\ApiException;
use App\Exceptions\DBException;
use App\Http\Controllers\Core\Auth;
use App\Models\Fpdx\PairModel;
use App\Http\Controllers\Controller;
use App\Models\User\UserModel;
use App\Services\Pair\PairService;
use Illuminate\Http\Request;
use App\Models\OrderModel;

class PairController extends Controller
{
    /**
     * 能够根据uid查询交友卡片及报名历史信息
     * @param  int  $uid
     * @return array
     */
    public function getHistoryPair(int $uid)
    {
        $user = UserModel::find($uid);
        $pairs = PairModel::where('uid', $uid)->orderBy('stage_id', 'desc')->get();
        foreach ($pairs as &$pair) {
            $orders = OrderModel::where([
                ['uid', $uid],
                ['order_state', '!=', 0],
                ['type', 3],
                ['type_id', $pair->stage_id]
            ])->get();
            $pair->orders = $orders;
            if (!empty($pair->assoc_id)) {
                $other_pair = PairModel::find($pair->assoc_id);
                $other_user = UserModel::find($other_pair->uid);
                $pair->other = array(
                    'pair' => $other_pair,
                    'user' => $other_user
                );
            } else {
                $pair->other = array();
            }
        }
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => array(
                'user' => $user,
                'pairs' => $pairs
            ),
        );
    }

    /**
     * 退款
     * @param  int  $uid
     * @param  float  $amount  退款金额 1.00
     * @return bool
     * @throws AlertException
     */
    private function refund(int $uid, float $amount)
    {
        $data = array(
            'uid' => $uid,
            'amount' => $amount
        );
        $data['sign'] = Md5("kdgx_fpdx_refund{$uid}+{$amount}");
        $url = config('app.pocket_url') . "/chargePartner/apiBack/oauthRefund";
        $reponse = json_decode(\Curl::to($url)->withData($data)->post());
        if ($reponse->errcode == 0) {
            return true;
        } else {
            throw new AlertException("退款失败,请联系技术小哥哥来背锅!～.～!请提供错误信息[{$reponse->errmsg}]", $reponse->errcode);
        }
    }

    /**
     * 删除当前期的报名
     * @param  int  $uid
     * @return array
     * @throws AlertException
     * @throws ApiException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function delPair(int $uid)
    {
        Auth::adminAuth();
        $pairService = new PairService();
        $pairService->deletePair($uid);
        return response([
            'code' => 200,
            'message' => '成功'
        ]);
    }

    /**
     * 修改某人某期结算结果为不满意状态
     * @param  Request  $request
     * @return array
     * @throws DBException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function upStateToRefund(Request $request)
    {
        Auth::adminAuth();
        $this->validate($request, [
            'uid' => 'required',
            'stage_id' => 'required'
        ]);
        $pair = PairModel::where([
            ['uid', $request->uid],
            ['stage_id', $request->stage_id]
        ])->whereBetween('state', [800, 899])->first();
        if (collect($pair)->isEmpty()) {
            return [
                'code' => 404,
                'message' => '未能自动索引到报名纪录，请联系管理员手动处理'
            ];
        }
        if (PairModel::where('id', $pair->id)->decrement('state', 300)) {
            return [
                'code' => 200,
                'message' => 'success'
            ];
        } else {
            throw new DBException();
        }
    }

    public function enrollInvite(int $stage_id)
    {
        $result = array(
            'total' => [
                0 => [
                    'man' => 0,
                    'women' => 0,
                    'count' => 0
                ]
            ],
            'list' => []
        );
        $datas = \DB::select(
            'SELECT sex, COUNT(*) as c FROM `kdgx_partner_charge_pair` as pair left join `kdgx_partner_charge_fpdx_invite` as invite on pair.`id`= invite.`pair_id` WHERE pair.`stage_id`= ? and `pair_id` IS NULL GROUP BY sex',
            [$stage_id]
        );
        foreach ($datas as $value) {
            if ($value->sex == 1) {
                $result['total'][0]['man'] += $value->c;
                $result['total'][0]['count'] += $value->c;
            } else {
                $result['total'][0]['women'] += $value->c;
                $result['total'][0]['count'] += $value->c;
            }
        }
        $manDatas = \DB::select(
            "SELECT c, COUNT(*) as cnt FROM(SELECT COUNT(*) as c, `pair_id` FROM `kdgx_partner_charge_pair` as pair left join `kdgx_partner_charge_fpdx_invite` as invite on pair.`id`= invite.`pair_id` WHERE invite.`state` != 2 and pair.`stage_id`= ? and pair.sex= ? GROUP BY `pair_id`) as tab where `pair_id` IS NOT NULL GROUP BY c",
            [$stage_id, 1]
        );
        $womenDatas = \DB::select(
            "SELECT c, COUNT(*) as cnt FROM(SELECT COUNT(*) as c, `pair_id` FROM `kdgx_partner_charge_pair` as pair left join `kdgx_partner_charge_fpdx_invite` as invite on pair.`id`= invite.`pair_id` WHERE invite.`state` != 2 and pair.`stage_id`= ? and pair.sex= ? GROUP BY `pair_id`) as tab where `pair_id` IS NOT NULL GROUP BY c",
            [$stage_id, 2]
        );
        foreach ($manDatas as $value) {
            $result['total'][$value->c]['man'] = $value->cnt;
            $result['total'][$value->c]['women'] = 0;
            $result['total'][$value->c]['count'] = $value->cnt;
        }
        foreach ($womenDatas as $value) {
            if (isset($result['total'][$value->c]['count'])) {
                $result['total'][$value->c]['count'] += $value->cnt;
            } else {
                $result['total'][$value->c]['count'] = $value->cnt;
            }
            if (!isset($result['total'][$value->c]['man'])) {
                $result['total'][$value->c]['man'] = 0;
            }
            $result['total'][$value->c]['women'] = $value->cnt;
        }
        for ($j = 0; $j < 12; $j++) {
            for ($i = 1; $i < 4; $i++) {
                $mancount = PairModel::where([
                    ['sex', 1],
                    ['stage_id', $stage_id],
                    ['state', $j * 100 + $i]
                ])->count();
                $womencount = PairModel::where([
                    ['sex', 2],
                    ['stage_id', $stage_id],
                    ['state', $j * 100 + $i]
                ])->count();
                $manDatas = \DB::select(
                    "SELECT c, COUNT(*) as cnt FROM(SELECT COUNT(*) as c, `pair_id` FROM `kdgx_partner_charge_pair` as pair left join `kdgx_partner_charge_fpdx_invite` as invite on pair.`id`= invite.`pair_id` WHERE invite.`state` != 2 and pair.`stage_id`= ? and pair.sex= ? and pair.state = ? GROUP BY `pair_id`) as tab where `pair_id` IS NOT NULL GROUP BY c",
                    [$stage_id, 1, $j * 100 + $i]
                );
                $womenDatas = \DB::select(
                    "SELECT c, COUNT(*) as cnt FROM(SELECT COUNT(*) as c, `pair_id` FROM `kdgx_partner_charge_pair` as pair left join `kdgx_partner_charge_fpdx_invite` as invite on pair.`id`= invite.`pair_id` WHERE invite.`state` != 2 and pair.`stage_id`= ? and pair.sex= ? and pair.state = ? GROUP BY `pair_id`) as tab where `pair_id` IS NOT NULL GROUP BY c",
                    [$stage_id, 2, $j * 100 + $i]
                );
                foreach ($manDatas as $value) {
                    $result['list'][$j * 100 + $i][$value->c]['man'] = $value->cnt;
                    $result['list'][$j * 100 + $i][$value->c]['women'] = 0;
                    $result['list'][$j * 100 + $i][$value->c]['count'] = $value->cnt;
                    $mancount -= $value->cnt;
                }
                foreach ($womenDatas as $value) {
                    if (!isset($result['list'][$j * 100 + $i][$value->c]['man'])) {
                        $result['list'][$j * 100 + $i][$value->c]['man'] = 0;
                    }
                    $result['list'][$j * 100 + $i][$value->c]['women'] = $value->cnt;
                    if (isset($result['list'][$j * 100 + $i][$value->c]['count'])) {
                        $result['list'][$j * 100 + $i][$value->c]['count'] += $value->cnt;
                    } else {
                        $result['list'][$j * 100 + $i][$value->c]['count'] = $value->cnt;
                    }
                    $womencount -= $value->cnt;
                }
                if ($mancount + $womencount > 0) {
                    $result['list'][$j * 100 + $i][0]['man'] = $mancount;
                    $result['list'][$j * 100 + $i][0]['women'] = $womencount;
                    $result['list'][$j * 100 + $i][0]['count'] = $mancount + $womencount;
                }
            }
        }
        return array(
            'code' => 200,
            'message' => 'success',
            'data' => $result
        );
    }

    /**
     * 匹配查询统计
     * @param  int  $stage_id
     * @return array
     * @throws ApiException
     */
    public function pairQuery(int $stage_id)
    {
        $result = array(
            'total' => [
                'all' => [
                    'true' => 0,
                    'false' => 0,
                    'count' => 0
                ],
                'success' => [
                    'true' => 0,
                    'false' => 0,
                    'count' => 0
                ],
                'fail' => [
                    'true' => 0,
                    'false' => 0,
                    'count' => 0
                ]
            ],
            'list' => []
        );
        try {
            $pairs = PairModel::where('stage_id', $stage_id)->get();
            $result['total']['all']['count'] = $pairs->count();
            $result['total']['all']['true'] = $pairs->where('login_time', '>', 0)->count();
            $result['total']['all']['false'] = $result['total']['all']['count'] - $result['total']['all']['true'];
            $succPairs = PairModel::where('stage_id', $stage_id)->whereNull('assoc_id')->get();
            $result['total']['success']['count'] = $succPairs->count();
            $result['total']['success']['true'] = $succPairs->where('login_time', '>', 0)->count();
            $result['total']['success']['false'] = $result['total']['success']['count'] - $result['total']['success']['true'];
            // $failPairs = PairModel::where('stage_id', $stage_id)->whereNotNull('assoc_id')->get();
            $result['total']['fail']['count'] = $succPairs->count();
            $result['total']['fail']['true'] = $succPairs->where('login_time', '>', 0)->count();
            $result['total']['fail']['false'] = $result['total']['fail']['count'] - $result['total']['fail']['true'];
            for ($i = 3; $i <= 12; $i++) {
                for ($j = 1; $j <= 3; $j++) {
                    $result['list'][$i * 100 + $j]['count'] = $pairs->where('state', $i * 100 + $j)->count();
                    $result['list'][$i * 100 + $j]['true'] = $pairs->where('state', $i * 100 + $j)->where(
                        'login_time',
                        '>',
                        0
                    )->count();
                    $result['list'][$i * 100 + $j]['false'] = $result['list'][$i * 100 + $j]['count'] - $result['list'][$i * 100 + $j]['true'];
                }
            }
            return array(
                'code' => 200,
                'message' => 'success',
                'data' => $result
            );
        } catch (\Exception $e) {
            throw new ApiException($e->getFile() . "|" . $e->getLine() . "|" . $e->getMessage(), 501);
        }
    }
}
