<?php
/**
 * 用户ajax请求处理
 */

include '../includes/fun.global.php';
include_once(SYSTEM_ROOT . "fun.admin.php");
@header('Content-Type: application/json; charset=UTF-8');
$USERDATA = login_data::user_data();
switch ($_QET['act']) {
    case 'prevent':
        if ($conf['userdomaintype'] == 1) {
            $url = is_https(false) . $USERDATA['domain'];
        } else $url = is_https(false) . href() . '?t=' . $USERDATA['domain'];
        if ($conf['prevent_switch'] == 1) {
            dies(1, reward::prevent($url, 2));
        } else dies(1, $url);
        break;
    case 'user_pay':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (empty((float)$_QET['money']) || empty($_QET['type'])) dies(-1, '请提交完整哦!');
        $data_arr = reward::user_payet($_QET['money'], $_QET['type'], $USERDATA);
        die($data_arr);
        break;
    case 'add_token': #生成
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        $token = md5($USERDATA['token'] . rand(10000, 9999999999) . time());
        $a = $DB->query("UPDATE `sky_user` SET `token`='$token' WHERE  (`id`='{$USERDATA['id']}')");
        if ($a) {
            die(json_encode(['code' => 1, 'msg' => 'token更新成功', 'token' => $token]));
        } else dies(-1, 'token更新失败');
        break;
    case 'ip_data':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (empty($_QET['ip_data'])) dies(-1, '请填写完整');
        $Ip = implode('|', $_QET['ip_data']);
        $a = $DB->query("UPDATE `sky_user` SET `ip_white_list`='$Ip' WHERE  (`id`='{$USERDATA['id']}')");
        if ($a) {
            die(json_encode(['code' => 1, 'msg' => '设置成功', 'ip_data' => $Ip]));
        } else dies(-1, '设置失败');
        break;
    case 'user_updating':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        header("Content-Type:text/html;charset=utf8");
        echo login_data::user_reception($_QET);
        break;
    case 'connected':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        die(login_data::login('/user/ajax.php?act=user_updating'));
        break;
    case 'Send_verification_code':
        $num = $conf['usersmsbinding'];
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (empty((int)$_QET['mobile'])) dies(-1, '请将手机号填写完整！');
        $count = $DB->count("SELECT count(*) FROM `sky_journal` WHERE `name` = '短信验证' AND `date` > '$times' AND `uid` = '{$USERDATA['id']}'  "); //今日发信次数
        if ($count >= $num) dies(-1, '今日短信验证次数已经耗尽,每日仅可发送' . $num . '次验证码！');
        if ($USERDATA['mobile'] == $_QET['mobile']) dies(-1, '新手机号不能和旧的相同！');
        $vr = $DB->get_row("SELECT * FROM `sky_user` WHERE `mobile` = '{$_QET['mobile']}' AND `id`!='{$_QET['id']}' ");
        if ($vr) dies(-1, '此手机号已被用户：' . $vr['id'] . '绑定！');
        $sms = new \sms\sms_operation(href(), $accredit['token'], 1);
        $_SESSION['VerifyCode'] = $sms->randString();
        $_SESSION['Mobile'] = (int)$_QET['mobile'];
        $arr = $sms->sum_send($_SESSION['VerifyCode'], $_SESSION['Mobile']);
        if ($arr['code'] == 1) {
            userlog('短信验证', '用户于' . $date . ' 为绑定手机号[' . $_SESSION['Mobile'] . '] 发送了短信验证码!', $USERDATA['id']);
            dier($arr);
        } else dier($arr);
        break;
    case 'Send_verification':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if (empty($_SESSION['VerifyCode']) || empty($_SESSION['Mobile'])) dies(-1, '请先发送验证码！');
        if (empty((int)$_QET['code'])) dies(-1, '请填写完整！');
        if ((int)$_SESSION['VerifyCode'] <> (int)$_QET['code']) dies(-2, '验证码有误,请核对后再输入！');
        $re = $DB->query("UPDATE `sky_user` SET `mobile`='{$_SESSION['Mobile']}' WHERE (`id`='{$USERDATA['id']}')");
        if ($re) {
            userlog('手机绑定', '用户于' . $date . '将绑定手机号修改为：' . $_SESSION['Mobile'], $USERDATA['id']);
            dies(1, '手机号绑定成功<br>您以后可以用手机号：' . $_SESSION['Mobile'] . '登陆后台了！!');
        } else dies(-1, '绑定失败！' . $DB->error());
        break;
    case 'configuration_save':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($conf['userleague'] <> 1) dies(-1, '当前商城未开启用户加盟权限！');
        if ($USERDATA['grade'] < $conf['userleaguegrade']) dies(-1, '您当前的等级无法开通店铺,请先去提升等级！');
        if (empty($_QET['type'])) dies(-1, '请填写完整！');
        if ($USERDATA['configuration'] == '') {
            $configuration_arr = [];
        } else $configuration_arr = config::common_unserialize($USERDATA['configuration']);
        switch ($_QET['type']) {
            case 'domain':
                if ($conf['userdomaintype'] == 1) {
                    if (empty($_QET['domain']) || empty($_QET['prefix'])) dies(-1, '请填写完整！');
                    preg_match('/^[a-zA-Z0-9]{2,6}+$/u', $_QET['prefix'], $arr_pr);
                    if (empty($arr_pr[0])) dies(-1, '前缀只可为a-Z,0-9的字符串<br>并且前缀长度必须在2-6之间！');
                    $domain = $_QET['prefix'] . '.' . $_QET['domain'];
                    if (in_array($_QET['prefix'], explode(',', $conf['userdomainretain']))) dies(-1, '此域名前缀不可使用，换一个吧！');
                    if ($DB->get_row("SELECT * FROM `sky_user` WHERE `domain` = '$domain' AND `id`<> '{$USERDATA['id']}' LIMIT 1")) dies(-1, '域名（' . $domain . '）已经被他人绑定过了，换一个吧');
                    if ($USERDATA['domain'] == '') {
                        $re = $DB->query("UPDATE `sky_user` SET `domain`='$domain' WHERE (`id`='{$USERDATA['id']}') ");
                        $money = 0;
                    } else {
                        $money = $conf['userdomainsetmoney'];
                        if (explode('.', $USERDATA['domain'])[0] == $_QET['prefix']) $money = 0;
                        if ($USERDATA['money'] < $money) dies(-1, '余额不足,无法完成域名换绑！<br>还差' . ($money - $USERDATA['money']) . '元,快去充值吧');
                        $re = $DB->query("UPDATE `sky_user` SET `domain`='$domain' , `money` = money - $money WHERE (`id`='{$USERDATA['id']}') ");
                    }
                    if ($re) {
                        userlog('域名绑定', '您在店铺管理界面绑定了域名：' . $domain, $USERDATA['id'], $money);
                        dies(1, '店铺域名绑定成功！<br>您以后可以用域名：' . $domain . '<br>访问您的店铺首页了哦！');
                    } else dies(-1, '店铺域名绑定失败,请联系管理员处理！');
                } else {
                    if (empty($_QET['prefix'])) dies(-1, '请填写完整！');
                    preg_match('/^[a-zA-Z0-9]{2,6}+$/u', $_QET['prefix'], $arr_pr);
                    if (empty($arr_pr[0])) dies(-1, '后缀小尾巴只可为a-Z,0-9的字符串<br>并且前缀长度必须在2-6之间！');
                    $domain = $_QET['prefix'];
                    if (in_array($_QET['prefix'], explode(',', $conf['userdomainretain']))) dies(-1, '此域名小尾巴不可使用，换一个吧！');
                    if ($DB->get_row("SELECT * FROM `sky_user` WHERE `domain` = '$domain' AND `id`<> '{$USERDATA['id']}' LIMIT 1")) dies(-1, '域名小尾巴（' . $domain . '）已经被他人绑定过了，换一个吧');
                    if ($USERDATA['domain'] == '') {
                        $re = $DB->query("UPDATE `sky_user` SET `domain`='$domain' WHERE (`id`='{$USERDATA['id']}') ");
                        $money = 0;
                    } else {
                        $money = $conf['userdomainsetmoney'];
                        if (explode('.', $USERDATA['domain'])[0] == $_QET['prefix']) $money = 0;
                        if ($USERDATA['money'] < $money) dies(-1, '余额不足,无法完成域名换绑！<br>还差' . ($money - $USERDATA['money']) . '元,快去充值吧');
                        $re = $DB->query("UPDATE `sky_user` SET `domain`='$domain' , `money` = money - $money WHERE (`id`='{$USERDATA['id']}') ");
                    }
                    if ($re) {
                        userlog('域名绑定', '您在店铺管理界面绑定了域名小尾巴：' . $domain, $USERDATA['id'], $money);
                        dies(1, '店铺域名绑定成功！<br>您以后可以用域名：' . is_https(false) . href() . '?t=' . $domain . '<br>访问您的店铺首页了哦！');
                    } else dies(-1, '店铺域名绑定失败,请联系管理员处理！');
                }
                break;
            case 'template':
                if ($USERDATA['grade'] < $conf['usergradegoodsstate']) dies(-1, '您当前等级无法装修店铺,请先去提升等级吧！');
                $template_arr = for_dir("../template/");
                if (!in_array($_QET['template'], $template_arr)) dies(-1, 'PC端模板[' . $_QET['template'] . ']不存在');
                if (!in_array($_QET['template_m'], $template_arr)) dies(-1, '移动端模板[' . $_QET['template_m'] . ']不存在');
                if (!in_array($_QET['background'], ['1', '2', '3', '4'])) dies(-1, '背景序列号不存在!');
                $configuration_arr = array_merge($configuration_arr, [
                    'template' => $_QET['template'],
                    'template_m' => $_QET['template_m'],
                    'background' => $_QET['background'],
                    'banner' => $_QET['banner'],
                ]);
                $configuration_arr = serialize($configuration_arr);
                break;
            case 'webset':
                if ($USERDATA['grade'] < $conf['usergradenotice']) dies(-1, '您当前等级无法配置店铺基础信息,请先去提升等级吧！');
                $configuration_arr = array_merge($configuration_arr, [
                    'sitename' => $_QET['sitename'],
                    'keywords' => $_QET['keywords'],
                    'description' => $_QET['description'],
                    'kfqq' => $_QET['kfqq'],
                    'Communication' => $_QET['Communication'],
                    'share_url' => $_QET['share_url'],
                ]);
                $configuration_arr = serialize($configuration_arr);
                break;
            case 'notice':
                if ($USERDATA['grade'] < $conf['usergradenotice']) dies(-1, '您当前等级无法配置店铺公告哦,请先去提升等级吧！');
                $configuration_arr = array_merge($configuration_arr, [
                    'notice_top' => base64_encode($_QET['notice_top']),
                    'notice_check' => base64_encode($_QET['notice_check']),
                    'notice_bottom' => base64_encode($_QET['notice_bottom']),
                ]);
                $configuration_arr = serialize($configuration_arr);
                break;
            default:
                dies(-1, '未知访问');
                break;
        }
        $re = $DB->query("UPDATE `sky_user` SET `configuration`='$configuration_arr'  WHERE (`id`='{$USERDATA['id']}') ");
        if ($re) {
            dies(1, '数据保存成功！');
        } else dies(-1, '数据保存失败！');
        break;
    case 'WithdrawDeposit':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($conf['userdeposit'] <> 1) dies(-1, '当前站点未开启提现功能！');
        if ($USERDATA['grade'] < $conf['userdepositgrade']) dies(-1, '您当前等级无法使用提现功能,请先去提升等级吧！');
        $arr_type = explode(',', $conf['userdeposittype']);
        if ($_QET['type'] == 'alipay' && $arr_type[0] <> 1) dies(-1, '当前支付宝提现方式未开启！');
        if ($_QET['type'] == 'wxpay' && $arr_type[1] <> 1) dies(-1, '当前微信提现方式未开启！');
        if ($_QET['type'] == 'qqpay' && $arr_type[2] <> 1) dies(-1, '当前QQ提现方式未开启！');
        if ((float)$_QET['money'] < $conf['userdepositmin']) dies(-1, '最低提现金额为' . $conf['userdepositmin'] . '元,提现条件未满足！');
        if ((float)$_QET['money'] > $USERDATA['money']) dies(-1, '余额不足,提现条件未满足！');
        $timehtm = md5($USERDATA['id'] . '小储云');
        $images = ROOT . '/assets/img/withdraw/' . $timehtm . '/' . $USERDATA['id'] . '.png';
        if (!file_exists($images)) dies(-1, '请先上传收款二维码！');
        $moneys = (float)$_QET['money'];
        $res = $DB->query("UPDATE `sky_user` SET `money`= money-$moneys WHERE (`id`='{$USERDATA['id']}')");
        $re = $DB->query("INSERT INTO `sky_withdrawal` (`type`, `name`, `account_number`, `uid`, `remarks`, `money`, `addtime`)  VALUES ('{$_QET['type']}', '{$_QET['name']}', '{$_QET['account_number']}', '{$USERDATA['id']}', '{$_QET['remarks']}', '{$_QET['money']}','$date');");
        if ($res && $re) {
            userlog('余额提现', '您于' . $date . '进行了提现处理操作,提现金额为：' . $moneys, $USERDATA['id'], $moneys);
            dies(1, '提现请求成功');
        } else dies(-1, '提现请求失败,请联系管理员处理！');
        break;
    case 'image_content': #编辑器专用
        unset($_QET['act']);
        $ImageArr = [];
        foreach ($_QET as $key => $value) {
            if ($value['type'] <> 'image/png' && $value['type'] <> 'image/gif' && $value['type'] <> 'image/jpeg') dies(-1, '只可上传png/jpg/gif类型的图片文件！');
            $image = explode('.', $value["name"]);
            $timehtm = date('Ymd');
            mkdirs("../assets/img/image/" . $timehtm . '/');
            $image = $image['0'] . '.' . $image['1'];
            move_uploaded_file($value["tmp_name"], '../assets/img/image/' . $timehtm . '/' . $image);
            $images = '/assets/img/image/' . $timehtm . '/' . $image;
            $ImageArr[] = ['src' => $images, 'size' => $value['size'] / 1000 . 'kb', 'name' => $value["name"]];
        }
        dier([
            'code' => 1,
            'msg' => '图片上传成功,本次共成功上传' . count($ImageArr) . '张图片',
            'SrcArr' => $ImageArr,
        ]);
        break;
    case 'DoGatheringFigure':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($conf['userdeposit'] <> 1) dies(-1, '当前站点未开启提现,无法上传收款图！');
        if ($USERDATA['grade'] < $conf['userdepositgrade']) dies(-1, '您当前等级无法使用提现功能,请先去提升等级吧！');
        $image = explode('.', $_QET["file"]["name"]);
        $timehtm = md5($USERDATA['id'] . '小储云');
        mkdirs("../assets/img/withdraw/" . $timehtm . '/');
        $image = $USERDATA['id'] . '.png';
        move_uploaded_file($_QET["file"]["tmp_name"], '../assets/img/withdraw/' . $timehtm . '/' . $image);
        $images = '/assets/img/withdraw/' . $timehtm . '/' . $image . '?time=' . time();
        dier(['code' => 0, 'msg' => '上传成功,上传的收款码大小为：' . $_QET['file']['size'] / 1000 . 'kb', 'src' => $images]);
        break;
    case 'withdraw_deposit':
        if ($USERDATA == false) dies(-1, '请先完成登陆！');
        if ($conf['userdeposit'] <> 1) dies(-1, '当前站点未开启提现功能！');
        if ($USERDATA['grade'] < $conf['userdepositgrade']) dies(-1, '您当前等级无法使用提现功能,请先去提升等级吧！');
        $page = ((int)$_GET['page'] - 1) * (int)$_GET['limit'];
        $limit = (int)$_GET['limit'];
        $data = $DB->query("SELECT * FROM `sky_withdrawal` WHERE `uid` = '{$USERDATA['id']}' order by id desc limit $page,$limit ");
        $count = $DB->count("SELECT count(*) FROM sky_withdrawal WHERE `uid` = '{$USERDATA['id']}' ");
        $data_arr = [];
        while ($re = $DB->fetch($data)) {
            $re['arrival_amount'] = round($re['money'] - (($conf['userdepositservice'] / 100) * $re['money']), 2);
            $data_arr[] = $re;
        }
        dier([
            'code' => 0,
            'msg' => '数据获取成功',
            'count' => $count,
            'data' => $data_arr
        ]);
        break;
    default:
        dies(-1, '403');
        break;
}