<?php

namespace app\admin\controller;


use app\common\model\User;
use app\common\model\WalletLog;
use app\common\model\Withdraw;
use think\facade\View;
use app\common\model\Reg;

class Finance extends Base
{
    //提现订单
    public function withdraw()
    {
        $nickname = $this->request->get('nickname', '', 'trim');
        $status = $this->request->get('status', 0, 'intval');
        $start_time = $this->request->get('start_time', '', 'trim');
        $where = [];
        $mod = new Withdraw();
        if ($this->agent_id)
            $where[] = ['u.agent_id', '=', $this->agent_id];
        if ($nickname)
            $where[] = ['u.username', 'like', "%$nickname%"];
        if ($start_time)
            $where[] = ['w.create_time', '>', strtotime($start_time)];
        $stat['price'] = $mod->alias('w')->leftJoin('mod_user u', 'w.uid=u.id')->where($where)->where('w.status', 2)->sum('price');
        $stat['fee'] = $mod->alias('w')->leftJoin('mod_user u', 'w.uid=u.id')->where($where)->where('w.status', 2)->sum('fee');
        $stat['total'] = $stat['price'] - $stat['fee'];
        if ($status)
            $where[] = ['w.status', '=', $status];
        $list = $mod->alias('w')->leftJoin('mod_user u', 'w.uid=u.id')->leftJoin('mod_bank b', 'w.bank_id=b.id')->where($where)
            ->field('w.*,u.username,u.pid,b.name,b.card_no,b.account_name,b.account_open_name,b.type,b.usdt_type')->order('w.id desc')->paginate($this->pageSize)->each(function ($item) {
                if ($item['status'] == 1) {
                    $item['status_txt'] = '未审核';
                } elseif ($item['status'] == 2) {
                    $item['status_txt'] = '已通过';
                } else {
                    $item['status_txt'] = '已驳回';
                }
                if ($item['handle_time'])
                    $item['handle_time'] = date('Y-m-d H:i:s', $item['handle_time']);
                else
                    $item['handle_time'] = '暂未处理';
                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');
        $typeName = [
            0 => [
                'name' => '银行卡',
                'address' => '银行卡卡号'
            ],
            1 => [
                'name' => 'USDT',
                'address' => '收款地址'
            ],
            2 => [
                'name' => 'Wise',
                'address' => 'WISE帐户电子邮件'
            ],
            3 => [
                'name' => 'Revolut',
                'address' => '收款地址'
            ],

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

    //提现审核
    public function withdrawProcess()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id', 0, 'intval');
            $status = $this->request->post('status', 1, 'intval');
            $process = $this->request->post('process', '', 'trim');
            if (!$id)
                $this->result(404, '参数有误');
            if ($status == 3 && !$process)
                $this->result(201, '请填写驳回原因');
            $info = Withdraw::find($id);
            if (!$info)
                $this->result(401, '该条记录不存在');
            if ($info['status'] > 1)
                $this->result(202, '该条记录已经被审核');
            $price = $info['price'] + $info['fee'];
            try {
                $data['status'] = $status;
                $data['remark'] = $process;
                $data['handle_time'] = time();
                $res = Withdraw::update($data, ['id' => $id]);
                $log['uid'] = $info['uid'];
                $log['order_id'] = $id;
                $log['type'] = 2;
                $log['status'] = 2;
                $log['price'] = $price;
                $log['price_pre'] = $info['price_pre'];
                $log['explain'] = '提现成功';
                if ($status == 2) {
                    User::where(['id' => $info['uid']])->dec('freeze_balance', $price)->inc('withdraw', $info['price'])->update();
                    WalletLog::create($log);
                } else
                    User::where(['id' => $info['uid']])->dec('freeze_balance', $price)->inc('balance', $price)->update();
            } catch (\Exception $e) {
                $res = false;
                $this->result(500, '操作异常');
            }
            if ($res)
                $this->result(200, '操作成功', ['time' => date('Y-m-d H:i:s')]);
            else
                $this->result(500, '操作失败');
        }
        $this->result(500, '非法访问');
    }

    //充值订单
    public function regList()
    {
        $nickname = $this->request->get('nickname', '', 'trim');
        $status = $this->request->get('status', 0, 'intval');
        $start_time = $this->request->get('start_time', '', 'trim');
        $where = [];
        $mod = new Reg();
        if ($this->agent_id)
            $where[] = ['u.agent_id', '=', $this->agent_id];
        if ($nickname)
            $where[] = ['u.username', 'like', "%$nickname%"];
        if ($start_time)
            $where[] = ['w.create_time', '>', strtotime($start_time)];
        $stat['price'] = $mod->alias('w')->leftJoin('mod_user u', 'w.uid=u.id')->where($where)->where('w.status', 2)->sum('price');
        $stat['fee'] = $mod->alias('w')->leftJoin('mod_user u', 'w.uid=u.id')->where($where)->where('w.status', 2)->sum('fee');
        $stat['total'] = $stat['price'] - $stat['fee'];
        if ($status)
            $where[] = ['w.status', '=', $status];
        $domain = $this->request->domain();
        $list = $mod->alias('w')->leftJoin('mod_user u', 'w.uid=u.id')->leftJoin('mod_bank_sys b', 'w.bank_id=b.id')->where($where)
            ->field('w.*,u.username,u.pid,b.name,b.card_no,b.account_name')->order('w.id desc')->paginate($this->pageSize)->each(function ($item) use ($domain) {
                if ($item['status'] == 1) {
                    $item['status_txt'] = '未审核';
                } elseif ($item['status'] == 2) {
                    $item['status_txt'] = '已通过';
                } else {
                    $item['status_txt'] = '已驳回';
                }
                if ($item['handle_time'])
                    $item['handle_time'] = date('Y-m-d H:i:s', $item['handle_time']);
                else
                    $item['handle_time'] = '暂未处理';
                // Prepend domain to proof image path if it exists
                // File is saved to /public/uploads/ relative to app root
                // app.peakwork.com subdomain points to app(backend) folder
                // So the URL needs /public prefix: /public/uploads/...
                if (!empty($item['proof']) && strpos($item['proof'], 'http') !== 0) {
                    // Use the same domain (admin panel is on app.peakwork.com)
                    // The path is /uploads/..., need to add /public prefix
                    $item['proof'] = $domain . '/public' . $item['proof'];
                }
                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');
        View::assign(['list' => $list, 'nickname' => $nickname, 'status' => $status, 'stat' => $stat, 'start_time' => $start_time, 'parent' => $parent]);
        return View::fetch();
    }

    //充值审核
    public function regProcess()
    {
        if ($this->request->isAjax()) {
            $id = $this->request->post('id', 0, 'intval');
            $status = $this->request->post('status', 1, 'intval');
            $process = $this->request->post('process', '', 'trim');
            if (!$id)
                $this->result(404, '参数有误');
            if ($status == 3 && !$process)
                $this->result(201, '请填写驳回原因');
            $info = Reg::find($id);
            if (!$info)
                $this->result(401, '该条记录不存在');
            if ($info['status'] > 1)
                $this->result(202, '该条记录已经被审核');
            $price = $info['price'] + $info['fee'];
            try {
                $data['status'] = $status;
                $data['remark'] = $process;
                $data['handle_time'] = time();
                $res = Reg::update($data, ['id' => $id]);
                $log['uid'] = $info['uid'];
                $log['order_id'] = $id;
                $log['type'] = 10;
                $log['status'] = 1;
                $log['price'] = $price;
                $log['price_pre'] = $info['price_pre'];
                $log['explain'] = '充值成功';
                if ($status == 2) {
                    User::where(['id' => $info['uid']])->inc('balance', $price)->update();
                    WalletLog::create($log);
                }
            } catch (\Exception $e) {
                $res = false;
                $this->result(500, '操作异常');
            }
            if ($res)
                $this->result(200, '操作成功', ['time' => date('Y-m-d H:i:s')]);
            else
                $this->result(500, '操作失败');
        }
        $this->result(500, '非法访问');
    }

    //钱包明细
    public function wallet()
    {
        $start_time = $this->request->get('start_time', '', 'trim');
        $uid = $this->request->get('uid', 0, 'intval');
        $nickname = $this->request->get('nickname', '', 'trim');
        $status = $this->request->get('status', 0, 'intval');
        $type = $this->request->get('type', 0, 'intval');
        $where = [];
        if ($this->agent_id)
            $where[] = ['u.agent_id', '=', $this->agent_id];
        if ($nickname)
            $where[] = ['u.username', 'like', "%$nickname%"];
        if ($status)
            $where[] = ['w.status', '=', $status];
        if ($uid)
            $where[] = ['w.uid', '=', $uid];
        if ($type)
            $where[] = ['w.type', '=', $type];
        if ($start_time)
            $where[] = ['w.create_time', '>', strtotime($start_time)];
        $list = WalletLog::alias('w')->leftJoin('mod_user u', 'w.uid=u.id')->where($where)->field('w.*,u.username,u.pid')->order('w.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');
        View::assign(['list' => $list, 'nickname' => $nickname, 'status' => $status, 'uid' => $uid, 'type_list' => WalletLog::$typeTxt, 'type' => $type, 'start_time' => $start_time, 'parent' => $parent]);
        return View::fetch();
    }

}
