<?php
namespace app\mainapp\controller;

use app\common\model\Config;
use app\common\model\OutRecruitReport;
use app\common\model\UserGetmoneyLog;
use app\mainapp\BaseController;
use app\common\model\OutCode as OutCodeModel;
use app\common\model\Broker as BrokerModel;
use app\common\model\UserAuths as UserAuthsModel;
use app\common\model\OutRecruit as OutRecruitModel;
use app\common\model\UserParam as UserParamModel;
use app\mainapp\validate\WorkerReportValidate;
use payment\wechat\WechatTransfers;
use think\exception\ValidateException;
use think\facade\Log;

class Outactivity extends BaseController
{

    public function checkCode()
    {
        $code = input('code/s','');
        if (empty($code)) {
            page_result(1, "该二维码已失效");
        }

        $info = OutCodeModel::where('code',$code)->find();
        if (empty($info)) {
            page_result(1, "该二维码已失效");
        }
        if ($info['status'] == 1) {
            page_result(1, "该二维码已被使用");
        }

        page_result(0);
    }

    public function listrecruit()
    {
        $ppage     = input('ppage/d', 1);
        $psize     = input('psize/d', 20);
        $map = [
            ['status', '=', 1]
        ];
        $orderby = ['priority' => 'desc', 'id' => 'desc'];
        $plist   = OutRecruitModel::where($map)->order($orderby)->page($ppage)->limit($psize)->select();

        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    public function detailrecruit()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            page_result(1,'招聘不存在');
        }

        $info = OutRecruitModel::find($id);
        if (empty($info) || $info['status'] != 1) {
            page_result(1,'该信息不存在或已下架');
        }

        page_result(0,'',$info);
    }

    public function apply()
    {
        $data  = input('param.');
        try {
            validate(WorkerReportValidate::class)->check($data);
        } catch (ValidateException $e) {
            page_result(1, $e->getError());
        }

        //报备记录
        $report = OutRecruitReport::with(['broker'])->where('mobile', $data['mobile'])->where('recruit_id', $data['recruit_id'])->find();
        $report && page_result(1, '请不要重复提交，等待对方联系');

        //添加报备信息
        $data['brokerid'] = Config::getConfigValue('default_broker');
        $broker = BrokerModel::find($data['brokerid']);

        $data['workerid']   = $broker['workerid'];
        $data['agentid']    = $broker['agentid'];
        $data['createtime'] = time();
        OutRecruitReport::create($data);

        page_result(0);
    }

    public function getmoney()
    {
        $code  = input('code/s', '');
        $userid = input('userid/d', 0);

        $info = OutCodeModel::where('code',$code)->find();
        if (empty($info)) {
            page_result(1, "该二维码已失效");
        }
        if ($info['status'] == 1) {
            page_result(1, "该二维码已被使用");
        }

        //获取金额
        $param = UserParamModel::where(1)->findOrEmpty();
        if (empty($param['out_getmoney'])) {
            page_result(1,'活动有误，请联系管理员确认！');
        }
        $money = $this->probabilityPick($param['out_getmoney']);

        //提现
        $batch_name   = '晋江人力小程序用户提现';//转账的名称
        $out_trade_no = 'outa' . getUniId();//单号
        $openid       = UserAuthsModel::where('userid', $userid)->where('identitytype', 'weixin')->value('identifier');//用户openid
        if (empty($openid)) {
            page_result(1, "登录信息有误，请重新登录");
        }
        $detail       = [];
        $transfers    = new WechatTransfers();
        $detail[]     = $transfers->getDetailList($out_trade_no, $money, $batch_name, $openid);
        $res          = $transfers->transfers($batch_name, $detail);
        Log::record('用户提现：' . json_encode($res));

        //记录
        if (!empty($res['batch_id'])) {
            UserGetmoneyLog::create([
                'userid'       => $userid,
                'out_trade_no' => $out_trade_no,
                'money'        => $money,
                'remark'       => '招聘广告宣传奖励提现',
                'createtime'   => time(),
            ]);

            //更改二维码状态
            $info->status = 1;
            $info->use_time = time();
            $info->userid = $userid;
            $info->money = $money;
            $info->save();

            page_result(0, "恭喜您，获得现金奖励{$money}元。已直接发放至微信零钱，请注意查收！",['money'=>$money]);
        } else {
            page_result(1,'活动有误，请联系管理员确认！');
        }
    }

    private function probabilityPick($data) {
        //计算概率总和
        $total = 0;
        foreach ($data as $k => $v) {
            $data[$k]['odds'] *= 100;
            $total += $data[$k]['odds'];
        }
        $random = mt_rand(1, $total);
        $current = 0;
        $count = count($data);

        for ($i = 0; $i < $count; $i++) {
            $current += $data[$i]['odds']; // 累计当前概率
            if ($random <= $current) {
                return $data[$i]['money']; // 如果随机数在当前概率范围内，返回索引
            }
        }
    }
}