<?php

namespace app\mainapp\controller;

use app\common\model\ResumeInvite;
use app\common\model\UserWill;
use app\mainapp\BaseController;

use app\common\model\Param as ParamModel;
use app\common\model\User as UserModel;
use app\common\model\UserAuths as UserAuthsModel;
use app\common\model\UserGroups as UserGroupsModel;
use app\common\model\UserIntegral as UserIntegralModel;
use app\common\model\UserParam as UserParamModel;
use app\common\model\UserPart as UserPartModel;
use app\common\model\UserRank as UserRankModel;
use app\common\model\ComjobsLog as ComjobsLogModel;

use app\common\model\Worker as WorkerModel;
use app\common\model\Agent as AgentModel;
use app\common\model\Broker as BrokerModel;

use app\common\model\ArticleCollect as ArticleCollectModel;

use echowx\WxProgram;

use echowx\WxPay;

class My extends BaseController
{

    // 我的推广码
    public function pageCode()
    {
        $param = ParamModel::where(1)->find();
        $plist = UserRankModel::order('partnumber', 'desc')->limit(100)->select();
        page_result(0, "", [
            'param'  => $param,
            'plist'  => $plist,
            'pcount' => count($plist),
        ]);
    }

    public function refCode()
    {
        $userid    = input('userid/d', 0);
        $wxprogram = new WxProgram();
        $wxampcode = $wxprogram->wxacode_get_unlimited($userid, "pages/login/sharepuser", 430, "attachment/wxampcode/" . md5(time()) . ".jpg");
        if ($wxampcode == false) {
            page_result(1, "小程序码生成失败，请稍后再试。");
        }
        UserModel::update([
            'id'        => $userid,
            'wxampcode' => $wxampcode,
        ]);
        page_result(0, "", [
            'wxampcode' => $wxampcode,
        ]);
    }

    public function regUser()
    {
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        $realname = input('realname/s', "");
        $mobile   = input('mobile/s', "");
        if (empty($realname) || empty($mobile)) {
            page_result(1, "姓名手机号均不能为空。");
        }
        $reguser = WorkerModel::where('mobile', '=', $mobile)->findOrEmpty();
        if (!$reguser->isEmpty()) {
            page_result(1, "该手机号已注册过了。");
        }
        $groups   = UserGroupsModel::order(['isdefault' => 'desc', 'id' => 'asc'])->findOrEmpty();
        $groupsid = $groups->isEmpty() ? 0 : $groups->id;
        $newuser  = new UserModel;
        $newuser->save([
            'groupsid'       => $groupsid,
            'brokerid'       => $user->brokerid,
            'nickname'       => $realname,
            'avatar'         => "",
            'realname'       => $realname,
            'mobile'         => $mobile,
            'password'       => md5(time() . mt_rand(100000, 999999)),
            'integral'       => 0,
            'inttotal'       => 0,
            'status'         => 2,
            'isvip'          => 1,
            'authstatus'     => 1,
            'authremark'     => "",
            'idcardzpic'     => "",
            'idcardfpic'     => "",
            'idcard'         => "",
            'gender'         => 1,
            'birthday'       => "",
            'address'        => "",
            'education'      => "",
            'createtime'     => time(),
            'jobintention'   => "",
            'workexperience' => "",
            'eduexperience'  => "",
            'followstatus'   => 1,
            'wxampcode'      => "",
            'bankcard'       => ['openbank' => "", 'account' => "", 'number' => ""],
        ]);
        $mobileuserauths = new UserAuthsModel;
        $mobileuserauths->save([
            'userid'       => $newuser->id,
            'identitytype' => "mobile",
            'identifier'   => $mobile,
            'password'     => md5(time() . mt_rand(100000, 999999)),
            'logintime'    => time(),
            'loginip'      => $_SERVER['SERVER_ADDR'],
        ]);

        $param = UserParamModel::where(1)->findOrEmpty();
        $part  = new UserPartModel;
        $part->save([
            'puserid'    => $userid,
            'userid'     => $newuser->id,
            'redmoney'   => intval($param->redmoney),
            'status'     => 1,
            'createtime' => time(),
        ]);
        if ($param->postintegral > 0) {
            $integral = new UserIntegralModel;
            $integral->save([
                'userid'      => $user->id,
                'title'       => "推荐注册用户奖励",
                'intvalue'    => $param->postintegral,
                'intmoney'    => 0.00,
                'onlycontent' => "",
                'remark'      => "推荐注册用户【" . $realname . "】奖励聘豆",
                'itype'       => 1,
                'status'      => 2,
                'createtime'  => time(),
                'yeartime'    => date("Y"),
                'monthtime'   => date("Ym"),
            ]);
            $updata = [
                'integral' => $user->integral + $param->postintegral,
                'inttotal' => $user->inttotal + $param->postintegral,
            ];
            $user->save($updata);
        }
        page_result(0, "", []);
    }


    // 获得用户信息
    public function getUser()
    {
        $param  = ParamModel::where(1)->find();
        $userid = input('userid/d');
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        // $user['nickname']  = mb_substr($user['nickname'],0,6,'utf-8').'...';
        $workerall = WorkerModel::where('userid', '=', $user->id)->select();
        $agentall  = AgentModel::where('userid', '=', $user->id)->select();
        $brokerall = BrokerModel::where('userid', '=', $user->id)->select();
        page_result(0, "", [
            'param'     => $param,
            'user'      => $user,
            'workerall' => $workerall->isEmpty() ? null : $workerall,
            'agentall'  => $agentall->isEmpty() ? null : $agentall,
            'brokerall' => $brokerall->isEmpty() ? null : $brokerall,
        ]);
    }


    // 我的职业顾问
    public function getMyBroker()
    {
        $userid = input('userid/d');
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        $agent  = AgentModel::where('id', '=', $user->agentid)->find();
        $broker = BrokerModel::where('id', '=', $user->brokerid)->find();
        page_result(0, "", [
            'agent'  => $agent,
            'broker' => $broker,
        ]);
    }

    // 收藏夹
    public function listCollect()
    {
        $ppage  = input('ppage/d', 1);
        $psize  = input('psize/d', 20);
        $userid = input('userid/d', 0);
        if (empty($userid)) {
            page_result(1, "用户信息不存在");
        }
        $plist = ArticleCollectModel::with('article')->where('userid', '=', $userid)->order(['id' => 'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    public function delCollect()
    {
        $id      = input('id/d', 0);
        $userid  = input('userid/d', 0);
        $collect = ArticleCollectModel::where(['id' => $id, 'userid' => $userid])->findOrEmpty();
        $result  = $collect->delete();
        if ($result) {
            exit(json_encode([
                'code' => 0,
                'msg'  => "",
            ]));
        }
        exit(json_encode([
            'code' => 1,
            'msg'  => "删除失败，请稍后重试",
        ]));
    }

    // 我的邀请
    public function myTeam()
    {
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在。");
        }
        $redmoneyarr = ['status0' => 0, 'status1' => 0, 'status2' => 0, 'status3' => 0];
        $redmoneyall = UserPartModel::field('status, userid, SUM(redmoney) AS redmoneysum')->where('puserid', '=', $userid)->group('status')->select()->toArray();
        if (!empty($redmoneyall)) {
            foreach ($redmoneyall as $k => $v) {
                $redmoneyarr['status' . $v['status']] = intval($v['redmoneysum']);
            }
        }
        $redmoneyarr['status0'] = $redmoneyarr['status2'] + $redmoneyarr['status3'];
        page_result(0, "", [
            'redmoneyarr' => $redmoneyarr,
        ]);
    }

    public function getTeam()
    {
        $ppage  = input('ppage/d', 1);
        $psize  = input('psize/d', 20);
        $userid = input('userid/d', 0);
        if ($userid != 0) {
            $map[] = ['puserid', '=', $userid];
        }
        $status = input('status/d', 0);
        if ($status != 0) {
            $map[] = ['status', '=', $status];
        }
        $plist = UserPartModel::with('user')->where($map)->order(['id' => 'desc'])->page($ppage)->limit($psize)->select();
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    // 我的聘豆
    public function myIntegral()
    {
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在。");
        }
        $monthtime     = date('Ym', strtotime('-1 month'));
        $monthintegral = UserIntegralModel::where(['monthtime' => $monthtime, 'userid' => $userid])->sum('intvalue');
        $userparam     = UserParamModel::where(1)->findOrEmpty();
        page_result(0, "", [
            'user'          => $user,
            'monthintegral' => $monthintegral,
            'userparam'     => $userparam,
        ]);
    }

    public function getRecharge()
    {
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在。");
        }
        $userauths = UserAuthsModel::where(['userid' => $userid, 'identitytype' => "weixin"])->findOrEmpty();
        if ($userauths->isEmpty()) {
            page_result(1, "请先授权微信号登录。");
        }
        $userparam = UserParamModel::where(1)->findOrEmpty();
        if ($userparam->isEmpty() || $userparam->intrecharge <= 0) {
            page_result(1, "禁止用户充值。");
        }
        $moneyvalue = input('moneyvalue/f', 0.00);
        $intvalue   = intval($moneyvalue * $userparam->intrecharge);
        if ($moneyvalue <= 0.00 || $intvalue <= 0) {
            page_result(1, "充值聘豆额不能小于0。");
        }
        $integral = new UserIntegralModel;
        $integral->save([
            'userid'      => $userid,
            'title'       => "用户聘豆充值（￥" . $moneyvalue . "元" . $intvalue . "聘豆）",
            'intvalue'    => $intvalue,
            'intmoney'    => $moneyvalue,
            'onlycontent' => "",
            'remark'      => "R" . date("YmdHis") . mt_rand(100000, 999999),
            'itype'       => 2,
            'status'      => 1,
            'createtime'  => time(),
            'yeartime'    => date('Y'),
            'monthtime'   => date('Ym'),
        ]);
        $payData = [
            'body'         => "用户聘豆充值（￥" . $moneyvalue . "元" . $intvalue . "聘豆）",
            'out_trade_no' => $integral->remark,
            'total_fee'    => intval($moneyvalue * 100),
            'openid'       => $userauths->identifier,
        ];
        $wxpay   = new WxPay();
        $info    = $wxpay->wxpay_unified_order($payData);
        if ($info['status'] == 1) {
            $payinfo = $wxpay->get_jsapi_param($info['data']['prepay_id']);
            page_result(0, "", ['payinfo' => $payinfo]);
        } else {
            page_result(1, $info['data']);
        }
    }

    public function getMoney()
    {
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在。");
        }
        $bankcard = $user->bankcard;
        if (empty($bankcard) || empty($bankcard['number'])) {
            page_result(1, "请先完善个人银行卡信息。");
        }
        $oldintegral = UserIntegralModel::where(['userid' => $userid, 'itype' => 3, 'status' => 1])->findOrEmpty();
        if (!$oldintegral->isEmpty()) {
            page_result(1, "你已存在未处理的兑现申请，请耐心等待客服处理，处理完成后方可再次提交兑现申请。");
        }
        $userparam = UserParamModel::where(1)->findOrEmpty();
        if ($userparam->isEmpty() || $userparam->inttomoney <= 0) {
            page_result(1, "禁止用户提现。");
        }
        $intvalue = input('intvalue/d', 0);
        if ($intvalue <= 0 || $intvalue < intval($userparam->minintegral)) {
            page_result(1, "兑现聘豆值要大于" . $userparam->minintegral . "。");
        }
        if ($intvalue > intval($user->integral)) {
            page_result(1, "兑现聘豆值不能大于当前可用聘豆。");
        }
        $integral = new UserIntegralModel;
        $intmoney = sprintf("%.2f", floatval($intvalue / $userparam->inttomoney));
        $integral->save([
            'userid'      => $userid,
            'title'       => "用户聘豆兑现",
            'intvalue'    => 0 - $intvalue,
            'intmoney'    => $intmoney,
            'onlycontent' => "",
            'remark'      => "用户聘豆兑现现金",
            'itype'       => 3,
            'status'      => 1,
            'createtime'  => time(),
            'yeartime'    => date('Y'),
            'monthtime'   => date('Ym'),
        ]);
        $hasintegral = intval($user->integral) - $intvalue;
        $user->save([
            'integral' => $hasintegral,
        ]);
        page_result(0, "", [
            'user' => $user,
        ]);
    }

    public function getIntegral()
    {
        $ppage  = input('ppage/d', 1);
        $psize  = input('psize/d', 20);
        $userid = input('userid/d', 0);
        if ($userid != 0) {
            $map[] = ['userid', '=', $userid];
        }
        $plist = UserIntegralModel::where($map)->order(['id' => 'desc'])->page($ppage)->limit($psize)->select()->append(['itype_text', 'status_text']);
        page_result(0, "", [
            'plist'   => $plist,
            'pstatus' => $psize > count($plist) ? 'noMore' : 'more',
        ]);
    }

    // 银行卡信息
    public function editUserBankinfo()
    {
        $userid = input('userid/d', 0);
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        $openbank = input('openbank/s', "");
        $account  = input('account/s', "");
        $number   = input('number/s', "");
        $bankcard = [
            'openbank' => $openbank,
            'account'  => $account,
            'number'   => $number,
        ];
        $user->save(['bankcard' => $bankcard]);
        page_result(0, "", $user);
    }


    // 个人信息
    public function editUserInfo()
    {
        $userid = input('userid/d');
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        $field       = input('field/s');
        $value       = input('value');
        $field_array = ['emp_time', 'com_cate'];
        if (in_array($field, $field_array)) {
            $value = json_decode($value, true);
        }
        $user->$field = $value;
        $user->save();
        page_result(0, "", $user);
    }

    // 身份证认证
    public function editIdCard()
    {
        $userid = input('userid/d');
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }

        $data = input('data');
        if (is_string($data)) {
            $data = json_decode($data, true);
        }
        $fileds = ['nickname', 'idcard', 'gender', 'birthday'];
        foreach ($data as $k => $v) {
            if (in_array($k, $fileds)) {
                $user->$k = $v;
            }
        }
        $user->save();
        page_result(0, "", $user);
    }

    // 提交实名认证审核
    public function setAuthStatus()
    {
        $userid = input('userid/d');
        $user   = UserModel::findOrEmpty($userid);
        if ($user->isEmpty()) {
            page_result(1, "用户信息不存在");
        }
        if (empty($user->idcardzpic)) {
            page_result(1, "请上传上传身份证（头像页）照。");
        }
        if (empty($user->idcardfpic)) {
            page_result(1, "请上传上传身份证（国徽页）照。");
        }
        if (empty($user->idcard)) {
            page_result(1, "请填写身份证号。");
        }
        if (isIdCard($user->idcard) == false) {
            page_result(1, "请填写正确的身份证号。");
        }
        if (empty($user->realname)) {
            page_result(1, "请填写姓名。");
        }
        $user->save([
            'authstatus' => 2,
            'gender'     => get_sex($user->idcard),
            'birthday'   => get_birthday($user->idcard),
        ]);
        page_result(0, "", $user);
    }


    public function jobintention_lst()
    {

        $plist = UserWill::select();
        page_result(0, "", [
            'plist' => $plist,
        ]);
    }

    public function getauthimg()
    {
        $image_url = "https://" . $_SERVER['SERVER_NAME'];
        $head1     = $image_url . "/static/images/head1.png";
        $head2     = $image_url . "/static/images/head2.png";
        page_result(0, "", [
            'head1' => $head1,
            'head2' => $head2,
        ]);
    }

    public function gettipnum()
    {
        $userid = input('userid/d');

        $comjobs_num = ComjobsLogModel::where('userid', $userid)->whereIn('status', [2, 3, 4])->count();
        $invite_num  = ResumeInvite::where('userid', $userid)->where('status', 1)->count();
        page_result(0, "", [
            'comjobs_num' => $comjobs_num,
            'invite_num'  => $invite_num,
        ]);
    }
}