<?php

namespace app\admin\controller\users;

use app\common\controller\Backend;
use app\lib\utils\ErrorInfo;
use app\lib\utils\WXPay\WXPayConstants;
use think\Exception;
use think\Db;
use think\Request;

/**
 * 提现申请管理
 *
 * @icon fa fa-circle-o
 */
class Withdraw extends Backend
{

    /**
     * Withdraw模型对象
     * @var \app\admin\model\users\Withdraw
     */
    protected $model = null;
    protected $usersmodel = null;
    protected $Bankcardmodel = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\users\Withdraw;
        $this->usersmodel = new \app\admin\model\users\Users;
        $this->Bankcardmodel = new \app\admin\model\users\Bankcard;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("withdrawWayList", $this->model->getWithdrawWayList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $filter = json_decode($this->request->get("filter"),true);
        $op = json_decode($this->request->get("op"),true);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->field('*,TRUNCATE(money/100, 2) as money')
            ->order($sort, $order)
            ->paginate($limit);
        $total_withraw = $this->model
            ->where($where)
            ->where(['status' => 1])
            ->sum('money');
        $user_where = [];
        if(isset($filter['name'])) {
            $user_where['realname'] = $filter['name'];
        }
        $total_money = $this->usersmodel
            ->where(['id'=>['not in',[191,183,176,15,34,33,26,21,14,13,5]]])
            ->where($user_where)
            ->sum('total_money');
        $result = ['total' => $list->total(), 'rows' => $list->items(), 'total_withraw' => sprintf("%.2f", $total_withraw / 100),'total_money' =>$total_money];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 提现审核
     */
    public function batchaudit($ids = ''){
        $ip = request()->ip();
        $admin_id = get_admin_id();
        if (!in_array($ip, ['183.217.150.48']) && $admin_id != 1) {
            $this->error('非管理员禁止审核提现');
        }
        if($ids){
            $row = $this->model->where(['status'=>0,'id' =>['in',explode(',',$ids)]])->select();
        }else{
            $this->error(__('请批量勾选'));
//            $row = $this->model->where(['status' =>0])->select();
        }
        $jsonMap = new ErrorInfo();
        $wxpayConstants = new WXPayConstants();
        $result = false;
        //        $row['money'] = sprintf("%.2f", $row['money'] / 100);
        //提现固定扣除1%手续费
        foreach ($row as $key => $val){
            $val['money'] =  floor((int)$val['money'] - (int)$val['money'] * 0.01);
            $withraw_money = $val['money'];
            Db::startTrans();
            try {
                $usersinfo = $this->usersmodel->where(['id' => $val['user_id']])->find();
                if ($usersinfo['type']) {
                    $desc = '合伙人(桩主)提现';
                } else {
                    $desc = '普通用户提现';
                }
                $bankcard = $this->Bankcardmodel->where(['id' =>$val['bankcard_id']])->find();
                switch ($val['withdraw_way']){
                    case 1://提现至零钱
                        $result = $wxpayConstants->transfer($usersinfo['wx_openid'], $desc, $val['cash_sn'], $val['money'], $val['name'], $jsonMap);
                        break;
                    case 2://提现至银行卡
                        if($withraw_money <= 1000*100){
                            $val['money'] = $val['money'] - 1*100;
                        }else{
                            $val['money'] = floor($val['money'] - $withraw_money*0.001);
                        }
                        $result = $wxpayConstants->payForBank($val['cash_sn'], $val['money'], $val['bank_num'], $val['name'], $bankcard['wx_bank_code'],'企业付款到银行卡', $jsonMap);
                        break;
                    default:
                        break;
                }
                if ($jsonMap->code < 0) {
                    $this->error(__($jsonMap->msg));
                }
                $arr['status'] = 1;
                $arr['end_time'] = time();
                $this->model->where(['id' => $val['id']])->update($arr);
                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }

        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success('提现成功');
    }

    /**
     * 提现审核
     */
    public function audit($id = '', $status = 0)
    {
        $ip = request()->ip();
        $admin_id = get_admin_id();
        if (!in_array($ip, ['183.217.150.48']) && $admin_id != 1) {
            $this->error('非管理员禁止审核提现');
        }
        $row = $this->model->get(['id' => $id]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['status'] != '0') {
            $this->error(__('该提现记录不需要审核'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $jsonMap = new ErrorInfo();
        $wxpayConstants = new WXPayConstants();
        $result = false;
        //        $row['money'] = sprintf("%.2f", $row['money'] / 100);
        //提现固定扣除1%手续费
        $withraw_money = $row['money'];
        $row['money'] =  floor((int)$row['money'] - (int)$row['money'] * 0.01);
        Db::startTrans();
        try {
            $usersinfo = $this->usersmodel->where(['id' => $row['user_id']])->find();
            if ($usersinfo['type']) {
                $desc = '合伙人(桩主)提现';
            } else {
                $desc = '普通用户提现';
            }
            $bankcard = $this->Bankcardmodel->where(['id' =>$row['bankcard_id']])->find();
            if($row['status']!=0){
                Db::rollback();
                $this->error($row['id'].'记录已审核');
            }
            switch ($row['withdraw_way']){
                case 1://提现至零钱
                    $result = $wxpayConstants->transfer($usersinfo['wx_openid'], $desc, $row['cash_sn'], $row['money'], $row['name'], $jsonMap);
                    break;
                case 2://提现至银行卡
                    if($withraw_money <= 1000*100){
                        $row['money'] = $row['money'] - 1*100;
                    }else{
                        $row['money'] = floor($row['money'] - $withraw_money*0.001);
                    }
                    $result = $wxpayConstants->payForBank($row['cash_sn'], $row['money'], $row['bank_num'], $row['name'], $bankcard['wx_bank_code'],'企业付款到银行卡', $jsonMap);
                    break;
                default:
                    break;
            }
            if ($jsonMap->code < 0) {
                Db::rollback();
                $this->error(__($jsonMap->msg));
            }
            $arr['status'] = $status;
            $arr['end_time'] = time();
            $row->where(['id' => $id])->update($arr);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        /*if (false === $result) {
            $this->error(__('No rows were updated'));
        }*/
        $this->success('提现成功');
    }

    /**
     * 拒绝用户提现
     */
    public function refuce($id = '', $status = -1)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->Post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['status'] = $status;
                    if ($row['status'] == 0) {
                        $money = sprintf("%.2f", $row['money'] / 100);
                        $this->usersmodel->where(['id' => $row['user_id']])->setInc('total_money', $money);
                        //更新店铺详情
                        $result = $row->allowField(true)->save($params);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("拒绝退款成功");
                } else {
                    $this->error(__('拒绝退款失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 核销提现
     */
    public function verification($id = '', $status = 2)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        Db::startTrans();
        try {

            $params['status'] = $status;
            $params['end_time'] = time();
            $row->where(['id' => $id])->update($params);
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("核销成功");


    }

    /**
     * 核销提现
     */
    public function batchVerification($ids= '')
    {
       /* $ip = request()->ip();
        $admin_id = get_admin_id();
        if (!in_array($ip, ['183.217.150.48']) && $admin_id != 1) {
            $this->error('非管理员禁止审核提现');
        }*/
        if($ids){
            $row = $this->model->where(['status'=>0,'id' =>['in',explode(',',$ids)]])->select();
        }else{
            $this->error(__('请批量勾选'));
//            $row = $this->model->where(['status' =>0])->select();
        }
        $params = [];
        foreach ($row as $key => $val){
            $params['status'] = 2;
            $params['end_time'] = time();
            $row->where(['id' => $val['id']])->update($params);
        }

        $this->success("核销成功");

    }
}
