<?php
namespace Smi\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class CrontabController extends Controller
{
    /**
     * 解冻订单佣金
     */
    public function thawFunds()
    {
        // 读取设置中的解冻时间
        $row = M("setFund")->find();
        $unlockTime = $row['unlock_time'];
        if (!is_numeric($unlockTime)) $unlockTime = 1;
        $daysBefore = $unlockTime - 1;
        if ($daysBefore < 0) $daysBefore = 0;
        // $daysBefore 天前凌晨0点时间戳 (每天凌晨00:00访问此方法)
        if ($daysBefore === 0) {
            $judgeTime = time();
        } elseif ($daysBefore === 1) {
            $judgeTime = strtotime("-1 day");
        } else {
            $judgeTime = strtotime("-{$daysBefore} days");
        }
        $time = date("Y-m-d H:i:s ");
        file_put_contents("./Logs/Crontab/thawFunds.log", "START: " . $time . "\r\n", FILE_APPEND);
        // 列出 $daysBefore 天前 完成 且 未退款/退货 的订单 (status=5)
        $orderList = M("order")->where("`finish_time` < {$judgeTime} AND `status` = 5 AND `dtb_status` = 1")->select();
        $log = serialize($orderList);
        dump($orderList);
        file_put_contents("./Logs/Crontab/thawFunds.log", M("order")->getlastsql() . "\r\n", FILE_APPEND);
        // 循环订单列表
        if ($orderList) {
            foreach ($orderList as $k => $v) {
                // 订单佣金状态改为解冻 (dtb_status=2)
                $result = M("order")->where("`id` = {$v['id']}")->setField("dtb_status", 2);
                $log = "order-id: " . $v['id'];
                dump($result);
                file_put_contents("./Logs/Crontab/thawFunds.log", M("order")->getlastsql() . "\r\n", FILE_APPEND);
                // 该订单产生的所有佣金记录 状态改为解冻 (status=2)
                $result = M("fundLog")->where("`orderid` = {$v['id']}")->setField("status", 2);
                $log = "benefits-Update: " . $result;
                dump($result);
                file_put_contents("./Logs/Crontab/thawFunds.log", M("benefits")->getlastsql() . "\r\n", FILE_APPEND);
                // 佣金记录所属用户 可提现佣金增加
                $benefitList = M("fundLog")->where("`orderid` = {$v['id']}")->select();
                echo M("fundLog")->getlastsql();
                dump($benefitList);
                foreach ($benefitList as $key => $value) {
                    $openid = $value['openid'];
                    $money = $value['benefit'];
                    $result = D("Api/Users")->makeFund($openid, $money);
                    dump($result);
                }
                unset($userList);
            }
        }
        file_put_contents("./Logs/Crontab/thawFunds.log", "END\r\n\r\n", FILE_APPEND);
    }

    /**
     * 解冻宴席佣金
     */
    public function dinnerFunds()
    {
        // 读取设置中的解冻时间
        $row = M("setFund")->find();
        $unlockTime = $row['unlock_time'];
        if (!is_numeric($unlockTime)) $unlockTime = 1;
        $daysBefore = $unlockTime - 1;
        if ($daysBefore < 0) $daysBefore = 0;
        // $daysBefore 天前凌晨0点时间戳 (每天凌晨00:00访问此方法)
        if ($daysBefore === 0) {
            $judgeTime = time();
        } elseif ($daysBefore === 1) {
            $judgeTime = strtotime("-1 day");
        } else {
            $judgeTime = strtotime("-{$daysBefore} days");
        }
        $time = date("Y-m-d H:i:s ");
        file_put_contents("./Logs/Crontab/dinnerFunds.log", "START: " . $time . "\r\n", FILE_APPEND);
        // 列出 $daysBefore 天前的宴席佣金记录 (type=2)
        $list = M("fundLog")->where("`create_time`<{$judgeTime} AND `type`=2")->select();
        dump($list);
        file_put_contents("./Logs/Crontab/dinnerFunds.log", M("fundLog")->getlastsql() . "\r\n", FILE_APPEND);
        // 循环佣金记录
        foreach ($list as $key => $value) {
            $openid = $value['openid'];    // 佣金记录的受益人 openid
            $money = $value['benefit'];    // 佣金记录金额
            $result = D("Api/Users")->makeFund($openid, $money);    // 受益人可提佣金增加
            dump($result);
            $result = M("fundLog")->where("`id` = {$value['id']}")->setField("status", 2);    // 佣金记录解冻
            echo M("fundLog")->getlastsql();
            dump($result);
        }
        echo "FINISHED";
        file_put_contents("./Logs/Crontab/dinnerFunds.log", "END\r\n\r\n", FILE_APPEND);
    }

    /**
     * 清理过期 未付款/取消 订单
     */
    public function clearOrders()
    {
        file_put_contents("./Logs/Crontab/clearOrders.log", "START: " . date("Y-m-d H:i:s ") . "\r\n", FILE_APPEND);
        // 上一天凌晨 00:00 的时间戳 (每天凌晨00:00访问此方法)
        $lastDay = strtotime("-1 day");
        // 过期订单ID
        $orderids = M("order")->where("(`status`=1 OR `status`=-1) AND `create_time` < {$lastDay}")->getField("id", true);
        $result = M("order")->where("(`status`=1 OR `status`=-1) AND `create_time` < {$lastDay}")->delete();
        file_put_contents("./Logs/Crontab/clearOrders.log", M("order")->getlastsql() . "\r\n", FILE_APPEND);
        file_put_contents("./Logs/Crontab/clearOrders.log", "Result: " . serialize($result) . "\r\n", FILE_APPEND);
        if ($result) {
            if (is_array($orderids) && count($orderids) > 0) {
                $orderids = implode(",", $orderids);
                if ($orderids) {
                    // 订单副表删除
                    $result = M("orderSmi")->where("`order_id` IN({$orderids})")->delete();
                    echo M("orderSmi")->getlastsql();
                    $result = M("orderGood")->where("`order_id` IN({$orderids})")->delete();
                    echo M("orderGood")->getlastsql();
                    file_put_contents("./Logs/Crontab/clearOrders.log", M("ordergood")->getlastsql() . "\r\n", FILE_APPEND);
                    file_put_contents("./Logs/Crontab/clearOrders.log", "Result: " . serialize($result) . "\r\n", FILE_APPEND);
                }
            }
        }
        dump($result);
        file_put_contents("./Logs/Crontab/clearOrders.log", "END\r\n\r\n", FILE_APPEND);
    }

    /**
     * 自动完成分订单 (2天)
     */
    public function orderFinish()
    {
        file_put_contents("./Logs/Crontab/orderFinish.log", "START: " . date("Y-m-d H:i:s ") . "\r\n", FILE_APPEND);
        // 计算临界时间戳 (2天前的凌晨00:00)
        $timeStamp = strtotime("-2 days");
        $drugeTime = mktime(0, 0, 0, date("m", $timeStamp), date("d", $timeStamp), date("Y", $timeStamp));
        // 临界时间前的分订单 (组管理员收货超2天)
        $orderSmiList = M("orderSmi")->where("`status`=4 AND `get_time`<{$drugeTime}")->select();
        file_put_contents("./Logs/Crontab/orderFinish.log", M("orderSmi")->getlastsql() . "\r\n", FILE_APPEND);
        foreach ($orderSmiList as $kosl => $vosl) {
            $id = $vosl['id'];
            $saveData = array(
                "status" => 5,
                "finish_time" => time()
            );
            $result = M("orderSmi")->where("`id`={$id}")->save($saveData);
            file_put_contents("./Logs/Crontab/orderFinish.log", M("orderSmi")->getlastsql() . "\r\n", FILE_APPEND);
            if ($result) {
                $flag = true;
                $row = M("orderSmi")->where("`id`={$id}")->find();
                file_put_contents("./Logs/Crontab/orderFinish.log", M("orderSmi")->getlastsql() . "\r\n", FILE_APPEND);
                $order_id = $row['order_id'];
                $village_id = $row['village_id'];
                $group_openid = $row['group_openid'];    // 组管理员openid
                $list = M("orderSmi")->where("`order_id`={$order_id}")->select();
                file_put_contents("./Logs/Crontab/orderFinish.log", M("orderSmi")->getlastsql() . "\r\n", FILE_APPEND);
                foreach ($list as $key => $value) {
                    $status = $value['status'];
                    if ($status < 5) {
                        $flag = false;
                        break;
                    }
                }
                unset($key, $value);
                if ($flag) {
                    // 订单下所有分订单已完成, 修改订单状态
                    $saveData = array(
                        "status" => 5,
                        "finish_time" => time()
                    );
                    M("order")->where("`id`={$order_id}")->save($saveData);
                    file_put_contents("./Logs/Crontab/orderFinish.log", M("order")->getlastsql() . "\r\n", FILE_APPEND);
                    $dtb_status = M("order")->where("`id`={$order_id}")->getField("dtb_status");
                    file_put_contents("./Logs/Crontab/orderFinish.log", M("order")->getlastsql() . "\r\n", FILE_APPEND);
                    if ($dtb_status == 1) {
                        // 这是正常订单, 产生佣金 (若此时 dtb_status == 2 则说明这是一条由换货产生的订单)
                        $goods = M("orderGood")
                            ->join("og LEFT JOIN `am_goods` g ON og.`good_id`=g.`id`")
                            ->where("og.`order_id`={$order_id}")
                            ->field("og.*,g.`is_self`,g.`village_percent`,g.`group_percent`")
                            ->select();
                        file_put_contents("./Logs/Crontab/orderFinish.log", M("orderGood")->getlastsql() . "\r\n", FILE_APPEND);
                        // 村管理员openid
                        $villager_openid = M("users")->where("`village_id`={$village_id} AND `identity`=2")->getField("openid");
                        file_put_contents("./Logs/Crontab/orderFinish.log", M("users")->getlastsql() . "\r\n", FILE_APPEND);
                        foreach ($goods as $key => $value) {
                            $refund_status = $value['refund_status'];
                            if ($refund_status > 3) {
                                // 该商品的退换货申请已通过后台审核, 不计算佣金, 跳至下一类商品
                                continue;
                            }
                            $is_self = $value['is_self'];
                            $good_id = $value['good_id'];
                            $kind_price = $value['kind_price'];
                            $village_percent = $value['village_percent'];
                            $group_percent = $value['group_percent'];
                            if ($is_self == 2) {
                                // 商品 设置了独立佣金比例, 以此计算 村、组管理员 的佣金
                                // 村管理员佣金
                                $addData = array(
                                    "type" => 1,
                                    "openid" => $villager_openid,
                                    "benefit" => $kind_price * $village_percent / 100,
                                    "order_id" => $order_id,
                                    "dinner_id" => 0,
                                    "good_id" => $good_id
                                );
                                M("fundLog")->add($addData);    // 产生佣金记录
                                file_put_contents("./Logs/Crontab/orderFinish.log", M("fundLog")->getlastsql() . "\r\n", FILE_APPEND);
                                // 组管理员佣金
                                $addData = array(
                                    "type" => 1,
                                    "openid" => $group_openid,
                                    "benefit" => $kind_price * $group_percent / 100,
                                    "order_id" => $order_id,
                                    "dinner_id" => 0,
                                    "good_id" => $good_id
                                );
                                M("fundLog")->add($addData);    // 产生佣金记录
                                file_put_contents("./Logs/Crontab/orderFinish.log", M("fundLog")->getlastsql() . "\r\n", FILE_APPEND);
                            } else {
                                $villageSet = M("regionVillage")->where("`id`={$village_id}")->find();
                                file_put_contents("./Logs/Crontab/orderFinish.log", M("regionVillage")->getlastsql() . "\r\n", FILE_APPEND);
                                $is_self = $villageSet['is_self'];
                                $village_percent = $villageSet['village_percent'];
                                $group_percent = $villageSet['group_percent'];
                                if ($is_self == 2) {
                                    // 村 设置了独立佣金比例, 以此计算 村、组管理员 的佣金
                                    // 村管理员佣金
                                    $addData = array(
                                        "type" => 1,
                                        "openid" => $villager_openid,
                                        "benefit" => $kind_price * $village_percent / 100,
                                        "order_id" => $order_id,
                                        "dinner_id" => 0,
                                        "good_id" => $good_id
                                    );
                                    M("fundLog")->add($addData);    // 产生佣金记录
                                    file_put_contents("./Logs/Crontab/orderFinish.log", M("fundLog")->getlastsql() . "\r\n", FILE_APPEND);
                                    // 组管理员佣金
                                    $addData = array(
                                        "type" => 1,
                                        "openid" => $group_openid,
                                        "benefit" => $kind_price * $group_percent / 100,
                                        "order_id" => $order_id,
                                        "dinner_id" => 0,
                                        "good_id" => $good_id
                                    );
                                    M("fundLog")->add($addData);    // 产生佣金记录
                                    file_put_contents("./Logs/Crontab/orderFinish.log", M("fundLog")->getlastsql() . "\r\n", FILE_APPEND);
                                } else {
                                    // 以后台设置的佣金比例计算 村、组管理员 的佣金
                                    $set = M("setFund")->find();
                                    $village_percent = $set['village_percent'];
                                    $group_percent = $set['group_percent'];
                                    // 村管理员佣金
                                    $addData = array(
                                        "type" => 1,
                                        "openid" => $villager_openid,
                                        "benefit" => $kind_price * $village_percent / 100,
                                        "order_id" => $order_id,
                                        "dinner_id" => 0,
                                        "good_id" => $good_id
                                    );
                                    M("fundLog")->add($addData);    // 产生佣金记录
                                    file_put_contents("./Logs/Crontab/orderFinish.log", M("fundLog")->getlastsql() . "\r\n", FILE_APPEND);
                                    // 组管理员佣金
                                    $addData = array(
                                        "type" => 1,
                                        "openid" => $group_openid,
                                        "benefit" => $kind_price * $group_percent / 100,
                                        "order_id" => $order_id,
                                        "dinner_id" => 0,
                                        "good_id" => $good_id
                                    );
                                    M("fundLog")->add($addData);    // 产生佣金记录
                                    file_put_contents("./Logs/Crontab/orderFinish.log", M("fundLog")->getlastsql() . "\r\n", FILE_APPEND);
                                }
                            }
                        }
                    }
                }
            }
        }
        file_put_contents("./Logs/Crontab/orderFinish.log", "END\r\n\r\n", FILE_APPEND);
    }
}