<?php
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// |
// +----------------------------------------------------------------------
// | Date: 2020-11-08 12:56
// +----------------------------------------------------------------------

namespace app\system\controller\v1;


use app\BaseController;
use app\model\api\Tx as TxModel;
use app\model\api\User as UserModel;
use app\model\api\Sys as SysModel;
use app\model\api\Bank as BankModel;
use app\model\api\UserDetail as UserDetailModel;
use app\model\api\TuserDetail as TuserDetailModel;
use think\db\exception\DbException;
use think\facade\Db;
use app\Request;
use library\services\UtilService;

class Tx extends BaseController
{
    /**
     * 初始化
     * @param Request $request
     * @return type
     */
    public function init(Request $request)
    {
        [$isTuser] = UtilService::getMore(
            [
                ['isTuser',0],
            ], $request,true);
        $isTuser = empty($isTuser) ? 0 : 1;
        $where=[];
        //获取全部提现
        $allTx = (new TxModel)->where($where)->count();
        $noTx  = (new TxModel)->where($where)->where('status', 0)->count();
        $yeTx  = (new TxModel)->where($where)->where('status', 1)->count();
        $errTx = (new TxModel)->where($where)->where('status', -1)->count();
        
        $bankList = (new BankModel)
//                ->where("status",1)
                ->order("seq","desc")
                ->order("id","desc")
                ->select()
                ->toArray();
        $bankList = empty($bankList)?[]:$bankList;
        
        
        return app('json')->success([
            'all_tx' => $allTx,
            'no_tx'  => $noTx,
            'yes_tx' => $yeTx,
            'err_tx' => $errTx,
            'bankList'=>$bankList,
        ]);
    }

    /**
     * 获取提现列表
     * @param Request $request
     */
    public function list(Request $request)
    {
        $pageSize = 50;
        $post     = UtilService::getMore(
            [
                //公共参数
                ['page', 1],
                ['status', ''],
                ['bank_type', ''],
                ['time',[]],
                //手机用户
                ['mobile',''],
                ['uip', ''],
                ['uid', ''],
            ], $request
        );
        $where=[];
        //公共参数
        if(is_numeric($post['status'])) {
            $where[]=['t.status',"=",$post['status']];
        }
        if(!empty($post['bank_type'])) {
            $where[]=['t.bank_type',"=",$post['bank_type']];
        }
        //提现时间
        $startTime = "";
        $endTime = "";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
            $startTime =  strtotime($post['time'][0]);
            $endTime = strtotime($post['time'][1]);
            $where[]=['t.time',"between","{$startTime},{$endTime}"];
        }
        //用户uid
        if(is_numeric($post['uid'])) {
            $where[]=['t.uid',"=",$post['uid']];
        }else if (!empty($post['uip'])) {
            $m  = Db::name("user")->where("uip",$post['uip'])->find();
            if(!empty($m)) {
                $where[]=['t.uid',"=",$m['uid']];
            }
        }else if (!empty($post['mobile'])) {
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where[]=['t.uid',"=",$m['uid']];
            }
        }
        $data = (new TxModel)
                ->alias("t")
                ->field("t.*,u.uip,u.nickname,u.mobile,a.username as admin_name,b.name as bank_type_name")
                ->leftJoin("user u", "u.uid = t.uid")
                ->leftJoin("admin a", "a.id = t.admin_id")
                ->leftJoin("bank b", "b.code = t.bank_type")
                ->where($where)
                ->page((int)$post["page"], $pageSize)
                ->order("t.id","desc")
                ->select()
                ->toArray();
        $pageCount = (new TxModel)->alias("t")->where($where)->count();
        $result = UtilService::getParam([
            "id",
            "uid",
            "bank_type",
            "bank_type_name",
            "bank_num",
            "bank_name",
            "bank_ad",
            "money",
            "tx_money",
            "hand_money",
            "status",
            ["time", "time", "date('Y-m-d H:i:s',$1)"],
            "admin_id",
            "admin_remark",
            ["admin_time", "admin_time", function ($item) {
                return empty($item) ? '' : date('Y-m-d H:i:s', $item);
            }],
            "admin_name",
            "mobile",
            "nickname",
            "uip",
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }
    /**
     * 提现处理
     * @param Request $request
     */
    public function dealSub(Request $request)
    {
        $post   = UtilService::getMore(
            [
                ['id', '', 'empty', '参数错误'],
                ['mono'],
                ['type', 0],
            ], $request);
        $txData = (new TxModel)->where('id', $post['id'])->find();
        if (empty($txData)) {
            return app('json')->fail('数据不存在');
        }
        if ($txData['status']!=0) {
            return app('json')->success( '当前提现申请已处理');
        }
        //提现通过
        if ($post['type'] == 1) {
            (new TxModel)
                ->where('id', $post['id'])
                ->save([
                    'status'        => 1,
                    'admin_remark' => empty($post['mono'])?"已确认打款":$post['mono'],
                    'admin_time'    => time(),
                    'admin_id'     => $request->adminInfo['id'],
                ]);
            return app('json')->success('操作成功');
        }
        //提现驳回
        if ($post['type'] == -1) {
            //添加事件回滚
            try{
                Db::startTrans();
                (new TxModel)
                    ->where('id', $post['id'])
                    ->save([
                        'status'        => -1,
                        'admin_remark' => empty($post['mono'])?"已驳回申请":$post['mono'],
                        'admin_time'    => time(),
                        'admin_id'     => $request->adminInfo['id'],
                    ]);
                if($txData["uid"]>0){
                    //用户提现驳回
                    (new UserDetailModel)->txRefundMoney($txData['uid'],$txData["money"],$txData["id"]);
                }else{
                    return app("json")->fail("提现用户不存在");
                }
                Db::commit();
                return app('json')->success('操作成功');
            }catch(DbException $db){
                Db::rollback();
                return app("json")->fail("操作失败");
            }
        }
    }
    /**
     * 获取订单数据
     * @param Request $request
     */
    public function down(Request $request)
    {
        $pageSize = 40000;
        $post     = UtilService::getMore(
            [
                ['page', 1],
                ['mobile',''],
                ['status', ''],
                ['bank_type', ''],
                ['uid', ''],
                ['time',[]],
            ], $request
        );
        $where    = [];
        $where=[];

        if(is_numeric($post['status'])) {
            $where['t.status'] = $post['status'];
        }
        if(is_numeric($post['uid'])) {
            $where['t.uid'] = $post['uid'];
        }

        if (!empty($post['mobile'])) {
            $m  = Db::name("user")->where("mobile",$post['mobile'])->find();
            if(!empty($m)) {
                $where['t.uid'] = $m['uid'];
            }
        }
        
        if(!empty($post['bank_type'])) {
            $where['t.bank_type'] = $post['bank_type'];
        }
        $startTime = "";
        $endTime = "";
        if(!empty($post['time'][0]) && !empty($post['time'][1])) {
           $startTime =  strtotime($post['time'][0]);
           $endTime = strtotime($post['time'][1]);
        }
        $data = (new TxModel)
                ->alias("t")
                ->field("t.*,u.uip,u.nickname,u.mobile,a.username as admin_name")
                ->leftJoin("user u", "u.uid = t.uid")
                ->leftJoin("admin a", "a.id = t.admin_id")
                ->where($where)
                ->when((!empty($startTime) && !empty($endTime)),function($query)use($startTime,$endTime){
                    $query->whereBetween("t.time","{$startTime},{$endTime}");
                })
                ->limit(0,30000)
                ->order("t.id","desc")
                ->select()
                ->toArray();
        $pageCount = (new TxModel)
                ->alias("t")
                ->leftJoin("user u", "u.uid = t.uid")
                ->leftJoin("admin a", "a.id = t.admin_id")
                ->where($where)
                ->when((!empty($startTime) && !empty($endTime)),function($query)use($startTime,$endTime){
                    $query->whereBetween("t.time","{$startTime},{$endTime}");
                })
                ->count();
        $result = UtilService::getParam([
            "id",
            "uid",
            "bank_type",
            "bank_num",
            "bank_name",
            "bank_ad",
            "money",
            "tx_money",
            "hand_money",
            "status",
            ["time", "time", "date('Y-m-d H:i:s',$1)"],
            "admin_id",
            "admin_remark",
            ["admin_time", "admin_time", function ($item) {
                return empty($item) ? '' : date('Y-m-d H:i:s', $item);
            }],
            "admin_name",
            "mobile",
            "nickname",
            "uip",
        ], $data);
        return app('json')->success([
            'list'      => $result,
            'pageCount' => $pageCount,
            'pageSize'  => $pageSize,
            'page'      => $post['page'],
        ]);
    }
    
}
