<?php

namespace App\Services\App;

use App\Http\Controllers\Miniprogram\Core;
use App\Http\Controllers\Wechat\Media;
use App\Models\Common\MediaModel;
use App\Models\Fpdx\WxkfModel;
use App\Models\User\UserModel;
use App\Services\Service;
use Illuminate\Support\Facades\Cache;

/**
 * Class KfService
 * @package App\Services\App
 */
class KfService extends Service
{

    /**
     * 获取小程序客服资源
     * @param  string  $key
     * @return bool|string
     */
    public function getMedia(string $key)
    {
        $public_id = config('miniprogram.public_id');
        $mm = new MediaModel();
        $km = $mm->where([['key', $key], ['public_id', $public_id]])->first();
        if (collect($km)->isEmpty()) {
            return false;
        }
        if (time() - $km->toArray()['updated_at'] > 86400) {
            $resp = Media::uploadImg($km->url, $km->public_id);
            if ($resp['code'] == 0) {
                $km->fill([
                    'updated_at' => time(),
                    'value' => $resp['data']['media_id'],
                ]);
                $km->save();

                return $resp['data']['media_id'];
            } else {
                return false;
            }
        } else {
            return $km->value;
        }
    }

    /**
     * @param  string  $key
     * @return bool|mixed
     */
    public function getOriginMedia(string $key)
    {
        $public_id = config('miniprogram.public_id');
        $mm = new MediaModel();
        $km = $mm->where([['key', $key], ['public_id', $public_id]])->first();
        if (collect($km)->isEmpty()) {
            return false;
        }

        return $km->url;
    }

    /**
     * hash映射活动微信客服
     * @param $uid
     * @return string
     */
    public function hashWxkf($uid)
    {
        $user = UserModel::findOrFail($uid);
        $wxm = new WxkfModel();
        if (!empty($user->wxkf)) {
            $wxkf = $wxm->where('wxid', $user->wxkf)->first();
            if (collect($wxkf)->isEmpty()) {
                return false;
            }
            if ("活动" == $wxkf->type && $wxkf->state == 1) {
                return $user->wxkf;
            } else {
                return false;
            }
        }
        $tmps = array();
        $wxs = $wxm->where(array(
            ['state', 1],
            ['sex', '!=', abs($user->sex - 3)],
            ['hour_queue_cnt', '>', 0],
            ['type', '活动'],
        ))->get();
        foreach ($wxs as $wx) {
            if ($wx->friend_cnt > 5000) {
                continue;
            }
            if ($wx->today_cnt >= $wx->day_limit) {
                continue;
            }
            if ($wx->today_add_cnt >= $wx->day_add_limit) {
                continue;
            }
            $tmps[] = array(
                'wxid' => $wx->wxid,
            );
        }
        if (count($tmps) == 0) {
            return false;
        }
        $key = $uid % count($tmps);
        $user->wxkf = $tmps[$key]['wxid'];
        $wxm->where('wxid', $user->wxkf)->increment('today_cnt', 1);
        $wxm->where('wxid', $user->wxkf)->decrement('hour_queue_cnt', 1);
        if ($user->save()) {
            return $user->wxkf;
        } else {
            return false;
        }
    }

    /**
     * hash映射微信审核专员
     * @param $uid
     * @return string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function hashWxshzy($uid)
    {
        $user = UserModel::findOrFail($uid);
        $wxm = new WxkfModel();
        if (!empty($user->wxkf)) {
            $wxkf = $wxm->where('wxid', $user->wxkf)->first();
            if ($wxkf->state == 1 && $wxkf->type == "审核") {
                return $user->wxkf;
            }
        }
        $tmps = array();
        $wxs = $wxm->where(array(
            ['state', 1],
            ['sex', '!=', abs($user->sex - 3)],
            ['type', '审核'],
        ))->get();

        list($two, $three, $four, $five) = array("✅", "✅", "✅", "✅");
        foreach ($wxs as $wx) {
            if ($wx->hour_queue_cnt <= 0) {
                $two = "❌";
                continue;
            }
            $two = "✅";
            if ($wx->today_cnt >= $wx->day_limit) {
                $three = "❌";
                continue;
            }
            $three = "✅";
            if ($wx->today_add_cnt >= $wx->day_add_limit) {
                $four = "❌";
                continue;
            }
            $four = "✅";
            if ($wx->friend_cnt > 5000) {
                $five = "❌";
                continue;
            }
            $five = "✅";
            $tmps[] = array(
                'wxid' => $wx->wxid,
            );
        }
        if (count($tmps) == 0) {
            try {
                $ispush = true;
                Cache::put("hashwxshzy:{$user->sex}", true);
                if ($ispush) {
                    $one = $wxm->where(array(
                        ['state', 1],
                        ['sex', '!=', abs($user->sex - 3)],
                        ['type', '审核'],
                    ))->exists() ? "✅" : "❌";
                    $admins = array(10002, 98047, 103143);
                    foreach ($admins as $admin) {
                        $public_id = \config('wechat.fpdx.public_id');
                        $template_id = "ugxHaIxl5sFf2T00QZdCc0l4qELRUfEtw1HnCE7PDww";
                        $data = [
                            'first' => [
                                'value' => "警告⚠️审核专员异常\n 请按照以下步骤排查：\n\n 【男】号【女】号都存在，且处于【上线】状态，并且功能都为【审核】  {$one}\n",
                            ],
                            'keyword1' => [
                                'value' => "「小时发码上限」小于 0  {$two}\n",
                            ],
                            'keyword2' => [
                                'value' => "「今日发码数」不大于「每日发码上限」{$three}\n",
                            ],
                            'keyword3' => [
                                'value' => "「今日好友数」不大于「每日添加好友上限」{$four}\n",
                            ],
                            'keyword4' => [
                                'value' => "「好友总数」小于 5000 {$five}\n",
                            ],
                            'remark' => [
                                'value' => " 联系开发人员",
                                "color" => "#FF7E98",
                            ],
                        ];
                        $core = new Core();
                        $core->template($admin, $template_id, $public_id, "", $data);
                    }
                }
            } catch (\Exception $exception) {
            }

            return false;
        }
        if (Cache::get("hashwxshzy:{$user->sex}")) {
            Cache::delete("hashwxshzy:{$user->sex}");
            try {
                $admins = array(10002, 98047, 795723, 103143);
                foreach ($admins as $admin) {
                    $public_id = \config('wechat.fpdx.public_id');
                    $template_id = "ugxHaIxl5sFf2T00QZdCc0l4qELRUfEtw1HnCE7PDww";
                    $sex = $user->sex == 1 ? "男" : "女";
                    $data = [
                        'first' => [
                            'value' => "✅「{$sex}」审核专员恢复正常",
                        ],
                        'keyword1' => [
                            'value' => "",
                        ],
                        'keyword2' => [
                            'value' => "",
                        ],
                        'keyword3' => [
                            'value' => "",
                        ],
                        'keyword4' => [
                            'value' => "",
                        ],
                        'remark' => [
                            'value' => "",
                            "color" => "#FF7E98",
                        ],
                    ];
                    $core = new Core();
                    $core->template($admin, $template_id, $public_id, "", $data);
                }
            } catch (\Exception $exception) {
            }
        }
        $key = $uid % count($tmps);
        $user->wxkf = $tmps[$key]['wxid'];
        $wxm->where('wxid', $user->wxkf)->increment('today_cnt', 1);
        $wxm->where('wxid', $user->wxkf)->decrement('hour_queue_cnt', 1);

        return $tmps[$key]['wxid'];
    }

    /**
     * 清理并记录每日数据
     * @return boolean
     */
    public function clearWxkf()
    {
        try {
            $wxkfmodel = new WxkfModel();
            $wxkfs = $wxkfmodel->get();
            $data = array();
            foreach ($wxkfs as $wxkf) {
                $data[] = array(
                    'date' => date('Y-m-d'),
                    'wxid' => $wxkf->wxid,
                    'today_cnt' => $wxkf->today_cnt,
                    'today_add_cnt' => $wxkf->today_add_cnt,
                    'replay_cnt' => $wxkf->replay_cnt,
                );
            }
            \DB::table('kdgx_fpdx_wxkf_log')->insert($data);
        } catch (\Exception $e) {
        }
        \DB::table('kdgx_fpdx_wxkf')->update(['today_cnt' => 0, 'today_add_cnt' => 0, 'replay_cnt' => 0]);

        return true;
    }

    /**
     * 清理每小时数据
     * @return boolean
     */
    public function wxkfHourQueue()
    {
        \DB::table('kdgx_fpdx_wxkf')->where('type', '活动')->update(['hour_queue_cnt' => 50]);
        \DB::table('kdgx_fpdx_wxkf')->where('type', '审核')->update(['hour_queue_cnt' => 200]);

        return true;
    }
}
