<?php

namespace app\admin\controller;

use app\common\model\Admin;
use app\common\model\Bank;
use app\common\model\Configure;
use app\common\model\Level;
use app\common\model\Message;
use app\common\model\Recharge;
use app\common\model\Schedule;
use app\common\model\User;
use app\common\model\WalletLog;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Log;
use think\facade\View;

class Member extends Base
{
    //会员等级列表
    public function levelList()
    {
        $list = Level::paginate($this->pageSize);
        View::assign(['list' => $list]);
        return View::fetch();
    }

    //会员等级添加
    public function levelAdd()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $id = $data['id'] ?? 0;
            unset($data['id']);
            if ($id)
                $res = Level::update($data, ['id' => $id]);
            else
                $res = Level::create($data);
            if ($res)
                $this->result(200, '操作成功');
            else
                $this->result(500, '操作失败');
        }
        $id = $this->request->get('id', 0);
        $info = [];
        if ($id) {
            $info = Level::find($id);
        }
        View::assign(['info' => $info, 'id' => $id]);
        return View::fetch();
    }

    //会员列表
    public function userList()
    {
        $nickname = $this->request->get('nickname', '', 'trim');
        $mobile = $this->request->get('mobile', '', 'trim');
        $type = $this->request->get('type', 0, 'intval');
        $status = $this->request->get('status', 0, 'intval');
        $ag_id = $this->request->get('ag_id', 0, 'intval');
        $start_time = $this->request->get('start_time', '', 'trim');
        $where = [];
        if ($this->agent_id)
            $where[] = ['u.agent_id', '=', $this->agent_id];
        else {
            if ($ag_id)
                $where[] = ['u.agent_id', '=', $ag_id];
        }
        if ($nickname)
            $where[] = ['u.username', 'like', "%$nickname%"];
        if ($type == 1) {
            $where[] = ['u.is_test', '=', 1];
        } elseif ($type == 2) {
            $where[] = ['u.is_test', '=', 0];
        } elseif ($type == 3) {
            $where[] = ['u.is_agent', '=', 1];
        }
        if ($status)
            $where[] = ['u.status', '=', $status];
        if ($start_time)
            $where[] = ['u.create_time', '>', strtotime($start_time)];
        $list = User::alias('u')->leftJoin('mod_level l', 'u.level_id=l.id')->where($where)
            ->field('u.*,l.name as level_name,l.order_num')->order('u.id desc')->paginate($this->pageSize)->each(function ($item) {
                if ($item['status'] == 1) {
                    $item['status_txt'] = '启用';
                } else {
                    $item['status_txt'] = '禁用';
                }
                if ($item['trade_status'] == 1) {
                    $item['trade_txt'] = '启用';
                } else {
                    $item['trade_txt'] = '禁用';
                }
                if ($item['is_agent']) {
                    $item['type'] = '代理用户';
                } elseif ($item['is_test']) {
                    $item['type'] = '测试用户';
                } else {
                    $item['type'] = '普通用户';
                }
                if ($item['login_time'])
                    $item['login_time'] = date('Y-m-d H:i', $item['login_time']);
                else
                    $item['login_time'] = '暂无';
                if (!$item['login_ip'])
                    $item['login_ip'] = '暂无';
                return $item;
            });
        $list_arr = $list->getCollection()->toArray();
        $uid_arr = array_merge(array_column($list_arr, 'pid'), array_column($list_arr, 'agent_id'));
        $uid_arr = array_unique($uid_arr);
        $parent = User::where(['id' => $uid_arr])->column('username', 'id');
        if (!$this->agent_id) {
            $agent = User::where(['is_agent' => 1])->column('username', 'id');
            View::assign('agent', $agent);
        }
        View::assign([
            'list' => $list, 'nickname' => $nickname, 'mobile' => $mobile,
            'type' => $type, 'status' => $status, 'start_time' => $start_time,
            'parent' => $parent, 'ag_id' => $ag_id,
        ]);
        return View::fetch();
    }

    //会员添加
    public function userAdd()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $id = $data['id'] ?? 0;
            unset($data['id']);
            $system_home = Cache::get('systemHome');//获取系统配置
            if (empty($system_home)) {
                $info = Configure::find(2);
                $system_home = json_decode($info['content'], true);
                Cache::set('systemHome', $system_home, 86400);
            }
            $system_basic = Cache::get('systemBasic');
            if (empty($system_basic)) {
                $info = Configure::find(1);
                $system_basic = json_decode($info['content'], true);
                Cache::set('systemBasic', $system_basic, 86400);
            }
//            if (!empty($data['password'])) {
//                $data['password'] = md5($data['password']);
//            }
//            if (!empty($data['deal_pass'])) {
//                $data['deal_pass'] = md5($data['deal_pass']);
//            }
            if ($id)
                $res = User::update($data, ['id' => $id]);
            else {
                $data['create_time'] = time();
                $data['balance'] = $system_basic['register_reward'] ?? 0;
                if ($this->agent_id)
                    $data['agent_id'] = $this->agent_id;
                $count = User::where(['username' => $data['username']])->count();
                if ($count)
                    $this->result(401, '该用户名已经存在，请更换');
                if (!empty($data['pid'])) {
                    $parent = User::field('sub_num,family,agent_id')->find($data['pid']);
                    if (!$parent)
                        $this->result(402, '上级不存在');
                    User::update(['sub_num' => $parent['sub_num'] + 1], ['id' => $data['pid']]);
                    if ($parent['family']) {
                        $family = explode('-', $parent['family']);
                        if (count($family) == 5) {
                            unset($family[4]);
                        }
                        array_unshift($family, $data['pid']);
                        $data['family'] = implode('-', $family);
                    } else {
                        $data['family'] = $data['pid'];
                    }
                    if (!$this->agent_id) {
                        $data['agent_id'] = $parent['agent_id'];
                    }
                }
                $data['invite_code'] = getRandStr(6);
                $data['is_test'] = 1;

                $mes_data['title_vi'] = $system_home['register_title_vi'] ?? '';
                $mes_data['title_en'] = $system_home['register_title_vi'] ?? '';
                $mes_data['content_vi'] = $system_home['register_vi'] ?? '';
                $mes_data['content_en'] = $system_home['register_en'] ?? '';
                $mes_data['create_time'] = time();

                $res = User::insertGetId($data);
                if ($res) {
                    $mes_data['uid'] = $res;
                    Message::create($mes_data);
                }
            }
            if ($res)
                $this->result(200, '操作成功');
            else
                $this->result(500, '操作失败');
        }
        $id = $this->request->get('id', 0);
        $info = ['is_agent' => 0, 'is_test' => 0, 'status' => 1, 'trade_status' => 1, 'level_id' => 1, 'pid' => $this->agent_id];
        $level_list = Level::field('id,name')->select()->toArray();
        if ($id) {
            $info = User::find($id);
        }
        View::assign(['info' => $info, 'id' => $id, 'level' => $level_list]);
        return View::fetch();
    }

    //加扣款
    public function balanceChange()
    {
        if ($this->request->isAjax()) {
            $uid = $this->request->post('uid', 0, 'intval');
            if (!$uid)
                $this->result(400, '参数有误');
            $price = $this->request->post('price', 0);
            if (!$price)
                $this->result(401, '金额为0');
            $dire = $this->request->post('dire', 1);//1-上分2-下分
            $user = User::where(['id' => $uid])->field('balance,is_test')->find();
            if (!$user)
                $this->result(402, '用户不存在');
            $error = '';
            $system_home = Cache::get('systemHome');//获取系统配置
            if (empty($system_home)) {
                $info = Configure::find(2);
                $system_home = json_decode($info['content'], true);
                Cache::set('systemHome', $system_home, 86400);
            }
            $day_user_key = 'dayFirstRechargeUser_' . date('Ymd');
            $day_user_arr = Cache::get($day_user_key) ?? '';

            Db::startTrans();
            try {
                if ($dire == 1) {
                    $res = User::where(['id' => $uid])->inc('balance', $price)->inc('recharge', $price)->update();
                    $price_real = $price;
                } else {
                    $res = User::where(['id' => $uid])->dec('balance', $price)->update();
                    $price_real = 0 - $price;
                }
                $log['uid'] = $uid;
                $log['status'] = $dire;
                $log['price'] = $price;
                $log['price_pre'] = $user['balance'];
                $res_wallet = WalletLog::create($log);

                // Add deposit record for Uniapp list
                if ($dire == 1) {
                    \app\common\model\Reg::create([
                        'uid' => $uid,
                        'price' => $price,
                        'price_pre' => $user['balance'],
                        'status' => 2,
                        'handle_time' => time(),
                        'remark' => 'System Recharge'
                    ]);
                }

                $recharge['uid'] = $uid;
                $recharge['admin_id'] = session('adminInfo.id');
                $recharge['price'] = $price;
                $recharge['status'] = $dire;
                $recharge['price_pre'] = $user['balance'];
                $res_recharge = Recharge::create($recharge);

                //添加充值消息
                if ($dire == 1 && !empty($system_home['recharge_vi']) && !empty($system_home['recharge_en'])) {
                    $mes['uid'] = $uid;
                    $mes['content_vi'] = str_replace('{{price}}', $price_real, $system_home['recharge_vi']);
                    $mes['content_en'] = str_replace('{{price}}', $price_real, $system_home['recharge_en']);
                    if (!empty($system_home['recharge_zh'])) {
                        $mes['content_zh'] = str_replace('{{price}}', $price_real, $system_home['recharge_zh']);
                    }
                    Message::create($mes);
                }
                if (!$user['is_test']) {
                    //添加首充记录
                    if (!$day_user_arr || !strpos($day_user_arr, (string)$uid)) {
                        $day_info = Db::name('DayFill')->where(['day' => date('Ymd'), 'agent_id' => $this->agent_id])->find();
                        if (!$day_info) {
                            $day_data['day'] = date('Ymd');
                            $day_data['people'] = 1;
                            $day_data['price'] = $price_real;
                            $day_data['agent_id'] = $this->agent_id;
                            Db::name('DayFill')->insert($day_data);
                        } else {
                            $day_data['people'] = $day_info['people'] + 1;
                            $day_data['price'] = $day_info['price'] + $price_real;
                            Db::name('DayFill')->where(['id' => $day_info['id']])->update($day_data);
                        }
                        $day_user_arr .= '#' . $uid;
                    }
                }
                if ($res && $res_wallet && $res_recharge) {
                    Cache::set($day_user_key, $day_user_arr, 86400);
                    Db::commit();
                } else {
                    $error = '操作失败';
                    Db::rollback();
                }
            } catch (\Exception $e) {
                Db::rollback();
                $error = '操作失败';
                Log::error('上下分失败-' . $e->getMessage() . ':' . $e->getLine());
            }
            if ($error)
                $this->result(500, $error);
            else
                $this->result(200, '操作成功');
        }
        $this->result(500, '非法请求');
    }

    //订单设置
    public function orderConfig()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            // Get value from hidden field (always present, even when checkbox is unchecked)
            $total_order_stop = isset($data['total_order_stop_value']) ? intval($data['total_order_stop_value']) : 1;
            unset($data['total_order_stop'], $data['total_order_stop_value']);
            $uid = $data['uid'] ?? 0;
            
            // Always update User table first, regardless of Schedule operations
            if ($uid) {
                User::update(['total_order_stop' => $total_order_stop], ['id' => $uid]);
            }
            
            // Handle Schedule operations only if config exists
            $config = $data['config'] ?? '';
            if (empty($config)) {
                // If no config, just return success (User update was successful)
                $this->result(200, '操作成功');
                return;
            }
            
            $id = $data['id'];
            $type = $data['type'] ?? 1;
            $start_num = $data['start_num'];
            $data['type'] = $type;
            $config = json_decode($config, true);
            unset($data['config'], $data['id']);
            
            if (!is_array($config)) {
                $config = [];
            }
            
            $goods = [];
            foreach ($config as $val) {
                if ($val) {
                    if ($type == 1) {
      $goods[$val['order_no']] = ['gid' => $val['gid'], 'order_rate' => $val['order_rate']];
                    } else {
                        $goods[$start_num] = ['gid' => $val['gid'], 'order_rate' => $val['order_rate']];
                        $start_num++;
                    }
                }
            }
            $data['status'] = $data['status'] ?? 2;
            if ($goods)
                $data['rule'] = json_encode($goods);
            if (!$id)
                $res = Schedule::create($data);
            else {
                unset($data['uid']);
                $res = Schedule::update($data, ['id' => $id]);
            }
            if ($res)
                $this->result(200, '操作成功');
            else
                $this->result(500, '操作失败');
        }
        $uid = $this->request->get('uid', 0, 'intval');
        $user_info = User::alias('u')->leftJoin('mod_level l', 'u.level_id=l.id')->where(['u.id' => $uid])
            ->field('u.order_total,u.nickname,u.total_order_stop,l.order_num,l.order_rate')->find();
        $order_total = $user_info['order_total'] ?? 0;
        $order_num = $user_info['order_num'] ?? 0;
        $nickname = $user_info['nickname'] ?? '';
        $total_order_stop = $user_info['total_order_stop'] ?? 1;
        $level_order_rate = $user_info['order_rate'] ?? '0';
        $info = Schedule::where(['uid' => $uid])->find();
        if ($info) {
            $info = $info->toArray();
            $info['rule'] = json_decode($info['rule'], true) ?? [];
            // dd($info);
            $info['current_config'] = '';
            $info['current_txt'] = '';//文字描述
            foreach ($info['rule'] as $key => $val) {
                $info['current_config'] .= $key . '-' . $val['gid'] . ',';
                $info['current_txt'] .= "[第{$key}单是产品{$val['gid']}]";
            }
        } else {
            $info['status'] = 1;
            $info['type'] = 1;
        }
        View::assign(['info' => $info, 'order_total' => $order_total, 'order_num' => $order_num, 'uid' => $uid, 'nickname' => $nickname, 'total_order_stop' => $total_order_stop, 'level_order_rate' => $level_order_rate]);
        return View::fetch();
    }

    //查看团队
    public function team()
    {
        $pid = $this->request->get('pid', 0, 'intval');
        $status = $this->request->get('status', 0, 'intval');
        $where['u.pid'] = $pid;
        if ($status)
            $where['u.status'] = $status;
        $list = User::alias('u')->leftJoin('mod_level l', 'u.level_id=l.id')->where($where)
            ->field('u.*,l.name as level_name,l.order_num')->paginate($this->pageSize)->each(function ($item) {
                if ($item['status'] == 1) {
                    $item['status_txt'] = '启用';
                } else {
                    $item['status_txt'] = '禁用';
                }
                if ($item['trade_status'] == 1) {
                    $item['trade_txt'] = '启用';
                } else {
                    $item['trade_txt'] = '禁用';
                }
                if ($item['is_agent']) {
                    $item['type'] = '代理用户';
                } elseif ($item['is_test']) {
                    $item['type'] = '测试用户';
                } else {
                    $item['type'] = '普通用户';
                }
                if ($item['login_time'])
                    $item['login_time'] = date('Y-m-d H:i', $item['login_time']);
                else
                    $item['login_time'] = '暂无';
                if (!$item['login_ip'])
                    $item['login_ip'] = '暂无';
                return $item;
            });
        View::assign(['list' => $list, 'pid' => $pid, 'status' => $status]);
        return View::fetch();
    }

    //重置任务量
    public function resetOrder()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id', 0, 'intval');
            if (!$id)
                $this->result(404, '参数有误');
            User::update(['order_total' => 0], ['id' => $id]);
            Schedule::update(['rule' => '[]'], ['uid' => $id]);
            $this->result(200, '重置成功');
        }
        $this->result(500, '非法访问');
    }

    //状态修改
    public function userDisable()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id', 0, 'intval');
            $id_arr = $this->request->post('ids', []);
            $type = $this->request->post('type', 0, 'intval');
            $status = $this->request->post('status', 1, 'intval');
            if (!$id && !$id_arr)
                $this->result(400, '参数有误');
            if ($type)
                $data['trade_status'] = $status;
            else
                $data['status'] = $status;
            if ($id_arr) {
                $id = $id_arr;
            }
            $res = User::update($data, ['id' => $id]);
            if ($res)
                $this->result(200, '操作成功');
            else
                $this->result(500, '操作失败');
        }
        $this->result(500, '非法访问');
    }

    //用户类型修改
    public function typeChange()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id', 0, 'intval');
            $type = $this->request->post('type', 0, 'intval');
            $status = $this->request->post('status', 0, 'intval');
            if (!$id)
                $this->result(400, '参数有误');
            $user_info = User::find($id);
            if (!$user_info)
                $this->result(404, '用户不存在');
            if ($type) {
                $data['is_agent'] = $status;
                $admin_data['role_id'] = 1;
                $admin_data['user_id'] = $id;
                $admin_data['username'] = $user_info['username'];
                $admin_data['password'] = md5($user_info['password']);
                $admin_data['remark'] = $user_info['password'];
                Admin::create($admin_data);
            } else
                $data['is_test'] = $status;
                // $data['agent_id'] = $id;
            $res = User::update($data, ['id' => $id]);
            if ($res)
                $this->result(200, '操作成功');
            else
                $this->result(500, '操作失败');
        }
        $this->result(500, '非法访问');
    }

    //密码修改
    public function changePass()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id', 0, 'intval');
            $password = $this->request->post('password', '', 'trim');
            $deal_pass = $this->request->post('deal_pass', '', 'trim');
            if (!$id)
                $this->result(400, '参数有误');
            $data = [];
            if ($password)
                $data['password'] = $password;
            if ($deal_pass)
                $data['deal_pass'] = $deal_pass;
            if (!$data) {
                $this->result(201, '无变化');
            }
            $res = User::update($data, ['id' => $id]);
            if ($res)
                $this->result(200, '操作成功');
            else
                $this->result(500, '操作失败');
        }
        $this->result(500, '非法访问');
    }

    //上下分记录
    public function rechargeList()
    {
        $nickname = $this->request->get('nickname', '', 'trim');
        $status = $this->request->get('status', 0, 'intval');
        $start_time = $this->request->get('start_time', '', 'trim');
        $where = [];
        if ($this->agent_id)
            $where[] = ['u.agent_id', '=', $this->agent_id];
        if ($nickname)
            $where[] = ['u.username', 'like', "%$nickname%"];
        if ($status)
            $where[] = ['r.status', '=', $status];
        if ($start_time)
            $where[] = ['r.create_time', '>', strtotime($start_time)];
        $mod = new Recharge();
        $list = $mod->alias('r')->leftJoin('mod_user u', 'u.id=r.uid')->leftJoin('mod_admin a', 'r.admin_id=a.id')->where($where)
            ->field('r.*,u.username as u_name,a.username,u.pid')->order('r.id desc')->paginate($this->pageSize)->each(function ($item) {
                if ($item['status'] == 1) {
                    $item['status_txt'] = '上分';
                    $item['price_after'] = $item['price_pre'] + $item['price'];
                } else {
                    $item['status_txt'] = '下分';
                    $item['price_after'] = $item['price_pre'] - $item['price'];
                }
                return $item;
            });
        $list_arr = $list->getCollection()->toArray();
        $uid_arr = array_unique(array_column($list_arr, 'pid'));
        $parent = User::where(['id' => $uid_arr])->column('username', 'id');

        $stat['up'] = $mod->alias('r')->leftJoin('mod_user u', 'u.id=r.uid')->where($where)->where('r.status', 1)->sum('price');
        $stat['down'] = $mod->alias('r')->leftJoin('mod_user u', 'u.id=r.uid')->where($where)->where('r.status', 2)->sum('price');
        $stat['total'] = $stat['up'] - $stat['down'];
        View::assign(['list' => $list, 'nickname' => $nickname, 'status' => $status, 'start_time' => $start_time, 'stat' => $stat, 'parent' => $parent]);
        return View::fetch();
    }

    //银行卡列表
    public function bankList()
    {
        $nickname = $this->request->get('nickname', '', 'trim');
        $start_time = $this->request->get('start_time', '', 'trim');
        $where = [];
        if ($this->agent_id)
            $where[] = ['u.agent_id', '=', $this->agent_id];
        if ($nickname)
            $where[] = ['u.username', 'like', "%$nickname%"];
        if ($start_time)
            $where[] = ['b.create_time', '>', strtotime($start_time)];
        $list = Bank::alias('b')->leftJoin('mod_user u', 'u.id=b.uid')->where($where)->field('b.*,u.username,u.pid')->order('b.id desc')->paginate($this->pageSize);
        $list_arr = $list->getCollection()->toArray();
        $uid_arr = array_unique(array_column($list_arr, 'pid'));
        $parent = User::where(['id' => $uid_arr])->column('username', 'id');

        View::assign(['list' => $list, 'nickname' => $nickname, 'start_time' => $start_time, 'parent' => $parent]);
        return View::fetch();
    }

    //佣金修改
    public function commissionChange()
    {
        if ($this->request->isAjax()) {
            $uid = $this->request->post('uid', 0, 'intval');
            $commission = $this->request->post('commission', 0);
            if (!$uid)
                $this->result(400, '参数有误');
            
            $res = User::update(['commission' => $commission], ['id' => $uid]);
            if ($res)
                $this->result(200, '操作成功');
            else
                $this->result(500, '操作失败');
        }
        $this->result(500, '非法访问');
    }

}
