<?php

namespace app\admin\controller;

use app\admin\controller\AuthBase;
use app\common\model\Refund;
use app\common\utils\WXSendMessage;
use think\Db;
use think\Exception;
use think\Loader;


Loader::import('wxpay.Api');

class Order extends AuthBase
{
    protected $order_model;

    public function _initialize()
    {
        parent::_initialize();
        $this->order_model = model('Order');
    }

    //订单列表
    public function index()
    {
        //搜索筛选
        $status     = input('get.status', '-1');
        $id         = input('get.id');
        $start_time = input('get.start_time');
        $end_time   = input('get.end_time');
        $type       = input('get.type');
        $condition  = [];

        //判断如果存在筛选字段，将其添加到筛选数组$condition中
        if ($status != '-1') {
            $condition['status'] = $status;
        }
        if ($id) {
            $condition['id'] = $id;
        }
        if ($type) {
            $condition['type'] = $type;
        }
        if ($start_time && $end_time) {
            $condition['created_at'] = ['between', [$start_time . ' 00:00:00', $end_time . ' 00:00:00']];
        } else {
            if ($start_time) {
                $condition['created_at'] = ['>', $start_time . ' 00:00:00'];
            } elseif ($end_time) {
                $condition['created_at'] = ['<', $end_time . ' 00:00:00'];
            }
        }
        if(input('get.title')){
            $condition['title'] = ['like','%'.input('get.title').'%'];
        }
        //根据筛选条件查询
        $order_list = $this->order_model->with(['project' => function ($query) {

        }])->where($condition)->order('created_at desc')->paginate(10, false, ['query' => ['status' => $status, 'start_time' => $start_time, 'end_time' => $end_time, 'type' => $type]])->each(function ($item) {
            $project                = \app\common\model\Project::withTrashed()->find($item['pid']);
            $item['project_poster'] = $project['poster'];
            $item['project_title']  = $project['title'];
        });
        $this->assign("order_list", $order_list);
        $this->assign("status", $status);
        return $this->fetch();
    }

    //订单表导出
    public function orderOutput()
    {
        //根据筛选条件查询数据
        $status     = input('get.status', '-1');
        $start_time = input('get.start_time');
        $end_time   = input('get.end_time');
        $type       = input('get.type');
        $condition  = [];
        if ($status != '-1') {
            $condition['status'] = $status;
        }
        if ($type) {
            $condition['type'] = $type;
        }
        if ($start_time && $end_time) {
            $condition['created_at'] = ['between', [$start_time . ' 00:00:00', $end_time . ' 00:00:00']];
        } else {
            if ($start_time) {
                $condition['created_at'] = ['>', $start_time . ' 00:00:00'];
            } elseif ($end_time) {
                $condition['created_at'] = ['<', $end_time . ' 00:00:00'];
            }
        }
        $order_list = $this->order_model->where($condition)->order('created_at desc')->select();
        //导出用户信息、活动信息、订单信息，如：姓名、手机号、活动名称、价格、家庭组数、大人数量、孩子数量、孩子年龄、备注等
        //导出到excel之前数据处理
        $mulit_arr         = [];
        $mulit_arr['data'] = [];
        $cont              = [['订单标题', '订单来源', '用户名', '电话', 'vip购买信息', '活动名称', '活动价格', '家庭组数', '大人数量', '孩子数量', '孩子年龄', '订单总价', '下单时间', '订单状态']];
        foreach ($order_list as $vo) {
            $arr   = [];
            $arr[] = $vo['title'];
            $arr[] = $vo['type'] == 1 ? '活动报名' : '购买会员卡订单';
            $arr[] = $vo->user_info['nickname'];
            $arr[] = $vo->user_info['phone'];
            $arr[] = isset($vo['extras']['vip_endtime']) ? $vo['extras']['vip_endtime'] . '到期' : '';
            $arr[] = $vo->project['title'];
            $arr[] = $vo->project['price'];
            $arr[] = isset($vo['extras']['sign_limits']) ? $vo['extras']['sign_limits'] : '';
            $arr[] = isset($vo['extras']['adult_number']) ? $vo['extras']['adult_number'] : '';
            $arr[] = isset($vo['extras']['children_number']) ? $vo['extras']['children_number'] : '';
            $arr[] = isset($vo['extras']['children_age']) ? $vo['extras']['children_age'] : '';
            $arr[] = $vo['total_fee'];
            $arr[] = $vo['created_at'];
            $arr[] = $vo->status_text;

            $cont[] = $arr;
        }
        $mulit_arr['data'][] = $cont;
        $mulit_arr['sheet']  = [['title' => '用户信息表']];
        $title               = '订单表';//这是标题
        $Subject             = '';//这是备注
        $Description         = '美行者订单导出';//这是描述;
        $Keywords            = '';//这是关键字
        $Category            = '';//这是分类
        $filename            = '美行者订单导出';//文件名
        $obj                 = new OutputExcel();
        /*调用excle导出类*/
        $obj->export($mulit_arr, $filename, $title, $Subject, $Description, $Keywords, $Category);
    }

    //退款审核 未完成
    public function refund()
    {
        $id        = input('get.id');
        $status    = input('get.status', '-1');
        $condition = [];
        if ($status != '-1') {
            $condition['status'] = $status;
        }
        if ($id) {
            $condition['id'] = $id;
        }
        $refund_list = model('Refund')->where($condition)->order('created_at desc')->paginate(10, false, ['query' => ['status' => $status]]);
        $this->assign('status', $status);
        $this->assign('refund_list', $refund_list);
        return $this->fetch();
    }

    //评论审核
    public function comment()
    {
        $id        = input('get.id');
        $status    = input('get.status', '-1');
        $condition = [];
        if ($status != '-1') {
            $condition['status'] = $status;
        }
        if ($id) {
            $condition['id'] = $id;
        }
        $comment_list = model('comment')->where($condition)->order('created_at desc')->paginate(10, false, ['query' => ['status' => $status]]);
        $this->assign('status', $status);
        $this->assign('comment_list', $comment_list);
        return $this->fetch();
    }

    public function commentStatus($status, $id)
    {
        $comment_model = model('comment');
        $res           = $comment_model->save(['status' => $status], ['id' => $id]);
        if ($status == 2) {
            $is_comment = 3;
        } elseif ($status == 3) {
            $is_comment = 2;
        }
        $status_str = array(
            '2' => '请求成功，已审核通过该评论',
            '3' => '请求成功，该评论审核不通过'
        );
        if ($res) {
            $comment_info = $comment_model->get($id);
            if ($comment_info) {
                $save_condition               = [];
                $save_condition['is_comment'] = $is_comment;
                $order_info                   = model('order')->get($comment_info['order_id']);
                if ($status == 2) {
                    //评论审核成功
                    //如果订单状态为待评价，则修改状态为已完成
                    if ($order_info['status'] == config('order_status.wait_comment')) {
                        $save_condition['status'] = config('order_status.complete');
                    };
                } elseif ($status == 3) {
                    //评论审核失败
                    if ($order_info['status'] == config('order_status.complete')) {
                        $save_condition['status'] = config('order_status.wait_comment');
                    }
                }

                $set_order_res = model('order')->save($save_condition, ['id' => $comment_info['order_id']]);
            }
            $this->success($status_str[$status]);
        } else {
            $this->error('修改失败，本次审核无效');

        }
    }

    public function refundStatus($status, $id)
    {
        $refund_model = model('refund');
        $res          = $refund_model->save(['status' => $status], ['id' => $id]);
        if ($status == 2) {
            $is_refund = 3;
        } elseif ($status == 3) {
            $is_refund = 2;
        }
        $status_str = array(
            '2' => '请求成功，已退款',
            '3' => '请求成功，已驳回该退款申请'
        );
        if ($res) {
            $refund_info = $refund_model->get($id);
            if ($refund_info) {
                $set_order_res = model('order')->save(['is_refund' => $is_refund], ['id' => $refund_info['order_id']]);
            }
            $this->success($status_str[$status]);
        } else {
            $this->error('修改失败，本次审核无效');
        }
    }


    //申请退款
    public function passRefund()
    {
        // //获取该订单
        $refund = Refund::get([
            'id'     => input('post.id', 0),
            'status' => 1
        ]);
        if (!$refund) {
            return json(['code' => 1, 'msg' => '退款异常,请刷新页面重试!']);
        }
        $order = \app\common\model\Order::get($refund->order_id);
        Db::startTrans();
        try {
            //修改订单状态
            $refund->status    = 2;
            $order->is_refund  = 3;
            $order->status     = 3;
            $project           = \app\common\model\Project::get($order->pid);
            $project->sign_num = $project->sign_num - $order['extras']['sign_limits'];
            $refund->save();//修改退款列表状态
            $order->save();//修改订单状态
            $project->save();//减少限制数组量

            //微信退款
            $input = new \WxPayRefund();
            $input->SetOut_trade_no($order['out_trade_no']);
            $input->SetTotal_fee($order['total_fee'] * 100);
            $input->SetRefund_fee($order['total_fee'] * 100);

            $config = new \WxPayConfig();
            $input->SetOut_refund_no("sdkphp" . date("YmdHis"));
            $input->SetOp_user_id($config->GetMerchantId());
            $result = \WxPayApi::refund($config, $input);
            if ($result['return_code'] == 'SUCCESS') {
                Db::commit();

                //发送消息模板
                $openId      = \app\common\model\User::get($order->uid)['openid'];
                $template_id = config('wxapp.template_id_refund');
                $page        = config('wxapp.page');
                $form_id     = $order->prepay_id;
                $param       = [
                    $order->out_trade_no,
                    $order->title,
                    $order->total_fee,
                    date('Y-m-d H:i:s')
                ];
                WXSendMessage::send_template_notice($openId, $template_id, $page, $form_id, $param);

                return json(['code' => 0, 'msg' => '退款成功']);
            } else {
                throw new Exception($result['return_msg']);
            }
        } catch (Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }

    }

    //驳回
    public function noPassRefund()
    {
        $refund = Refund::get([
            'id'     => input('post.id', 0),
            'status' => 1
        ]);
        if (!$refund) {
            return ['code' => 1, 'msg' => '退款异常,请刷新页面重试!'];
        }
        $refund->status = 3;
        $refund->save();
        $order            = \app\common\model\Order::get($refund->order_id);
        $order->is_refund = 2;
        $order->save();
        return ['code' => 0, 'msg' => '驳回成功'];
    }
}
