<?php
/**
 *  订单列表
 * @author  system
 * @version    1.0
 * @date 2018-07-12 08:32:14
 *
 */

namespace App\Http\Controllers\Admin\Order;

use App\Http\Controllers\Admin\Controller;
use App\Models\OrderInfoModel;
use App\Models\RefundInfoModel;
use App\Models\SettingInfoModel;
use App\Services\Base\Attachment;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Order\Criteria\MultiWhere;
use App\Repositories\Order\InfoRepository;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;

class InfoController extends Controller
{
    private $repository;

    public function __construct(InfoRepository $repository)
    {
        if (!$this->repository) $this->repository = $repository;
    }

    function index(Request $request)
    {
        $search['keyword'] = $request->input('keyword');
        $search['status'] = $request->input('status');

        $order = array();
        if (isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
            $order[$request['sort_field']] = $request['sort_field_by'];
        } else {
            $order['status'] = 'ASC';
            $order['id'] = 'DESC';
        }

        $list = $this->repository->with(['refundinfo','paidinfo'])->searchOrder($search, $order);
        $list = $list->get()->filter(function ($value) use ($search) {
            if ($search['status'] == 3 && count($value->refundinfo)) {
                return false;
            }
            return true;
        });
        $list = $this->paginate($list);


        return view('admin.order.info.index', compact('list'));
    }

    public function paginate($items, $perPage = 10, $page = null, $options = [])
    {
        $page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
        $items = $items instanceof Collection ? $items : Collection::make($items);
        return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
    }


    function check(Request $request)
    {
        $request = $request->all();
        $search['keyword'] = $request->input('keyword');
        $orderby = array();
        if (isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
            $orderby[$request['sort_field']] = $request['sort_field_by'];
        }
        $list = $this->repository->search($search, $orderby);
        return view('admin.order.info.check', compact('list'));
    }


    /**
     * 添加
     *
     */
    public function create(Request $request)
    {
        if ($request->method() == 'POST') {
            return $this->_createSave();
        }
        return view('admin.order.info.edit');
    }

    /**
     * 保存修改
     */
    private function _createSave()
    {
        $data = (array)request('data');
        $id = $this->repository->create($data);
        if ($id) {
            $url[] = array('url' => U('Order/Info/index'), 'title' => '返回列表');
            $url[] = array('url' => U('Order/Info/create'), 'title' => '继续添加');
            $this->showMessage('添加成功', $url);
        } else {
            $url[] = array('url' => U('Order/Info/index'), 'title' => '返回列表');
            return $this->showWarning('添加失败', $url);
        }
    }

    /**
     *
     * 修改
     *
     *
     */
    public function update(Request $request)
    {
        $id = request('id');
        $order = OrderInfoModel::find($id);
        $order->status = 2;
        $ok = $order->save();
        if ($ok) {
            return $this->showMessage('操作成功', urldecode(request('_referer')));
        } else {
            return $this->showWarning('操作失败', urldecode(request('_referer')));
        }

    }

    /**
     * 保存修改
     */
    private function _updateSave()
    {
        $data = (array)request('data');
        $ok = $this->repository->update(request('id'), $data);
        if ($ok) {
            $url[] = array('url' => U('Order/Info/index'), 'title' => '返回列表');
            return $this->showMessage('操作成功', urldecode(request('_referer')));
        } else {
            $url[] = array('url' => U('Order/Info/index'), 'title' => '返回列表');
            return $this->showWarning('操作失败', $url);
        }
    }

    public function view(Request $request)
    {
        $data = $this->repository->find(request('id'));

        if($data->photo) $photo = explode(',',$data->photo);

        return view('admin.order.info.view', compact('data','photo'));
    }


    /**
     *
     * 状态改变
     *
     */
    public function status(Request $request)
    {
        $ok = $this->repository->updateStatus(request('id'), request('status'));
        if ($ok) {
            return $this->showMessage('操作成功');
        } else {
            return $this->showWarning('操作失败');
        }
    }

    /**
     * 删除
     */
    public function destroy(Request $request)
    {
        $bool = $this->repository->destroy($request->get('id'));
        if ($bool) {
            return $this->showMessage('操作成功');
        } else {
            return $this->showWarning("操作失败");
        }
    }

    public function upload(Request $request){
        if ($request->method() == 'POST') {
            return $this->_uploadSave();
        }

        $order = OrderInfoModel::find(request('id'));

        if($order->photo) $photo = explode(',',$order->photo);


        return view('admin.order.info.upload',compact('photo','order'));
    }

    public function _uploadSave(){

        $array_photo = (array)request('photo');

        if ($array_photo && isset($array_photo['url'])) {
            $data['photo'] = '';
            foreach ($array_photo['url'] as $item) {
                if (substr($item, 0, 7) == 'http://' || substr($item, 0, 8) == 'https://') {
                    $data['photo'] .= $item . ',';
                } else {
                    $data['photo'] .= env('APP_URL', '') . $item . ',';
                }
            }

            if ($data['photo']) $data['photo'] = rtrim($data['photo'], ',');
        }else{
            $data['photo'] = '';
        }
        $order = OrderInfoModel::find(request('id'));
        $ok = $this->repository->update(request('id'), $data);

        if ($ok) {
            //操作成功，删除原来的图片
            if ($order && $order->photo) {
                $photos = explode(',', $order->photo);
                foreach ($photos as $photo) {
                    if (!in_array($photo, $array_photo['url'])) {
                        $md5 = $this->getarea($photo);
                        $attache = new Attachment();
                        $attache->deleteAttachment($md5);
                    }
                }
            }

            $url[] = array('url' => U('Order/Info/index?status=2'), 'title' => '返回列表');
            return $this->showMessage('操作成功',$url);
        } else {

            return $this->showWarning('操作失败');
        }

    }

    /***
     * 退款
     */
    public function refund(Request $request)
    {
        $settinig = SettingInfoModel::first();
        $config = [
            // 必要配置
            'app_id' => $settinig->app_id,
            'mch_id' => $settinig->mch_id,
            'key' => $settinig->api_key,   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path' => $settinig->cert_path, // XXX: 绝对路径！！！！
            'key_path' => $settinig->key_path,      // XXX: 绝对路径！！！！
        ];

        $app = Factory::payment($config);
        $orderid = request('id');
        $order = OrderInfoModel::with('paidinfo')->find($orderid);
        $out_trade_no = $order->out_trade_no;
        $total_price = $order->paidinfo->paid_price * 100;

        $refund_time = strtotime($order->updated_at);
        $schedule_time = strtotime($order->schedule_time);

        if ($schedule_time < $refund_time) {
            $refund_price = $total_price * 0.75;
        } else {
            $time = $schedule_time - $refund_time / 3600;
            $hour = 12;

            if ($time > $hour) {
                $refund_price = $total_price;
            } else {
                $refund_price = $total_price * 0.85;
            }
        }

        \Log::info($settinig->cert_path);
        $result = $app->refund->byOutTradeNumber($out_trade_no, $out_trade_no, $total_price, $refund_price, [
            'refund_desc' => $out_trade_no . '退款',
        ]);
        \Log::info($result);

        if ($result) {
            $data = [
                'refund_no' => $out_trade_no,
                'order_id' => $orderid,
                'refund_price' => $refund_price
            ];

            $ok = RefundInfoModel::create($data);
            if ($ok['return_code'] == 'SUCCESS') {
                return $this->showMessage('退款成功');
            } else {
                return $this->showWarning('操作失败,请稍后再试');
            }

        }

    }

    public function notify()
    {

    }

    /*
* 获取md5码
*/
    public function getarea($str)
    {
        $start = strripos($str, '/');
        $first = substr($str, $start + 1);
        $end = strripos($first, '.');
        $last = substr($first, 0, $end);
        return $last;
    }
}