<?php
namespace Api\Controller;

use Think\Controller;

header("Content-Type:text/html;CharSet=UTF-8");
class RefundController extends Controller
{
    /**
     * 村管理员不通过
     */
    public function reject()
    {
        $id = $_GET['id'];    // 商品副表ID
        if (!$id || $id == "undefined" || $id == "null" || !is_numeric($id)) {
            $data = array("status" => -1, "msg" => "商品副表记录ID有误");
        } else {
            $saveData = array(
                "refund_status" => -1
            );
            $result = M("orderGood")->where("`id`={$id}")->save($saveData);
            if (!$result) {
                $data = array("status" => -1, "msg" => "系统繁忙");
            } else {
                $orderGoodInfo = M("orderGood")->where("`id`={$id}")->find();
                $order_id = $orderGoodInfo['order_id'];
                $out_refund_no = $orderGoodInfo['out_refund_no'];
                $reason = $orderGoodInfo['reason'];
                $orderInfo = M("order")->where("`id`={$order_id}")->find();
                $prepay_id = $orderInfo['prepay_id'];
                $openid = $orderInfo['openid'];
                $str = "感谢您的惠顾";
                // 发送模板消息
                vendor("WxPayPubHelper.WxPlugin");
                $WxPlugin = new \WxPlugin();
                $params['form_id'] = $prepay_id;
                $params['touser'] = $openid;
                $params['template_id'] = "Sse96UtkKyu6q326k-g5ziNugTOMDy24w4y3bgPV5P0";
                $params['data'] = array(
                    "keyword1" => array("value" => "退换货审核失败", "color" => "#000000"),
                    "keyword2" => array("value" => $out_refund_no, "color" => "#000000"),
                    "keyword3" => array("value" => $str, "color" => "#000000")
                );
                $result = $WxPlugin->XcxSend($params);
                if ($result['status'] == -1) {
                    file_put_contents("./Logs/reject.log", JSON($result), FILE_APPEND);
                }
                $data = array("status" => 1, "msg" => "操作成功");
            }
        }
        apiReturn($data);
    }

    /**
     * 村管理员审核通过
     */
    public function villagePass()
    {
        $id = $_GET['id'];    // 商品副表ID
        if (!$id || $id == "undefined" || $id == "null" || !is_numeric($id)) {
            $data = array("status" => -1, "msg" => "商品副表记录ID有误");
        } else {
            // 查看商品是否需要后台审核
            $orderGoodInfo = M("orderGood")->where("`id`={$id}")->find();
            $good_id = $orderGoodInfo['good_id'];
            $goodInfo = M("goods")->where("`id`={$good_id}")->find();
            $audit_neet = $goodInfo['audit_neet'];    // 退货是否需要总后台审核  1.需要 -1.不需要
            if ($audit_neet == 1) {
                // 需要后台审核, 剩下工作由后台完成
                $result = M("orderGood")->where("`id`={$id}")->setField("refund_status", 3);
            } else {
                // 不需要后台审核, 完成所有退换货工作
                $result = M("orderGood")->where("`id`={$id}")->setField("refund_status", 4);
                if ($result) {
                    // 生成退款记录, 用于退款
                    $addData = array(
                        "order_good_id" => $id,
                        "create_time" => $_SERVER['REQUEST_TIME']
                    );
                    M("refund")->add($addData);
                }
            }
            if (!$result) {
                $data = array("status" => -1, "msg" => "系统繁忙");
            } else {
                $data = array("status" => 1, "msg" => "操作成功");
            }
        }
        apiReturn($data);
    }

    /**
     * 组管理员收货
     */
    public function groupGet()
    {
        $id = $_GET['id'];    // 商品副表ID
        if (!$id || $id == "undefined" || $id == "null" || !is_numeric($id)) {
            $data = array("status" => -1, "msg" => "商品副表记录ID有误");
        } else {
            $result = M("orderGood")->where("`id`={$id}")->setField("refund_status", 5);
            if (!$result) {
                $data = array("status" => -1, "msg" => "系统繁忙");
            } else {
                $data = array("status" => 1, "msg" => "操作成功");
            }
        }
        apiReturn($data);
    }

    /**
     * 村管理员收货
     */
    public function villageGet()
    {
        $id = $_GET['id'];    // 商品副表ID
        if (!$id || $id == "undefined" || $id == "null" || !is_numeric($id)) {
            $data = array("status" => -1, "msg" => "商品副表记录ID有误");
        } else {
            $result = M("orderGood")->where("`id`={$id}")->setField("refund_status", 6);
            if (!$result) {
                $data = array("status" => -1, "msg" => "系统繁忙");
            } else {
                $status = M("refund")->where("`order_good_id`={$id}")->getField("status");
                if ($status == 2) {
                    $data = array("status" => -1, "msg" => "该商品已退款");
                } else {
                    $saveData = array("refund_time" => time(), "status" => 2);
                    $result = M("refund")->where("`order_good_id`={$id}")->save($saveData);
                    if ($result) {
                        // 查询退款单
                        $row = M("refund")
                            ->join("r LEFT JOIN `am_order_good` og ON r.`order_good_id` = og.`id`")
                            ->join("LEFT JOIN `am_users` u ON og.`openid` = u.`openid`")
                            ->join("LEFT JOIN `am_goods` g ON og.`good_id` = g.`id`")
                            ->join("LEFT JOIN `am_order` o ON og.`order_id` = o.`id`")
                            ->field("r.`id`,r.`status`,r.`create_time`,r.`order_good_id`,og.`out_refund_no`,u.`nickname`,g.`goods_name`,og.`order_id`,og.`good_id`,og.`num`,og.`unit_price`,og.`kind_price`,og.`refund_type`,o.*")
                            ->where("r.`order_good_id`={$id}")
                            ->find();
                        // 商品副表记录 状态改为 已退款
                        M("orderGood")->where("`id`={$row['order_good_id']}")->setField("refund_status", 6);
                        $refund_type = $row['refund_type'];    // 1.换货 2.退货
                        if ($refund_type == 1) {
                            // 换货, 库存不需要变化, 自动生成新的 已支付、佣金已解冻 的订单, 不退款
                            $newOrderSn = "SN{$id}" . date("YmdHis");
                            $addData = array(
                                "openid" => $row['openid'],
                                "order_sn" => $newOrderSn,
                                "village_id" => $row['village_id'],
                                "type" => 2,
                                "total_fee" => $row['kind_price'],
                                "name" => $row['name'],
                                "tel" => $row['tel'],
                                "address" => $row['address'],
                                "group_openid" => $row['group_openid'],
                                "prepay_id" => $row['prepay_id'],
                                "form_id_create" => $row['form_id_back'],
                                "status" => 2,
                                "dtb_status" => 2,    // 佣金状态设为已解冻, 避免重复抽佣
                                "create_time" => time(),
                                "pay_time" => time()
                            );
                            $newOrderId = M("order")->add($addData);
                            // 查看商品的总仓库库存
                            $good_id = $row['good_id'];    // 商品ID
                            // 总仓库库存
                            $storage = M("goodsStorage")->where("`good_id`={$good_id}")->getField("storage");
                            // 购买数量
                            $num = $row['num'];
                            if ($storage >= $num) {
                                // 库存充足
                                $addData = array(
                                    "order_id" => $newOrderId,
                                    "storage_status" => 1,
                                    "smi_sn" => "{$newOrderSn}_1",
                                    "status" => 2
                                );
                            } else {
                                // 库存不足
                                $addData = array(
                                    "order_id" => $newOrderId,
                                    "storage_status" => 2,
                                    "smi_sn" => "{$newOrderSn}_2",
                                    "status" => 2
                                );
                            }
                            $newSmiId = M("orderSmi")->add($addData);
                            if ($newSmiId) {
                                // 计算预计送达时间
                                $village_expect = M("goodsVillageSet")->where("`village_id`={$row['village_id']} AND `good_id`={$good_id}")->getField("expect_time");    // 该商品 在该村的预计送达天数
                                if (!$village_expect) {
                                    $village_expect = M("goods")->where("`id`={$good_id}")->getField("village_expect");    // 该商品 分仓库预计送达天数
                                    if (!$village_expect) {
                                        $set = M("setElse")->find();
                                        // 统一设置的预计送达时间
                                        if ($set['sure_get'] > 0) {
                                            $village_expect = $set['sure_get'];
                                        } else {
                                            $village_expect = 0;
                                        }
                                    }
                                }
                                $expect_time = $_SERVER['REQUEST_TIME'] + $village_expect * 24 * 60 * 60;    // 预计送达时间
                                $hour = intval(date("H"));    // 当前时间小时单位
                                if ($hour > 21) {
                                    // 晚上 9点后 下单, 预计送达时间 增加 24小时
                                    $expect_time += 24 * 60 * 60;
                                }
                                // 新建商品副表
                                $addData = array(
                                    "openid" => $row['openid'],
                                    "order_id" => $newOrderId,
                                    "smi_id" => $newSmiId,
                                    "good_id" => $good_id,
                                    "num" => $num,
                                    "unit_price" => $row['unit_price'],
                                    "kind_price" => $row['kind_price'],
                                    "expect_time" => $expect_time
                                );
                                M("orderGood")->add($addData);
                            }
                            $data = array("status" => 1, "msg" => "操作成功");
                        } elseif ($refund_type == 2) {
                            // 退货, 库存需要补回, 不生成新订单, 退款
                            // 总仓库库存补回
                            $result = M("goodsStorage")->where("`village_id`=0 AND `good_id`={$row['good_id']}")->lock()->setInc("storage", $row['num']);
                            if ($result) {
                                // 总仓库入库记录
                                $addData = array(
                                    "choice" => 2,
                                    "type" => 6,
                                    "order_id" => $row['order_id'],
                                    "dinner_id" => 0,
                                    "good_id" => $row['good_id'],
                                    "change_num" => $row['num'],
                                    "create_time" => time()
                                );
                                M("storageTotal")->add($addData);
                                // 商品销量回减
                                M("goods")->where("`id`={$row['good_id']}")->lock()->setDec("sales_volume", $row['num']);
                                // 该商品&订单对应的 佣金删除 (若已过解冻时限, 则佣金已入受益用户的可提现账户)
                                M("fundLog")->where("`order_id`={$row['order_id']} AND `good_id`={$row['good_id']}")->delete();
                            }
                            //引入WxPayPubHelper
                            vendor('WxPayPubHelper.WxPayPubHelper');
                            // 模板消息类 (小程序)
                            vendor("WxPayPubHelper.WxPlugin");
                            // 退款
                            $Refund = new \Refund_pub();
                            $Refund->setParameter("out_trade_no", $row['order_sn']);
                            $Refund->setParameter("out_refund_no", $row['out_refund_no']);
                            $Refund->setParameter("total_fee", intval($row['total_fee'] * 100));
                            $Refund->setParameter("refund_fee", intval($row['kind_price'] * 100));
                            $Refund->setParameter("op_user_id", \WxPayConf_pub::MCHID);
                            $refundRes = $Refund->getResult();
                            file_put_contents("./Logs/refund.log", serialize($refundRes));
                            if ($refundRes['result_code'] == "SUCCESS") {
                                // 发送模板消息
                                $WxPlugin = new \WxPlugin();
                                $params['form_id'] = $row['prepay_id'];
                                $params['touser'] = $row['openid'];
                                $params['template_id'] = "Sse96UtkKyu6q326k-g5ziNugTOMDy24w4y3bgPV5P0";
                                $params['data'] = array(
                                    "keyword1" => array("value" => "退款成功", "color" => "#000000"),
                                    "keyword2" => array("value" => $row['out_refund_no'], "color" => "#000000"),
                                    "keyword3" => array("value" => "支付款已按原路退到帐号上，请查收", "color" => "#000000")
                                );
                                $result = $WxPlugin->XcxSend($params);
                                if ($result['status'] == -1) {
                                    file_put_contents("./Logs/reject.log", JSON($result) . "\r\n\r\n", FILE_APPEND);
                                }
                                $data = array("status" => 1, "msg" => "操作成功");
                            } elseif ($refundRes['return_code'] == "SUCCESS") {
                                $data = array("status" => -1, "msg" => "{$refundRes['err_code_des']}");
                            } else {
                                $data = array("status" => -1, "msg" => "退款异常，错误码：{$refundRes['return_msg']}");
                            }
                        }
                    } else {
                        file_put_contents("./Logs/refund.log", "{$row['out_refund_no']}退款异常：" . M("refund")->getlastsql() . "\r\nresult:" . serialize($result) . "\r\n\r\n", FILE_APPEND);
                    }
                }
            }
        }
        apiReturn($data);
    }

    /**
     * 退换货订单列表 村管理
     */
    public function villageList()
    {
        $village_id = $_GET['village_id'];    // 村ID
        if (!$village_id || $village_id == "undefined" || $village_id == "null" || !is_numeric($village_id)) {
            $data = array("status" => -1, "msg" => "村ID有误");
        } else {
            $list = M("orderGood")
                ->join("og LEFT JOIN `am_order` o ON og.`order_id`=o.`id`")
                ->join("LEFT JOIN `am_goods` g ON og.`good_id`=g.`id`")
                ->join("LEFT JOIN `am_users` grouper ON o.`group_openid`=grouper.`openid`")
                ->where("og.`refund_status`>1 AND og.`refund_status` < 6 AND o.`village_id`={$village_id}")
                ->field("og.`id`,og.`out_refund_no`,og.`num`,og.`refund_status`,og.`refund_type`,o.`create_time`,g.`goods_name`,g.`goods_price`,g.`thumb`,g.`des`,grouper.`name` AS `group_name`")
                ->order("og.`refund_time` DESC")
                ->select();
            foreach ($list as $kl => $vl) {
                if ($vl['create_time']) {
                    $list[$kl]['create_time'] = date("Y-m-d H:i", $vl['create_time']);
                }
                $list[$kl]['thumb'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/{$vl['thumb']}";
            }
            unset($kl, $vl);
            if (!$list) {
                $list = array();
            }
            $data = array("status" => 1, "result" => $list);
        }
        apiReturn($data);
    }

    /**
     * 退换货订单详情 村管理
     */
    public function villageDetail()
    {
        $id = $_GET['id'];    // 商品副表记录ID
        if (!$id || $id == "undefined" || $id == "null" || !is_numeric($id)) {
            $data = array("status" => -1, "msg" => "商品副表记录ID有误");
        } else {
            $info = M("orderGood")
                ->join("og LEFT JOIN `am_order` o ON og.`order_id`=o.`id`")
                ->join("LEFT JOIN `am_goods` g ON og.`good_id`=g.`id`")
                ->join("LEFT JOIN `am_order_smi` os ON og.`smi_id`=os.`id`")
                ->join("LEFT JOIN `am_users` grouper ON o.`group_openid`=grouper.`openid`")
                ->where("og.`id`={$id}")
                ->field("og.*,o.`create_time`,o.`name`,o.`tel`,o.`address`,o.`order_sn`,os.`get_time`,g.`goods_name`,g.`goods_price`,g.`thumb`,g.`des`,grouper.`name` AS `group_name`")
                ->find();
            if ($info['create_time']) {
                $info['create_time'] = date("Y-m-d H:i", $info['create_time']);
            }
            if ($info['get_time']) {
                $info['get_time'] = date("Y-m-d H:i", $info['get_time']);
            }
            if ($info['refund_time']) {
                $info['refund_time'] = date("Y-m-d H:i", $info['refund_time']);
            }
            $info['thumb'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/{$info['thumb']}";
            // 组管理员
            $group = M("users")->where("`openid`='{$order['group_openid']}'")->getField("name");
            // 商品
            $good = M("goods")->where("`id`={$info['good_id']}")->find();
            $thumb = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/" . $good['thumb'];
            $info['thumb'] = $thumb;
            $data = array("status" => 1, "result" => $info);
        }
        apiReturn($data);
    }

    /**
     * 退换货订单列表 组管理
     */
    public function groupList()
    {
        $openid = $_GET['openid'];    // 组管理员（当前用户）openid
        if (!$openid || $openid == "undefined" || $openid == "null") {
            $data = array("status" => -1, "msg" => "openid有误");
        } else {
            $list = M("orderGood")
                ->join("og LEFT JOIN `am_order` o ON og.`order_id`=o.`id`")
                ->join("LEFT JOIN `am_goods` g ON og.`good_id`=g.`id`")
                ->join("LEFT JOIN `am_users` grouper ON o.`group_openid`=grouper.`openid`")
                ->where("og.`refund_status`>3 AND og.`refund_status` < 6 AND o.`group_openid`='{$openid}'")
                ->field("og.`id`,og.`out_refund_no`,og.`num`,og.`refund_status`,og.`refund_type`,o.`create_time`,g.`goods_name`,g.`goods_price`,g.`thumb`,g.`des`,grouper.`name` AS `group_name`")
                ->order("og.`refund_time` DESC")
                ->select();
            foreach ($list as $kl => $vl) {
                if ($vl['create_time']) {
                    $list[$kl]['create_time'] = date("Y-m-d H:i", $vl['create_time']);
                }
                $list[$kl]['thumb'] = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/{$vl['thumb']}";
            }
            unset($kl, $vl);
            if (!$list) {
                $list = array();
            }
            $data = array("status" => 1, "result" => $list);
        }
        apiReturn($data);
    }

    /**
     * 退换货订单详情 组管理
     */
    public function groupDetail()
    {
        $id = $_GET['id'];    // 商品副表记录ID
        if (!$id || $id == "undefined" || $id == "null" || !is_numeric($id)) {
            $data = array("status" => -1, "msg" => "商品副表记录ID有误");
        } else {
            $info = M("orderGood")
                ->join("og LEFT JOIN `am_order` o ON og.`order_id`=o.`id`")
                ->where("og.`id`={$id}")
                ->field("og.`id`,og.`order_id`,og.`num`,og.`good_id`,og.`out_refund_no` AS `sn`,og.`refund_status` AS `status`")
                ->select();
            // 订单信息
            $order = M("order")->where("`id`={$info['order_id']}")->find();
            // 商品
            $good = M("goods")->where("`id`={$info['good_id']}")->find();
            $thumb = "http://" . $_SERVER['HTTP_HOST'] . __ROOT__ . "/Uploads/" . $good['thumb'];
            $result = array(
                "id" => $info['id'],
                "sn" => $info['sn'],
                "status" => $info['status'],
                "name" => $order['name'],
                "tel" => $order['tel'],
                "address" => $order['address'],
                "goods" => array(
                    array(
                        "id" => $info['good_id'],
                        "num" => $info['num'],
                        "goods_name" => $good['goods_name'],
                        "thumb" => $thumb
                    )
                )
            );
            $data = array("status" => 1, "result" => $result);
        }
        apiReturn($data);
    }
}