<?php

namespace App\Http\Controllers\Fpdx;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Core\Ding;
use App\Http\Controllers\Controller;
use App\Models\Fpdx\ActivityModel;
use App\Models\Fpdx\MediaModel;
use App\Models\Fpdx\PairModel;
use App\Models\Fpdx\MediaNotiveModel;
use App\Models\Fpdx\MediaOrderModel;

class Media extends Controller
{
    private $model;

    public function __construct()
    {
        $this->model = new MediaModel();
    }

    /**
     * @param  Request  $request
     * @return array
     */
    public function createLink(Request $request)
    {
        $data = array(
            'public_name' => $request->post('public_name'),
            'attach' => json_encode($request->toArray())
        );
        $data['media_id'] = "kd_" . bin2hex(\openssl_random_pseudo_bytes(6));
        $media = $this->model->fill($data);
        if ($media->save()) {
            Redis::lpush("{pair_hides}", $data['media_id']);
            return [
                'code' => 200,
                'message' => 'success',
                'data' => $media
            ];
        } else {
            return [
                'code' => 500,
                'message' => 'fail',
            ];
        }
    }

    /**
     * 自动结算任务
     * @param  int  $stage_id
     */
    public static function autoCpAccount(int $stage_id = 0)
    {
        if ($stage_id == 0) {
            $activitys = ActivityModel::getActivitys();
            $stage_id = $activitys['last'];
        }
        PairModel::where('stage_id', $stage_id)->whereIn('state', [401, 402, 403, 404])->increment('state', 400);
        $pairs = PairModel::where(array(
            ['stage_id', $stage_id],
            ['fx_money', '=', 0]
        ))->where("completed_at", 0)->whereBetween('state', [100, 899])->get();
        foreach ($pairs as $pair) {
            $pair->completed_at = time();
            $pair->save();

            $media = new Media();
            if (
                in_array($pair->media_id, [
                    'kd_b598cb7474d8',
                    'kd_5edc93aa148e',
                    'gh_01c089b58dda',
                    'gh_c94c95866ca5',
                    'gh_5edc93aa148e',
                    'gh_b598cb7474d8'
                ])
                || strpos("#" . $pair->media_id, 'gh_') != 1
            ) {
                $media->kolFenxiao($pair->id);
            } else {
                $media->cpFenxiao($pair->id);
            }
        }
        Ding::robot([
            'title' => '活动分销提醒',
            'text' => "分配对象第「{$stage_id}」期结算任务完成"
        ]);
    }

    /**
     * 分配对象分销
     * @param  int pair_id 匹配报名的id
     * @return void
     */
    public function cpFenxiao(int $pair_id)
    {
        $pair = PairModel::find($pair_id);
        if (collect($pair)->isEmpty()) {
            return;
        }
        if ($pair->state > 800 && $pair->state < 899) {
            if ($pair->sex == 2) {
                $pair->fx_money = 3.5;
            } else {
                $pair->fx_money = 2.5;
            }
        } else {
            $pair->fx_money = 0.5;
        }
        if ($pair->save()) {
            $this->fenxiao($pair->media_id, $pair->fx_money, $column = 'fpdx_money');
            MediaOrderModel::create([
                'media_id' => $pair->media_id,
                'type' => 'income',
                'amount' => $pair->fx_money * 100,
                'tag' => '分配对象',
                'describe' => "分配对象活动第{$pair->stage_id}期结算（订单ID：{$pair->order_id}）"
            ]);
        }
    }

    /**
     * kol分销
     * @param  int  $pair_id  匹配报名id
     * @return void
     */
    public function kolFenxiao(int $pair_id)
    {
        $pair = PairModel::find($pair_id);
        if (collect($pair)->isEmpty()) {
            return;
        }
        if ($pair->state > 800 && $pair->state < 899) {
            $pair->fx_money = $pair->pay;
        } else {
            $pair->fx_money = 0;
        }
        if ($pair->save()) {
            $this->fenxiao($pair->media_id, $pair->fx_money, $column = 'fpdx_money');
            if ($pair->fx_money > 0) {
                MediaOrderModel::create([
                    'media_id' => $pair->media_id,
                    'type' => 'income',
                    'amount' => $pair->fx_money * 100,
                    'tag' => '分配对象',
                    'describe' => "分配对象活动第{$pair->stage_id}期结算（订单ID：{$pair->order_id}）"
                ]);
            }
        }
    }

    /**
     * 公众号分销，增加账户收入
     * @param  string  $media_id
     * @param  float money
     * @param  string  $column
     * @return void
     */
    private function fenxiao(string $media_id, float $money, $column = 'gold_flower')
    {
        $media = $this->model->where('media_id', $media_id)->first();
        if (collect($media)->isEmpty()) {
            $media = $this->model->fill([
                'media_id' => $media_id,
                $column => $money
            ]);
            $media->save();
        } else {
            $this->model->where('media_id', $media_id)->increment($column, $money);
        }
        return;
    }

    /**
     * 广播通知
     * @param  Request  $request
     * @return array
     */
    public function broadcastNotive(Request $request)
    {
        $medias = $this->model->where()->pluck('media_id');
        array_map(function ($media_id) use ($request, &$datas) {
            array_push($datas, [
                'created_at' => time(),
                'media_id' => $media_id,
                'content' => $request->input('content'),
                'type' => 1
            ]);
            if (count($datas) > 100) {
                \DB::table('kdgx_fpdx_media_notive')->insert($datas);
                $datas = array();
            }
        }, $medias);
        return [
            'code' => 200,
            'message' => 'success'
        ];
    }

    /**
     * 获取未读消息数
     * @param  string  $media_id  公众号id
     * @return array [
     *      'code' => 200,
     *      'message' => 'success',
     *      'data' => [
     *          'count' => 未读消息数量,
     *          'list' => [
     *              'id' => 消息id,
     *              'created_at' => 创建时间,
     *              'content' => 内容,
     *              'read_at' => 阅读时间,
     *              'type' => 消息类型
     *          ],
     *      ],
     * ]
     */
    public function unread($media_id)
    {
        $datas = MediaNotiveModel::where('media_id', $media_id)->whereNull('read_at')->get([
            'id',
            'created_at',
            'content',
            'read_at',
            'type'
        ]);
        return [
            'code' => 200,
            'message' => 'success',
            'data' => [
                'count' => $datas->count(),
                'list' => $datas
            ],
        ];
    }

    /**
     * 获取消息列表
     * @param  string  $media_id  公众号id
     * @param  int page 页数？
     * @return array [
     *      'code' => 200,
     *      'message' => 'success',
     *      'data' => [
     *          'page' => [
     *              'count' => 总数,
     *              'limit' => 每页数量
     *          ],
     *          'list' => [
     *              'id' => 消息id,
     *              'created_at' => 创建时间,
     *              'content' => 内容,
     *              'read_at' => 阅读时间,
     *              'type' => 消息类型
     *          ],
     *      ],
     * ]
     */
    public function notivelist($media_id, $page = 1)
    {
        $count = MediaNotiveModel::where('media_id', $media_id)->count();
        $datas = MediaNotiveModel::where('media_id', $media_id)->skip(($page - 1) * 20)->take(20)->get([
            'id',
            'created_at',
            'content',
            'read_at',
            'type'
        ]);
        return [
            'code' => 200,
            'message' => 'success',
            'data' => [
                'page' => [
                    'count' => $count,
                    'limit' => 20,
                ],
                'list' => $datas
            ],
        ];
    }

    /**
     * 阅读通知
     * @param  int  $notive_id
     * @return array
     */
    public function readNotive(int $notive_id)
    {
        $notive = MediaNotiveModel::find($notive_id);
        $notive->read_at = time();
        $notive->save();
        return [
            'code' => 200,
            'message' => 'success'
        ];
    }

    /**
     * 获取分配对象收益明细
     * @param  Request  $request
     * @param  string  $media_id  公众号id
     * @return array [
     *      'code' => 200,
     *      'message' => 'success',
     *      'data' => [
     *          'total' => [
     *              'count' => 累计报名人数,
     *              'fx_money' => 累计收益,
     *              'expect_money' => 预期收益
     *          ],
     *          'data' => [
     *              [
     *                  'uid' => 用户id,
     *                  'stage_id' =>  期数,
     *                  'sex' => 性别,
     *                  'create_time' => 报名时间,
     *                  'fx_money' => 本次收益,
     *                  'state' => 结算状态,
     *                  'user' => [
     *                      'uid' => 用户id,
     *                      'nickanem' => '用户昵称'
     *                  ],
     *              ],
     *          ],
     *      ],
     * ]
     */
    public function fxIncome(Request $request, string $media_id)
    {
        $page = $request->page;
        $pairModel = new PairModel();
        $datas = $pairModel->fxIncome($media_id);
        $total = array(
            'count' => $datas->count(),
            'fx_money' => $datas->sum('fx_money'),
            'expect_money' => $datas->where('sex', 1)->filter(function ($item) {
                    return $item->state > 100 && $item->state < 299;
            })->count() * 2.5 + $datas->where('sex', 2)->filter(function ($item) {
                return $item->state > 100 && $item->state < 299;
            })->count() * 3.5
        );
        $pages = array(
            'count' => $datas->count(),
            'limit' => 40,
            'page' => $page
        );
        $tmp = $datas->slice(($page - 1) * $pages['limit'])->take($pages['limit']);
        $list = array();
        $tmp->each(function ($item, $key) use (&$list) {
            array_push($list, $item);
        });
        return [
            'code' => 200,
            'message' => 'success',
            'data' => [
                'total' => $total,
                'pages' => $pages,
                'list' => $list
            ],
        ];
    }

    /**
     * fpdx公众号收益总计
     * @param  string  $media_id  公众号id
     * @return array [
     *      'code' => 200,
     *      'message' => 'success',
     *      'data' => [
     *           'count' => 累计报名人数,
     *           'fx_money' => 累计收益,
     *           'expect_money' => 预期收益
     *      ],
     * ]
     */
    public function fpdxIncome(string $media_id)
    {
        $pairModel = new PairModel();
        $datas = $pairModel->fxIncome($media_id);
        $data = array(
            'count' => $datas->count(),
            'fx_money' => $datas->sum('fx_money'),
        );
        $res = MediaModel::where("media_id", $media_id)->first(['fpdx_money']);
        $data['fpdx_money'] = $res->fpdx_money;
        $activitys = ActivityModel::getActivitys();
        $datas = $pairModel->fxrank($activitys['next']);
        $rank = 0;
        foreach ($datas as $value) {
            $rank++;
            if ($value->media_id == $media_id) {
                break;
            }
        }
        $data['rank'] = $rank;
        return [
            'code' => 200,
            'message' => 'success',
            'data' => $data
        ];
    }

    /**
     * msy公众号收益总计
     * @param  string  $media_id  公众号id
     * @return array [
     *      'code' => 200,
     *      'message' => 'success',
     *      'data' => [
     *           'count' => 累计消费笔数,
     *           'fx_money' => 累计收益,
     *           'today_count' => 今日笔数
     *      ],
     * ]
     */
    public function msyIncome(string $media_id)
    {
        $data = $this->model->incomeData($media_id);
        return [
            'code' => 200,
            'message' => 'success',
            'data' => $data
        ];
    }

    /**
     * @param  string  $media_id
     * @return array
     */
    public function isOpen(string $media_id)
    {
        $wx_fpdx = $this->model->isOpen($media_id, 'fpdx', 'weixiao');
        $kd_fpdx = $this->model->isOpen($media_id, 'fpdx', 'koudai');

        $wx_msy = $this->model->isOpen($media_id, 'msy', 'weixiao');
        $kd_msy = $this->model->isOpen($media_id, 'msy', 'koudai');
        return [
            'code' => 200,
            'message' => 'successs',
            'data' => [
                'fpdx' => [
                    'isopen' => $wx_fpdx || $kd_fpdx
                ],
                'msy' => [
                    'isopen' => $wx_msy || $kd_msy
                ],
            ],
        ];
    }

    /**
     * @param  Request  $request
     * @param  string  $media_id  公众号id
     * @return array
     * [
     *      "code" => 200,
     *      'message' => 'success',
     *      'data' => [
     *
     *      ]
     * ]
     * @throws \ApiException
     */
    public function info(Request $request, string $media_id)
    {
        $app = $request->get('app');
        $data = $this->model->mediaInfo($media_id, $app);
        return [
            'code' => 200,
            'message' => 'success',
            'data' => $data
        ];
    }
}
