<?php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Redis;
use Request;
use Excel;
use DB;

class OrderReturnModel extends Model
{
	protected $connection = 'order';
    protected $table = 'lie_order_return';
    protected $primaryKey = 'return_id';
    public $timestamps = false;

    // 获取退货单明细
    public function hasManyReturnItems()
    {
        return $this->hasMany('App\Model\OrderReturnItemsModel', 'return_id', 'return_id');
    }

    // 获取退货单记录
    public function hasManyReturnLog()
    {
        return $this->hasMany('App\Model\OrderReturnLogModel', 'return_id', 'return_id')->orderBy('create_time', 'desc');
    }

    // 退货导出
    public function export($request)
    {
        set_time_limit(0); 
        ini_set('memory_limit', '512M');
        
        $map = array();

        // 页面参数
        $map['order_sn']           = $request->input('order_sn', '');
        $map['time_start']         = $request->input('time_start', '');
        $map['time_end']           = $request->input('time_end', '');
        $map['apply_status']       = $request->input('apply_status', '');
        $map['order_payment_mode'] = $request->input('order_payment_mode', '');
        $map['order_goods_type']   = $request->input('order_goods_type', 1);

        $list = $this->from('lie_order_return as r')
                ->leftJoin('lie_pay_log as p', 'r.order_id', '=', 'p.order_id')
                ->where(function ($query) use ($map) {
                    // 订单编号
                    if (!empty($map['order_sn'])) {
                        $query->where('r.order_sn', '=', $map['order_sn']);
                    }
                })
                ->where(function ($query) use ($map) {
                    // 创建时间
                    if (!empty($map['time_start']) && !empty($map['time_end'])) {
                        $query->whereBetween('r.create_time', [$map['time_start'], $map['time_end']]); 
                    } else if (!empty($map['time_start'])) {
                        $query->where('r.create_time', '>', $map['time_start']);
                    } else if (!empty($map['time_end'])) {
                        $query->where('r.create_time', '<', $map['time_end']); 
                    }
                })
                ->where(function ($query) use ($map) {
                    // 订单状态
                    if (!empty($map['apply_status'])) {
                        $query->whereIn('r.status', explode(',', $map['apply_status']));
                    }
                })
                ->where(function ($query) use ($map) {
                    // 支付方式
                    if (!empty($map['order_payment_mode'])) {
                        $pay_name = explode(',', $map['order_payment_mode']);
                        $order_payment_mode = [];

                        foreach ($pay_name as $v) {
                            switch ($v) {
                                case '1': $order_payment_mode[] = '微信支付';break;
                                case '2': $order_payment_mode[] = '支付宝';break;
                                case '3': $order_payment_mode[] = '银联支付(B2B)';break;
                                case '4': $order_payment_mode[] = '银联支付(B2C)';break;
                                case '5': $order_payment_mode[] = '账期支付';break;
                                case '6': $order_payment_mode[] = '京东支付';break;
                                case '7': $order_payment_mode[] = '交通银行';break;
                                case '8': $order_payment_mode[] = '恒生银行';break;
                                case '9': $order_payment_mode[] = '钱包支付';break;
                            }
                        }

                        $query->whereIn('p.pay_name', $order_payment_mode);
                    }
                })
                ->where('r.order_goods_type', $map['order_goods_type'])
                ->select('r.return_id', 'r.return_sn', 'r.order_id', 'r.order_sn', 'r.removal_sn', 'r.user_id', 'r.mobile', 'r.email', 'r.company_name', 'r.order_goods_type', 'r.currency', 'r.return_way', 'r.pay_amount', 'r.return_amount', 'r.return_reason', 'r.bank_account', 'r.bank_name', 'r.bank_sub_name', 'r.bank_user', 'r.shipping_id', 'r.shipping_sn', 'r.status', 'r.cancel_reason', 'r.refuse_reason', 'r.create_uid', 'r.audit_uid', 'r.create_time', 'r.audit_time', 'r.putaway_time')
                ->orderBy('r.create_time', 'DESC')
                ->get()
                ->toArray();

        if (!empty($list)) {
            // 订单数据处理
            $cellData = $this->exportList($list);

            // 标题
            $headerCell = ['退货单ID', '退货单号', '订单ID', '订单编号', '出库单号', '会员账号', '公司名称', '币种', '支付金额', '退货总额', '退货原因', '退货方式', '快递名称', '快递单号', '银行账号', '银行名称', '银行支行名称', '银行开户人', '取消原因', '驳回原因', '创建人', '创建时间', '审核人', '退货处理状态', '审核时间', '退货入库时间'];  

            array_unshift($cellData, $headerCell);

            $fileName = $map['order_goods_type'] == 1 ? '联营退货单导出' : '自营退货单导出'.date('_YmdHis');

            Excel::create($fileName, function($excel) use ($cellData){
                $excel->sheet('退货单导出', function($sheet) use ($cellData){
                    $sheet->rows($cellData);
                });
            })->export('xls');
        } else {
            return redirect('/prompt')->with(['message'=>"数据为空无法导出!",'url'=>$_SERVER['HTTP_REFERER'], 'jumpTime'=>3,'status'=>false]);
        }
    }

    /**
     * 导出数据处理
     * @param  [type] $order [查询出的退货单数据]
     * @return [type]        [description]
     */
    public function exportList($return)
    {
        $tmp = array();
        $CmsModel = new CmsModel();

        for ($i = 0; $i < count($return); $i++) {
            $tmp[$i]['return_id']     = $return[$i]['return_id'];
            $tmp[$i]['return_sn']     = "\t".$return[$i]['return_sn']."\t";
            $tmp[$i]['order_id']      = $return[$i]['order_id'];
            $tmp[$i]['order_sn']      = "\t".$return[$i]['order_sn']."\t";
            $tmp[$i]['removal_sn']    = "\t".$return[$i]['removal_sn']."\t";
            $tmp[$i]['user_account']  = $return[$i]['mobile'] ? $return[$i]['mobile'] : $return[$i]['email'];
            $tmp[$i]['company_name']  = $return[$i]['company_name'];
            $tmp[$i]['currency']      = $return[$i]['currency'] == 1 ? '人民币' : '美元';
            $tmp[$i]['pay_amount']    = $return[$i]['pay_amount'];
            $tmp[$i]['return_amount'] = $return[$i]['return_amount'];
            $tmp[$i]['return_reason'] = $return[$i]['return_reason'];
            $tmp[$i]['return_way']    = $return[$i]['return_way'] == 1 ? '快递' : '自送';
            $tmp[$i]['shipping_id']   = $this->getShippingName($return[$i]['shipping_id']);
            $tmp[$i]['shipping_sn']   = $return[$i]['shipping_sn'];
            $tmp[$i]['bank_account']  = $return[$i]['bank_account'];
            $tmp[$i]['bank_name']     = $return[$i]['bank_name'];
            $tmp[$i]['bank_sub_name'] = $return[$i]['bank_sub_name'];
            $tmp[$i]['bank_user']     = $return[$i]['bank_user'];
            $tmp[$i]['cancel_reason'] = $return[$i]['cancel_reason'];
            $tmp[$i]['refuse_reason'] = $return[$i]['refuse_reason'];
            $tmp[$i]['create_uid']    = $CmsModel->getUserName($return[$i]['create_uid']);
            $tmp[$i]['create_time']   = date('Y-m-d H:i:s', $return[$i]['create_time']); 
            $tmp[$i]['audit_uid']     = $CmsModel->getUserName($return[$i]['audit_uid']);
            $tmp[$i]['status']        = Config('params.return_status')[$return[$i]['status']];
            $tmp[$i]['audit_time']    = $return[$i]['audit_time'] ? date('Y-m-d H:i:s', $return[$i]['audit_time']) : '';     
            $tmp[$i]['putaway_time']  = $return[$i]['putaway_time'] ? date('Y-m-d H:i:s', $return[$i]['putaway_time']) : '';     
        }

        return $tmp;
    }

    // 获取物流名称
    public function getShippingName($shipping_id) 
    {
        $shipping = DB::connection('order')->table('lie_shipping')->where('shipping_id', $shipping_id)->select('shipping_name')->first();

        return $shipping ? $shipping->shipping_name : '';
    }

    // 审核
    public function check($request)
    {
        $return_id   = $request->input('return_id');
        $type        = $request->input('type');
        $operator_id = $request->user->userId;

        if ($type == 2) {
            $event = '审核通过退货单';
        } else {          
            $update['refuse_reason'] = $request->input('refuse_reason');
            $event = '驳回退货单,原因:'.$update['refuse_reason'];
        }

        $update['status'] = $type;
        $update['audit_uid'] = $operator_id;
        $update['audit_time'] = time();

        try {
            DB::connection('order')->beginTransaction(); // 开启事务

            $OrderReturnLogModel = new OrderReturnLogModel();

            $this->where('return_id', $return_id)->update($update);
            $OrderReturnLogModel->addLog($return_id, $operator_id, $event);

            DB::connection('order')->commit(); // 提交事务

            return ['err_code'=>0, 'err_msg'=>'操作成功'];
        } catch(Exception $e) {
            DB::connection('order')->rollback(); // 回滚
            return ['err_code'=>1, 'err_msg'=>'操作失败,原因:'.$e->getMessage()];
        }
    }

    // 物流信息
    public function shipping($request)
    {
        $return_id   = $request->input('return_id');
        $operator_id = $request->user->userId;

        $data['shipping_id'] = $request->input('shipping_id');
        $data['shipping_sn'] = $request->input('shipping_sn');
        $data['status']      = 7; // 待收货
        $data['syn_sign']    = 1; // 标记wms同步

        try {
            DB::connection('order')->beginTransaction(); // 开启事务

            $OrderReturnLogModel = new OrderReturnLogModel();

            $this->where('return_id', $return_id)->update($data);
            $OrderReturnLogModel->addLog($return_id, $operator_id, '填写物流信息,快递名称:'.$this->getShippingName($data['shipping_id']).',快递单号:'.$data['shipping_sn']);

            DB::connection('order')->commit(); // 提交事务

            return ['err_code'=>0, 'err_msg'=>'操作成功'];
        } catch(Exception $e) {
            DB::connection('order')->rollback(); // 回滚
            return ['err_code'=>1, 'err_msg'=>'操作失败,原因:'.$e->getMessage()];
        }
    }

    // 获取活动期间已完成退款的用户金额
    public function getSelfReturnAmount($user_id, $start_time, $end_time)
    {
        return $this->where('user_id', $user_id)
                ->where('status', 10)
                ->whereBetween('putaway_time', [$start_time, $end_time])
                ->select('user_id', 'currency', 'return_amount')
                ->get()
                ->toArray();
    }

}