<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class FundApplyController extends BaseController
{
    /**
     * 钩子 (TP自动继承父级构造)
     */
    public function _initialize()
    {
        // 此处引入的是设为小程序配置的支付类, 收款用户为小程序用户
        //引入WxPayPubHelper
        vendor('WxPayPubHelper.WxPayPubHelper');
        // 引入企业付款类
        vendor('WxPayPubHelper.EnterprisePayment');
    }

    /**
     * 提现申请 列表
     */
    public function applyList()
    {
        auth_check("permit_read");
        // 申请总额
        $allPayment = M("fundApply")->where("`status`=1")->sum("money");
        if (!$allPayment) {
            $allPayment = 0;
        }
        $this->assign("allPayment", $allPayment);
        // 列表
        $l = 10;//确定每页记录数
        $where = "fa.`status`=1";
        // $search = I("search");
        // if ($search) {
        //     $where .= " AND (o.`ordersn` LIKE '%$search%' OR o.`name` LIKE '%$search%' OR o.`tel` LIKE '%$search%')";
        //     $this->assign("search", $search);
        // }
        $order = "`id` DESC";
        $count = M("fundApply")
            ->join("fa LEFT JOIN `am_users` u ON fa.`openid`=u.`openid`")
            ->where($where)
            ->count();// 查询满足要求的总记录数
        // 实例化分页类 传入总记录数和每页显示的记录数($l)
        $Page = new \Think\Page($count, $l);
        $show = $Page->show();// 分页显示输出
        $list = M("fundApply")
            ->join("fa LEFT JOIN `am_users` u ON fa.`openid`=u.`openid`")
            ->where($where)
            ->field("fa.*,u.`name`,u.`mobile`")
            ->order($order)
            ->limit($Page->firstRow . ',' . $Page->listRows)
            ->select();
        $this->assign('page', $show);// 赋值分页输出
        // 定义变量并显示模板
        $this->assign("list", $list);
        $this->display("applyList");die;
    }

    /**
     * 一键提现
     */
    public function permitAll()
    {
        auth_check("permit_opt");
        // 脱离浏览器运行
        ignore_user_abort(true);
        set_time_limit(0);
        // 分批打款, 每批 200 条申请记录, 用旗帜标识, 旗帜倒下循环结束
        $flag = true;
        while ($flag) {
            // 未打款的提现申请
            $list = M("fundApply")->where("`status`=1")->limit(200)->select();
            $len = count($list);
            if (is_array($list) && $len > 0) {
                foreach ($list as $key => $value) {
                    // 进行付款操作
                    $this->payForOneOrder($value);
                }
            }
            unset($key, $value);
            echo "本批打款完成<br/>";
            // 剩余未打款的申请数量
            $count = M("fundApply")->where("`status`=1")->count();
            if ($count > 0) {
                // 继续打款
                $flag = true;
            } else {
                // 打款结束
                $flag = false;
            }
        }
        alertMsg("一键提现已完成！", U("applyList"));
    }

    /**
     * 为单个提现申请付款    仅本控制器可使用
     * $data    am_fund_apply 表的单条记录
     */
    protected function payForOneOrder($data)
    {
        $id = $data['id'];
        if (!$id) {
            alertMsg("无法获取提现订单", U("applyList"));
        } else {
            $partner_trade_no = $data['partner_trade_no'];
            $openid = $data['openid'];
            $amount = intval($data['money'] * 100);
            $EP = new \EnterprisePayment();
            $EP->setParameter("partner_trade_no", $partner_trade_no);
            $EP->setParameter("openid", $openid);
            $EP->setParameter("amount", $amount);
            $payResult = $EP->getResult();
            if ($payResult['result_code'] == "SUCCESS") {
                $result = D("FundApply")->paySuccess($id, $payResult['payment_no']);
                if ($result) {
                    // $data['money'] 为乘100前的元单位金额, $amount 为乘100后的分单位金额
                    D("Users")->takeFund($openid, $data['money'], $partner_trade_no, $payResult['payment_no']);    // 操作用户的佣金账户
                    echo "提现申请{$partner_trade_no}付款成功<br/>";
                } else {
                    echo "提现申请{$partner_trade_no}已付款<br/>";
                }
                unset($EP);    // 删除对象变量, 对象失去指向变量进而析构, 释放内存
            } elseif ($payResult['return_code'] == "SUCCESS") {
                alertMsg($payResult['err_code_des'], U("applyList"));
            } else {
                alertMsg($payResult['return_msg'], U("applyList"));
            }
        }
    }

    /**
     * 驳回 提现申请
     */
    public function applyBack()
    {
        auth_check("permit_opt");
        $id = $_POST['id'];
        $data = array(
            "status" => -1,
            "reason" => I("reason")
        );
        $row = M("fundApply")->where("`id`={$id}")->find();
        // 修改记录状态
        $result = M("fundApply")->where("`id`={$id}")->save($data);
        if ($result) {
            // 佣金补回用户可提现账户
            M("users")->where("`openid`='{$row['openid']}'")->lock()->setInc("fund_enable", $row['money']);
        }
        $this->redirect("applyList");die;
    }
    
    /**
     * 佣金设置
     */
    public function distribution()
    {
        auth_check("permit_opt");
        if (IS_POST) {
            // 提交表单
            $result = D("SetFund")->saveForm(I());
            alertMsg("修改成功", U("distribution"));
        }
        // 表单页面
        $info = M("setFund")->find();
        $this->assign("info", $info);
        $this->display("distribution");die;
    }
}