<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
/**
 * 订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    protected $noNeedLogin = ['xieyipdf'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("roadtypeList", $this->model->getRoadtypeList());
        $this->view->assign("jxtypeList", $this->model->getJxtypeList());
    }



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


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['product','usera','userb'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                
                $row->getRelation('product')->visible(['name']);
				$row->getRelation('usera')->visible(['nickname','mobile']);
				$row->getRelation('userb')->visible(['nickname','mobile']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 退款
     */
    public function refund(){
        $id = input('id',0);
        $row = Db::name('order')->where('id',$id)->find();

        if($this->request->isPost()){
            if($row['status'] != 21){
                $this->error('订单状态有误，请勿重复提交');
            }

            $refund_reason = input('refund_reason','');
            $refund_remark = input('refund_remark','');
            $refund_fee    = input('refund_fee',0);

            if($refund_fee > $row['pay_fee']){
                $this->error('退还金额不能大于实际支付金额'.$row['pay_fee']);
            }

            //更新订单
            $update = [
                'refund_reason' => $refund_reason,
                'refund_time'   => time(),
                'refund_remark' => $refund_remark,
                'refund_fee'    => $refund_fee,
                'status' => 22,
            ];
            Db::startTrans();
            $rs = Db::name('order')->where('id',$id)->update($update);
            if($rs === false){
                Db::rollback();
                $this->error('提交失败');
            }

            //车票还回去
            $order_id = $id;
            $order_road = Db::name('order_road')->where('order_id',$order_id)->lock(true)->select();
            foreach($order_road as $key => $road){
                $chufabanci = Db::name('product_chufabanci')->where('id',$road['chufabanci_id'])->lock(true)->find();
                if(empty($chufabanci)){
                    continue;
                }
                $update = [
                    'ticket_remain' => $chufabanci['ticket_remain'] + $road['ticket_number'],
                ];
                $rs_ticket = Db::name('product_chufabanci')->where('id',$road['chufabanci_id'])->update($update);
                if($rs_ticket === false){
                    Db::rollback();
                    $this->error('退回票失败');
                }
            }

            //
            if($refund_fee > 0){
                //退款
                $refund_result = $this->old_refund($row, 'order',$refund_fee,'订单申请退款');

                if($refund_result !== true){
                    Db::rollback();
                    $this->error($refund_result);
                }
            }

            Db::commit();
            $this->success('退款完成');
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    // 退款
    private function old_refund($order,$table, $refund_price,$remark = '')
    {
        $order['pay_type'] = 'wechat';

        // 生成退款单
        $refund_data = [
            'order_id' => $order['id'],
            'out_refund_no'=> createUniqueNo('R',$order['id']),
            'pay_fee'  => $order['pay_fee'],
            'refund_price' => $refund_price,
            'pay_type' => $order['pay_type'],
            'status' => 0,
            'createtime' => time(),
            'updatetime' => time(),
            'table' => $table,
            'table_id' => $order['id'],
        ];
        $refund_log_id = Db::name('order_refund_log')->insertGetId($refund_data);
        if(!$refund_log_id){
            return '退款失败';
        }

        if ($order['pay_type'] == 'wechat') {
            // 微信|支付宝退款

            // 退款数据
            $order_data = [
                'out_trade_no' => $order['pay_out_trade_no']
            ];

            if ($order['pay_type'] == 'wechat') {
                //$order['pay_fee'] = 0.01;//测试支付强制0.01元
                $total_fee = $order['pay_fee'] * 100;
                $refund_fee = $refund_price * 100;

                $order_data = array_merge($order_data, [
                    'out_refund_no' => $refund_data['out_refund_no'],
                    'total_fee' => $total_fee,
                    'refund_fee' => $refund_fee,
                    'refund_desc' => $remark,
                ]);
            }

            //
            if ($order['pay_type'] == 'wechat') {
                $wxpay = new \app\common\library\Wxpay;
                $result = $wxpay->WxPayRefund($order_data);
                // 微信通知回调 pay->notifyr
                if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                    Db::name('order_refund_log')->where('id',$refund_log_id)->update(['status'=>1]);
                    return true;
                } else {
                    return $result['return_msg'].'-'.$result['err_code_des'];
                }
            }

            // {        // 微信返回结果
            //     "return_code":"SUCCESS",
            //     "return_msg":"OK",
            //     "appid":"wx39cd0799d4567dd0",
            //     "mch_id":"1481069012",
            //     "nonce_str":"huW9eIAb5BDPn0Ma",
            //     "sign":"250316740B263FE53F5DFF50AF5A8FA1",
            //     "result_code":"SUCCESS",
            //     "transaction_id":"4200000497202004072822298902",
            //     "out_trade_no":"202010300857029180027000",
            //     "out_refund_no":"1586241595",
            //     "refund_id":"50300603862020040700031444448",
            //     "refund_channel":[],
            //     "refund_fee":"1",
            //     "coupon_refund_fee":"0",
            //     "total_fee":"1",
            //     "cash_fee":"1",
            //     "coupon_refund_count":"0",
            //     "cash_refund_fee":"1
            // }

            // {        // 支付宝返回结果
            //     "code": "10000",
            //     "msg": "Success",
            //     "buyer_logon_id": "157***@163.com",
            //     "buyer_user_id": "2088902485164146",
            //     "fund_change": "Y",
            //     "gmt_refund_pay": "2020-08-15 16:11:45",
            //     "out_trade_no": "202002460317545607015300",
            //     "refund_fee": "0.01",
            //     "send_back_fee": "0.00",
            //     "trade_no": "2020081522001464141438570535"
            // }
        }

        return true;
    }

    /**
     * 取消售后
     */
    public function refundcancel(){

        if($this->request->isAjax()){
            $id = input('id',0);

            Db::startTrans();
            $row = Db::name('order')->where('id',$id)->lock(true)->find();

            if($row['status'] != 21){
                Db::rollback();
                $this->error('订单状态有误，请勿重复提交');
            }

            //更新订单
            $update = [
                'refund_remark' => '后台取消售后',
                'status' => 1,
            ];
            $rs = Db::name('order')->where('id',$id)->update($update);
            if($rs === false){
                Db::rollback();
                $this->error('操作失败');
            }

            Db::commit();
            $this->success('取消售后完成');
        }

    }

    /**
     * 协议导出
     */
    public function xieyipdf(){
        $id = input('id');
        $info = Db::name('order')->where('id',$id)->find();
        $this->assign('info',$info);
        //
        $xieyi = Db::name('product_xieyi')->where('id',$info['xieyi_id'])->find();
        $this->assign('content',$xieyi['content']);
        //
        $this->view->engine->layout(false);
        return $this->view->fetch();
    }

}
